<?php

namespace App\Services;

use App\Entities\Configuracion\ImpresoraEtiquetaEntity;
use App\Models\Configuracion\ImpresoraEtiquetaModel;
use CodeIgniter\Config\BaseService;
use DOMDocument;
use Throwable;
use Exception;

class ImpresoraEtiquetaService extends BaseService
{

    protected ImpresoraEtiquetaModel $impresoraEtiquetaModel;
    protected array $TEST = [
        "printer" => "LABPRINT-1",
        "header" => [
            "_FORMAT" => "E:PEDIDO.ZPL",
            "_QUANTITY" => 1,
            "_PRINBTERNAME" => "Printer 1",
            "_JOBNAME" => "LBL101"
        ],
        "labels" => [
            [
                "cliente" => "Cliente Potencial",
                "titulo"  => "[1234] TEST OLIVEROS",
                "cantidad" => 100,
                "tirada"   => 50,
                "cajas" => 1,
                "ean" => null,
                "nombre" => "___Nombre___",
                "direccion" => "C/ test n10, Madrid, 12345, España",
                "notas" => "Nota....",
                "refcliente" => "Refclient:1234",
                "npedido" => "1234"
            ]
        ]
    ];

    public function __construct()
    {
        $this->impresoraEtiquetaModel = model(ImpresoraEtiquetaModel::class);
    }
    public function test(): array
    {
        try {
            $status = false;
            $content = "";
            $impresora = $this->impresoraEtiquetaModel->where("name", $this->TEST["printer"])->first();
            if ($impresora) {
                $content = $this->createEtiqueta($this->TEST);
                $status = $this->sendToImpresoraEtiqueta(1234, $content, $impresora);
            }
            return ["impresora" => $impresora, "content" => $content, "status" => $status];
        } catch (Throwable $th) {
            return ["impresora" => $impresora, "content" => $th->getMessage(), "status" => $status];
        }
    }
    protected function createEtiqueta(array $data_label = []): ?string
    {
        $xml = new DOMDocument('1.0', 'utf-8');
        $labels = $xml->createElement("labels");
        foreach ($data_label["header"] as $key => $value) {
            $labels->setAttribute($key, $value);
        }
        foreach ($data_label["labels"] as $label) {
            $labelChild = $labels->appendChild($xml->createElement('label'));
            foreach ($label as $attrName => $attributeValue) {
                $variableChild = $labels->appendChild($xml->createElement('variable'));
                $variableChild->setAttribute("name", $attrName);
                $variableChild->append((string) $attributeValue);
                $labelChild->appendChild($variableChild);
            }
        }
        $xml->appendChild($labels);
        return $xml->saveXML();
    }
    protected function sendToImpresoraEtiqueta(string $name, string $content, ImpresoraEtiquetaEntity $impresoraEtiqueta): bool
    {
        $tmpFile = tmpfile();

        fwrite($tmpFile, $content);
        rewind($tmpFile);

        $tmpMetaData = stream_get_meta_data($tmpFile);
        $conn = @ftp_connect($impresoraEtiqueta->ip,$impresoraEtiqueta->port);
        if(!$conn){
            throw new Exception('Error al establecer conexión FTP');
        }
        $isLoginSuccess = @ftp_login($conn, $impresoraEtiqueta->user, $impresoraEtiqueta->pass);
        if ($isLoginSuccess) {
        } else {
            throw new Exception('Error haciendo login en el servidor FTP');
        }
        if (!ftp_pasv($conn, true)) {
            throw new Exception('Error entrando en modo pasivo');
        }
        if (ftp_put($conn, $name, $tmpMetaData['uri'], FTP_ASCII) === FALSE) {
            $status = false;
            ftp_close($conn);
        }else{
            $status = true;
        }
        
        return $status;
    }
}
