<?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;

// Helper functions to replace php_printer functionality
function cutString($text, $maxLength) {
    return substr($text, 0, $maxLength);
}

function printLine($printer, $text, $width = 48) {
    $printer->text(str_pad($text, $width) . "\n");
}

function printAlignedText($printer, $leftText, $rightText, $width = 48) {
    $rightLen = strlen($rightText);
    $leftLen = $width - $rightLen;
    $leftPadded = str_pad($leftText, $leftLen, " ", STR_PAD_RIGHT);
    $printer->text($leftPadded . $rightText . "\n");
}

function printSeparatorLine($printer, $char = "-", $width = 48) {
    $printer->text(str_repeat($char, $width) . "\n");
}

// Check if this is a POST request with corte data
$dataPrint = null;
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST["dataPrint"])) {
    $dataPrint = json_decode($_POST["dataPrint"], true);
}

// If no POST data, assume variables are already set (for CodeIgniter compatibility)
if ($dataPrint) {
    // Extract data from POST
    $printCorteFiscal = $dataPrint['printCorteFiscal'] ?? true;
    $PRINTER_NAME = $dataPrint['printer'] ?? 'POS-80C';
    $numero_corte = $dataPrint['numero_corte'] ?? '';
    $nombre_empresa = $dataPrint['nombre_empresa'] ?? '';
    $rsocial_empresa = $dataPrint['rsocial_empresa'] ?? '';
    $direcion_empresa = $dataPrint['direcion_empresa'] ?? '';
    $nrc_empresa = $dataPrint['nrc_empresa'] ?? '';
    $nit_empresa = $dataPrint['nit_empresa'] ?? '';
    $doc_resolucion = $dataPrint['doc_resolucion'] ?? '';
    $doc_desde = $dataPrint['doc_desde'] ?? '';
    $doc_hasta = $dataPrint['doc_hasta'] ?? '';
    $cajero = $dataPrint['cajero'] ?? '';
    $tipo_corte = $dataPrint['tipo_corte'] ?? '';
    $fecha = $dataPrint['fecha'] ?? '';
    $dataCorteFiscal = $dataPrint['dataCorteFiscal'] ?? [];
}

