<?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);
    
    // Log para depuración
    error_log("=== DATOS RECIBIDOS EN CORTE_8.PHP ===");
    error_log("dataPrint completo: " . print_r($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'] ?? '';
    $dotacion = $dataPrint['dotacion'] ?? 0;
    $dataCorteFiscal = $dataPrint['dataCorteFiscal'] ?? [];
    
    // Log de dataCorteFiscal
    error_log("dataCorteFiscal: " . print_r($dataCorteFiscal, true));
}

if ($printCorteFiscal && !empty($dataCorteFiscal)) {
    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'] ?? 0, 2));
        printAlignedText($printer, "Total Exentas:", "$" . number_format($dataCorteFiscal['total_ticket_exento'] ?? 0, 2));
        printAlignedText($printer, "Total No Sujeto:", "$" . number_format($dataCorteFiscal['total_ticket_nosujeto'] ?? 0, 2));
        $total_tickets = ($dataCorteFiscal['total_ticket_grabado'] ?? 0) + ($dataCorteFiscal['total_ticket_exento'] ?? 0) + ($dataCorteFiscal['total_ticket_nosujeto'] ?? 0);
        printAlignedText($printer, "Total Tickets:", "$" . number_format($total_tickets, 2));
        printSeparatorLine($printer);
        
        // FACTURA SECTION
        $total_factura = ($dataCorteFiscal['total_factura_grabado'] ?? 0) + ($dataCorteFiscal['total_factura_exento'] ?? 0) + ($dataCorteFiscal['total_factura_nosujeto'] ?? 0);
        printAlignedText($printer, "Total Facturas:", "$" . number_format($total_factura, 2));
        printSeparatorLine($printer);
        printAlignedText($printer, "Total Gravadas:", "$" . number_format($dataCorteFiscal['total_factura_grabado'] ?? 0, 2));
        printAlignedText($printer, "Total Exentas:", "$" . number_format($dataCorteFiscal['total_factura_exento'] ?? 0, 2));
        printAlignedText($printer, "Total No Sujeto:", "$" . number_format($dataCorteFiscal['total_factura_nosujeto'] ?? 0, 2));
        printSeparatorLine($printer);
        
        // CCF SECTION
        $total_ccf = ($dataCorteFiscal['total_ccf_grabado'] ?? 0) + ($dataCorteFiscal['total_ccf_exento'] ?? 0) + ($dataCorteFiscal['total_ccf_nosujeto'] ?? 0);
        printAlignedText($printer, "Total CCF:", "$" . number_format($total_ccf, 2));
        printSeparatorLine($printer);
        printAlignedText($printer, "Total Gravadas:", "$" . number_format($dataCorteFiscal['total_ccf_grabado'] ?? 0, 2));
        printAlignedText($printer, "Total Exentas:", "$" . number_format($dataCorteFiscal['total_ccf_exento'] ?? 0, 2));
        printAlignedText($printer, "Total No Sujeto:", "$" . number_format($dataCorteFiscal['total_ccf_nosujeto'] ?? 0, 2));
        printSeparatorLine($printer);
        
        // DEVOLUCIONES SECTION
        $total_devs = ($dataCorteFiscal['total_devolucion_ticket'] ?? 0) + ($dataCorteFiscal['total_devolucion_factura'] ?? 0) + 
                     ($dataCorteFiscal['total_devolucion_ccf'] ?? 0) + ($dataCorteFiscal['total_devolucion_ncredito'] ?? 0);
        
        printAlignedText($printer, "Total Devoluciones:", "($" . number_format($total_devs, 2) . ")");
        printSeparatorLine($printer);
        printAlignedText($printer, "Dev. Tickets:", "$" . number_format($dataCorteFiscal['total_devolucion_ticket'] ?? 0, 2));
        printAlignedText($printer, "Anulacion Fac.:", "$" . number_format($dataCorteFiscal['total_devolucion_factura'] ?? 0, 2));
        printAlignedText($printer, "Anulacion CCF:", "$" . number_format($dataCorteFiscal['total_devolucion_ccf'] ?? 0, 2));
        printAlignedText($printer, "Anulacion N de Cred:", "$" . number_format($dataCorteFiscal['total_devolucion_ncredito'] ?? 0, 2));
        printSeparatorLine($printer);
        
        // RECIBOS SECTION
        if (isset($dataCorteFiscal['total_recibo']) && $dataCorteFiscal['total_recibo'] > 0) {
            printAlignedText($printer, "Total Recibos:", "$" . number_format($dataCorteFiscal['total_recibo'], 2));
            printSeparatorLine($printer);
            if (isset($dataCorteFiscal['total_trans_recibo']) && $dataCorteFiscal['total_trans_recibo'] > 0) {
                printAlignedText($printer, "Recibos Emitidos:", (string)$dataCorteFiscal['total_trans_recibo']);
                printSeparatorLine($printer);
            }
        }
        
        // PROPINA TOTAL
        $total_propina_general = ($dataCorteFiscal['total_propina'] ?? 0) + ($dataCorteFiscal['total_propina_pos'] ?? 0);
        printAlignedText($printer, "Total Propina:", "$" . number_format($total_propina_general, 2));
        printSeparatorLine($printer);
        
        // TOTAL EN VENTAS
        $total_recibo_val = isset($dataCorteFiscal['total_recibo_sin_propina']) ? $dataCorteFiscal['total_recibo_sin_propina'] : (isset($dataCorteFiscal['total_recibo']) ? $dataCorteFiscal['total_recibo'] : 0);
        $total_en_ventas = $total_propina_general + $total_factura + $total_ccf + $total_recibo_val - $total_devs;
        
        $printer->setEmphasis(true);
        printAlignedText($printer, "TOTAL EN VENTAS:", "$" . number_format($total_en_ventas, 2));
        $printer->setEmphasis(false);
        printSeparatorLine($printer);
        
        // CONTADORES DE DOCUMENTOS
        printAlignedText($printer, "Facturas Emitidas:", (string)($dataCorteFiscal['total_trans_factura'] ?? 0));
        printAlignedText($printer, "CCF Emitidos:", (string)($dataCorteFiscal['total_trans_ccf'] ?? 0));
        $trans_realizadas = ($dataCorteFiscal['total_trans_factura'] ?? 0) + ($dataCorteFiscal['total_trans_ccf'] ?? 0) + 
                           ($dataCorteFiscal['total_trans_ncredito'] ?? 0) + ($dataCorteFiscal['total_trans_ticket'] ?? 0) + 
                           ($dataCorteFiscal['total_trans_ticket_dev'] ?? 0);
        printAlignedText($printer, "Transacciones realizadas:", (string)$trans_realizadas);
        printSeparatorLine($printer);
        
        // TOTAL VENTAS EFECTIVO + PROPINA
        printAlignedText($printer, "Total Efectivo + Propina:", "$" . number_format($dataCorteFiscal['total_ventas_efectivo'] ?? 0, 2));
        printSeparatorLine($printer);
        
        // TOTAL EN EFECTIVO CC
        printAlignedText($printer, "Total Efectivo CC:", "$" . number_format($dataCorteFiscal['total_ventas_efectivo_cc'] ?? 0, 2));
        printSeparatorLine($printer);
        
        // TOTAL PROPINA EN EFECTIVO
        printAlignedText($printer, "Total Propina Efectivo:", "$" . number_format($dataCorteFiscal['total_propina'] ?? 0, 2));
        printSeparatorLine($printer);
        
        // TOTAL VENTAS POS + PROPINA
        printAlignedText($printer, "Total POS + Propina:", "$" . number_format($dataCorteFiscal['total_ventas_pos'] ?? 0, 2));
        printSeparatorLine($printer);
        
        // TOTAL EN POS CC
        printAlignedText($printer, "Total POS CC:", "$" . number_format($dataCorteFiscal['total_ventas_pos_cc'] ?? 0, 2));
        printSeparatorLine($printer);
        
        // TOTAL PROPINA POS
        printAlignedText($printer, "Total Propina POS:", "$" . number_format($dataCorteFiscal['total_propina_pos'] ?? 0, 2));
        printSeparatorLine($printer);
        
        // CAJA CHICA
        $total_caja_chica = isset($dataCorteFiscal['total_caja_chica']) ? $dataCorteFiscal['total_caja_chica'] : 0;
        $total_ingresos_cc = isset($dataCorteFiscal['total_ingresos_cc']) ? $dataCorteFiscal['total_ingresos_cc'] : 0;
        $total_egresos_cc = isset($dataCorteFiscal['total_egresos_cc']) ? $dataCorteFiscal['total_egresos_cc'] : 0;
        
        printAlignedText($printer, "Total en Caja Chica:", "$" . number_format($total_caja_chica, 2));
        printSeparatorLine($printer);
        printAlignedText($printer, "+ Ingresos / Reposiciones:", "$" . number_format($total_ingresos_cc, 2));
        printAlignedText($printer, "- Gastos / Egresos:", "($" . number_format($total_egresos_cc, 2) . ")");
        printSeparatorLine($printer);
        
        // DOTACION
        printAlignedText($printer, "Dotacion:", "$" . number_format($dotacion, 2));
        printSeparatorLine($printer);
        
        // TOTAL EFECTIVO CAJA
        $total_efectivo_caja = $dotacion + ($dataCorteFiscal['total_ventas_efectivo'] ?? 0) + 
                              ($dataCorteFiscal['total_ventas_efectivo_cc'] ?? 0) - $total_egresos_cc + $total_ingresos_cc;
        printAlignedText($printer, "Total Efectivo Caja:", "$" . number_format($total_efectivo_caja, 2));
        $printer->text("(Efectivo + Dotacion +- Caja Chica)\n");
        printSeparatorLine($printer);
        
        // 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()
        ]);
    }
}
?>