<?php

namespace App\Libraries;

use App\Models\Pedidos\PedidoLineaModel;
use App\Models\Presupuestos\PresupuestoFicheroModel;
use Exception;
use phpseclib3\Net\SFTP;

class SafekatFtpClient
{
    protected SFTP $ftp;
    protected string $host;
    protected int $port;
    protected string $username;
    protected string $password;
    protected string $base_dir;
    protected bool $xml_enabled;
    protected object $pedido_xml_config;

    public function __construct()
    {
        $this->pedido_xml_config = config("PedidoXML");
        $this->host = $this->pedido_xml_config->host;
        $this->username = $this->pedido_xml_config->username;
        $this->password = $this->pedido_xml_config->password;
        $this->port = $this->pedido_xml_config->port;
        $this->base_dir = $this->pedido_xml_config->base_dir;
        $this->xml_enabled = $this->pedido_xml_config->xml_enabled;
        $this->ftp = new SFTP($this->host);

    }
    /**
     * Upload the content of $filename to the base directory declared in App\Config\FTP.php
     *
     * @param string $content
     * @param string $filename
     * @return boolean
     */
    public function uploadXML(string $content, string $filename): bool
    {
        try {
            if ($this->xml_enabled == false) return false;
            $remotePath = implode("/", [$this->base_dir,'pedidos','xml_nuevos']);
            $this->ftp->login(username: $this->username, password: $this->password);
            if(!$this->ftp->is_dir($remotePath)){
                $this->ftp->mkdir($remotePath,recursive:true);
            }
            $this->ftp->put($remotePath.'/'.$filename, $content);

            return true;
        } catch (\Throwable $th) {
            throw $th;
            log_message('error', $th->getMessage());
            return false;
        }
    }
    public function uploadFilePresupuesto(int $presupuesto_id)
    {
        try {
            if ($this->xml_enabled == false) return false;
            $model = model(PresupuestoFicheroModel::class);
            $modelPedidoLinea = model(PedidoLineaModel::class);
            $pedidoLinea = $modelPedidoLinea->findByPresupuesto($presupuesto_id);
            $rootIdExtern = $this->pedido_xml_config->id_offset + $pedidoLinea->pedido_id;
            $presupuestoFiles = $model->getFiles($presupuesto_id);
            $this->ftp->login(username: $this->username, password: $this->password);
            
            foreach ($presupuestoFiles as $key => $value) {
                $filename = array_reverse(explode("/", $value->file_path))[0];
                $remoteDir = implode("/", [$this->base_dir,"pedidos_files",$rootIdExtern]);
                $remoteFile = implode("/", [$this->base_dir,"pedidos_files",$rootIdExtern,$filename]);
                if(!$this->ftp->is_dir($remoteDir)){
                    $this->ftp->mkdir($remoteDir,recursive:true);
                }
                $this->ftp->put($remoteFile,$value->file_path,mode:$this->ftp::SOURCE_LOCAL_FILE);
            }
            $this->ftp->disconnect();
        } catch (Exception $e) {
            log_message('error', $e->getMessage());
            throw $e;
        }
    }
    public function removeFiles(int $presupuesto_id)
    {
        try {
            // if ($this->xml_enabled == false) return false;
            $model = model(PresupuestoFicheroModel::class);
            $modelPedidoLinea = model(PedidoLineaModel::class);
            $pedidoLinea = $modelPedidoLinea->findByPresupuesto($presupuesto_id);
            $rootIdExtern = $this->pedido_xml_config->id_offset + $pedidoLinea->pedido_id;
            $presupuestoFiles = $model->getFiles($presupuesto_id);
            $this->ftp->login(username: $this->username, password: $this->password);
            
            foreach ($presupuestoFiles as $key => $value) {
                $filename = array_reverse(explode("/", $value->file_path))[0];
                $remoteFile = implode("/", [$this->base_dir,"pedidos_files",$rootIdExtern,$filename]);
                $this->ftp->delete($remoteFile);
            }
            $this->ftp->disconnect();
        } catch (Exception $e) {
            log_message('error', $e->getMessage());
            throw $e;
        }
    }
}