if ($printCorteFiscal) {
    try {
        $connector = new WindowsPrintConnector($PRINTER_NAME);
        $printer = new Printer($connector);
        
        // COMPANY HEADER
        $printer->setJustification(Printer::JUSTIFY_CENTER);
        $printer->setTextSize(2, 2);
        $printer->text(cutString(strtoupper($nombre_empresa), 21) . "\n");
        
        $printer->setTextSize(1, 1);
        $printer->text(cutString(strtoupper($rsocial_empresa), 45) . "\n");
        $printer->text(cutString(strtoupper($direcion_empresa), 45) . "\n");
        $printer->text(cutString(strtoupper("NRC: " . $nrc_empresa), 45) . "\n");
        $printer->text(cutString(strtoupper("NIT: " . $nit_empresa), 45) . "\n");
        $printer->text(cutString(strtoupper("Vendedor: " . $cajero), 45) . "\n");
        
        $printer->text("\n");
        $printer->setEmphasis(true);
        $printer->text(cutString(strtoupper("TOTAL " . $tipo_corte), 45) . "\n");
        $printer->setEmphasis(false);
        $printer->text("\n");
        
        $printer->text(cutString("Reporte No: " . $numero_corte, 45) . "\n");
        printSeparatorLine($printer);
        
        // TICKETS SECTION
        $printer->setJustification(Printer::JUSTIFY_LEFT);
        printAlignedText($printer, "Total Gravadas:", "$" . number_format($dataCorteFiscal['total_ticket_grabado'], 2));
        printAlignedText($printer, "Total Exentas:", "$" . number_format($dataCorteFiscal['total_ticket_exento'], 2));
        printAlignedText($printer, "Total No Sujeto:", "$" . number_format($dataCorteFiscal['total_ticket_nosujeto'], 2));
        printAlignedText($printer, "Total Tickets:", "$" . number_format(($dataCorteFiscal['total_ticket_grabado'] + $dataCorteFiscal['total_ticket_exento'] + $dataCorteFiscal['total_ticket_nosujeto']), 2));
        
        printSeparatorLine($printer);
        
        // PROPINA SECTION
        printAlignedText($printer, "Total Propina:", "$" . number_format(($dataCorteFiscal['total_propina_declarada'] + $dataCorteFiscal['total_propina_declarada_pos']), 2));
        
        printSeparatorLine($printer);
        
        // FACTURA SECTION
        printAlignedText($printer, "Total Gravadas:", "$" . number_format($dataCorteFiscal['total_factura_grabado'], 2));
        printAlignedText($printer, "Total Exentas:", "$" . number_format($dataCorteFiscal['total_factura_exento'], 2));
        printAlignedText($printer, "Total No Sujeto:", "$" . number_format($dataCorteFiscal['total_factura_nosujeto'], 2));
        printAlignedText($printer, "Total Factura:", "$" . number_format(($dataCorteFiscal['total_factura_grabado'] + $dataCorteFiscal['total_factura_exento'] + $dataCorteFiscal['total_factura_nosujeto']), 2));
        
        printSeparatorLine($printer);
        
        // CCF SECTION
        printAlignedText($printer, "Total Gravadas:", "$" . number_format($dataCorteFiscal['total_ccf_grabado'], 2));
        printAlignedText($printer, "Total Exentas:", "$" . number_format($dataCorteFiscal['total_ccf_exento'], 2));
        printAlignedText($printer, "Total No Sujeto:", "$" . number_format($dataCorteFiscal['total_ccf_nosujeto'], 2));
        printAlignedText($printer, "Total CCF:", "$" . number_format(($dataCorteFiscal['total_ccf_grabado'] + $dataCorteFiscal['total_ccf_exento'] + $dataCorteFiscal['total_ccf_nosujeto']), 2));
        
        printSeparatorLine($printer);
        
        $total_ventas = $dataCorteFiscal['total_propina_declarada'] + $dataCorteFiscal['total_propina_declarada_pos'] + 
                       $dataCorteFiscal['total_ticket_grabado'] + $dataCorteFiscal['total_ticket_exento'] + $dataCorteFiscal['total_ticket_nosujeto'] +
                       $dataCorteFiscal['total_factura_grabado'] + $dataCorteFiscal['total_factura_exento'] + $dataCorteFiscal['total_factura_nosujeto'] +
                       $dataCorteFiscal['total_ccf_grabado'] + $dataCorteFiscal['total_ccf_exento'] + $dataCorteFiscal['total_ccf_nosujeto'];
        
        // DEVOLUCIONES SECTION
        printAlignedText($printer, "Dev. Tickets:", "$" . number_format($dataCorteFiscal['total_devolucion_ticket'], 2));
        printAlignedText($printer, "Anulacion Fac.:", "$" . number_format($dataCorteFiscal['total_devolucion_factura'], 2));
        printAlignedText($printer, "Anulacion CCF:", "$" . number_format($dataCorteFiscal['total_devolucion_ccf'], 2));
        printAlignedText($printer, "Anulacion N de Cred:", "$" . number_format($dataCorteFiscal['total_devolucion_ncredito'], 2));
        
        $total_devs = $dataCorteFiscal['total_devolucion_ticket'] + $dataCorteFiscal['total_devolucion_factura'] + 
                     $dataCorteFiscal['total_devolucion_ccf'] + $dataCorteFiscal['total_devolucion_ncredito'];
        
        printAlignedText($printer, "Total Devoluciones:", "($" . number_format($total_devs, 2) . ")");
        printSeparatorLine($printer);
        
        // TOTAL SECTION
        $printer->setEmphasis(true);
        printAlignedText($printer, "Total Ventas:", "$" . number_format(($total_ventas - $total_devs), 2));
        $printer->setEmphasis(false);
        printSeparatorLine($printer);
        
        $printer->text("\n");
        
        // CONTADORES SECTION
        $trans = $dataCorteFiscal['total_trans_ticket'] + $dataCorteFiscal['total_trans_ticket_dev'] + 
                $dataCorteFiscal['total_trans_factura'] + $dataCorteFiscal['total_trans_ccf'];
        
        printAlignedText($printer, "Trans. Realizadas:", (string)$trans);
        printAlignedText($printer, "Tickets Emitidos:", (string)($dataCorteFiscal['total_trans_ticket'] + $dataCorteFiscal['total_trans_ticket_dev']));
        printAlignedText($printer, "Dev.(Tickets):", (string)$dataCorteFiscal['total_trans_ticket_dev']);
        printAlignedText($printer, "Inicio:", (string)$dataCorteFiscal['ticketInicio']);
        printAlignedText($printer, "Final:", (string)$dataCorteFiscal['ticketFin']);
        printAlignedText($printer, "Facturas Emitidas:", (string)$dataCorteFiscal['total_trans_factura']);
        printAlignedText($printer, "CCF Emitidos:", (string)$dataCorteFiscal['total_trans_ccf']);
        
        $printer->text("\n");
        
        // CAJERO Y FECHA
        $printer->text("Cajero: " . $cajero . "\n");
        $printer->text($fecha . "\n");
        $printer->text("\n");
        
        $printer->setJustification(Printer::JUSTIFY_CENTER);
        $printer->setEmphasis(true);
        $printer->text("***Operacion Finalizada***\n");
        $printer->setEmphasis(false);
        
        $printer->setTextSize(1, 1);
        $printer->text(cutString(strtoupper($nombre_empresa), 45) . "\n");
        
        // CORTAR PAPEL Y CERRAR IMPRESORA
        $printer->feed(2);
        $printer->cut();
        $printer->close();
        
        echo json_encode([
            "status" => "success",
            "message" => "Corte impreso correctamente."
        ]);
        
    } catch (Exception $e) {
        echo json_encode([
            "status" => "error",
            "message" => "Error al imprimir: " . $e->getMessage()
        ]);
    }
}
?>