<?php
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
    http_response_code(204); // Sin contenido
    exit;
}

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', '/logs/error.log');

require __DIR__ . '/vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;

$dataPrint = json_decode($_POST["dataPrint"]);

if($dataPrint && json_last_error() === JSON_ERROR_NONE) {
    //Printer Name
    $PRINTER_NAME = $dataPrint->printer ?? 'POS-80C';
    //CONFIGURACIONES
    $maxDescripcion = 27; //Maximo de caracteres por linea para la descripcion del producto
    $anchoTicket = 48; //Ancho del ticket en caracteres
   
    //DATOS
    $nombreEmpresa = $dataPrint->empresa;
    $concepto = $dataPrint->concepto;
    $fecha = date("d/m/Y H:i:s", strtotime($dataPrint->fecha)) ?? null;

    try {
        $connector = new WindowsPrintConnector($PRINTER_NAME);
        $printer = new Printer($connector);
        $printer->setJustification(Printer::JUSTIFY_CENTER);
        $printer->setTextSize(2, 2);
        $printer->text("$nombreEmpresa\n");
        $printer->setTextSize(1, 1);
        $printer->text("$concepto\n");
        $printer->text("Fecha: ".$fecha." \n");
        $printer->setJustification(Printer::JUSTIFY_LEFT);
        $printer->text("\n");
        //PRODUCTOS
        $printer->setEmphasis(true);
        $printer->text("Descripcion                Cant   Costo  Total\n");
        $printer->text(str_repeat("-", $anchoTicket) . "\n");
        $printer->setEmphasis(false);


        if (isset($dataPrint->productos) && is_array($dataPrint->productos)) {
            foreach ($dataPrint->productos as $producto) {
                $cantidad = str_pad(number_format($producto->cant, 2), 4, " ", STR_PAD_RIGHT);
                $costo = str_pad(number_format($producto->costo, 4), 7, " ", STR_PAD_LEFT);
                $total = str_pad(number_format($producto->cant * $producto->costo, 4), 7, " ", STR_PAD_LEFT);

                $descripcion = wordwrap(($producto->sku ?? '') . ' - ' . ($producto->desc ?? ''), $maxDescripcion, "\n", true);
                $lineasDescripcion = explode("\n", $descripcion);

                // Imprimir primera línea con cantidad, precio y total
                $printer->text(str_pad($lineasDescripcion[0], $maxDescripcion, " ") . "$cantidad " .  $costo . " $total\n");

                // Imprimir líneas adicionales de la descripción (si hay más)
                for ($i = 1; $i < count($lineasDescripcion); $i++) {
                    $printer->text(str_pad($lineasDescripcion[$i], $maxDescripcion) . "\n");
                }
                 $printer->text(str_repeat("-", $anchoTicket) . "\n");
            }
        }
        $printer->text("\n");
        $printer->text("IMPRESO: \n");
        $printer->text(gmdate('Y-m-d H:i:s',strtotime('- 6 hours')) . " Por: " . ($dataPrint->usuario ?? 'Desconocido') . "\n");

        $printer->text("\n");
        $printer->text(str_pad("Notas de salida: ", $anchoTicket, "_", STR_PAD_RIGHT) . "\n");
        $printer->text(str_repeat("_", $anchoTicket) . "\n");
        $printer->text(str_repeat("_", $anchoTicket) . "\n");
        $printer->text("\n");
        $printer->text(str_pad("Recibido por: ", $anchoTicket, "_", STR_PAD_RIGHT) . "\n");
        $printer->text(str_pad("Notas de recepción: ", $anchoTicket, "_", STR_PAD_RIGHT) . "\n");
        $printer->text(str_repeat("_", $anchoTicket) . "\n");
        $printer->text(str_repeat("_", $anchoTicket) . "\n");

        $printer->text("\n");
        $printer->setJustification(Printer::JUSTIFY_CENTER);
        $printer->text(str_pad("Fin de operación", $anchoTicket, " * ", STR_PAD_BOTH) . "\n");



        $printer->feed(2);
        $printer->cut();
        $printer->close();

    }
    catch (Exception $e) {
        echo json_encode([
            "status" => "error",
            "message" => "Error al imprimir: " . $e->getMessage()
        ]);
    }
    /*print_r($dataPrint);
    $empresa = $dataPrint['empresa'] ?? '';
    $concepto = $dataPrint['concepto'] ?? '';  
    $productos = $dataPrint['productos'] ?? null;
    print_r($empresa);
    echo "<hr>";
    print_r($concepto);
    echo "<hr>";
    print_r($productos);*/
}