<?php
// api/controllers/reportes.php
header("Content-Type: application/pdf");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

require_once dirname(__DIR__) . '/vendor/tcpdf/tcpdf.php';
require_once dirname(__DIR__) . '/config/database.php';

// Initialize DB
$database = new Database();
$db = $database->getConnection();

$id_orden = $_GET['id'] ?? null;
if (!$id_orden) {
    http_response_code(400);
    echo "ID de orden es requerido.";
    exit;
}

// 1. Load configuration
$queryConf = "SELECT clave, valor FROM configuracion";
$stmtConf = $db->query($queryConf);
$config = [];
if ($stmtConf) {
    while ($rowConf = $stmtConf->fetch(PDO::FETCH_ASSOC)) {
        $config[$rowConf['clave']] = $rowConf['valor'];
    }
}

// Set Timezone
if (!empty($config['zona_horaria'])) {
    date_default_timezone_set($config['zona_horaria']);
} else {
    date_default_timezone_set('America/Puerto_Rico');
}

$empresa_nombre = $config['empresa_nombre'] ?? 'Lavandería y Sastrería PR';
$empresa_telefono = $config['empresa_telefono'] ?? '(787) 555-0000';
$empresa_email = $config['empresa_email'] ?? 'contacto@laundryexpress.com';
$empresa_direccion = $config['empresa_direccion'] ?? 'Calle 34 #7534';
$formato_fecha = $config['formato_fecha'] ?? 'm/d/Y';
$recibo_footer = $config['recibo_footer'] ?? "Gracias por preferirnos, vuelva pronto...";
$moneda = $config['moneda'] ?? 'USD';

// Parse taxes JSON
$taxes_json = $config['system_taxes'] ?? '[{"name":"IVU Estatal","rate":"10.5"},{"name":"IVU Municipal","rate":"1.0"}]';
$active_taxes = json_decode($taxes_json, true);
if (!is_array($active_taxes)) {
    $active_taxes = [
        ["name" => "IVU Estatal", "rate" => "10.5"],
        ["name" => "IVU Municipal", "rate" => "1.0"]
    ];
}

// 2. Fetch Order details
$query = "SELECT o.*, c.full_name as cliente_nombre, c.phone as cliente_telefono, c.email as cliente_email
          FROM orders o
          JOIN customers c ON o.customer_id = c.id
          WHERE o.id = ?";
$stmt = $db->prepare($query);
$stmt->execute([$id_orden]);
$orden = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$orden) {
    http_response_code(404);
    echo "Orden no encontrada";
    exit;
}

// 3. Fetch Items
$tagColumn = "'' AS tag_code";
$garmentColumn = "1 AS garment_count";
try {
    $columnCheck = $db->query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'order_items' AND COLUMN_NAME IN ('tag_code', 'garment_count')");
    $columns = $columnCheck ? $columnCheck->fetchAll(PDO::FETCH_COLUMN) : [];
    if (in_array('tag_code', $columns, true)) {
        $tagColumn = "oi.tag_code AS tag_code";
    }
    if (in_array('garment_count', $columns, true)) {
        $garmentColumn = "oi.garment_count AS garment_count";
    }
} catch (Exception $e) {}

$queryItems = "SELECT oi.id, oi.order_id, oi.service_id, oi.quantity, oi.unit_price, oi.line_total as subtotal, oi.descripcion_item, $tagColumn, $garmentColumn, s.service_name as servicio_nombre
               FROM order_items oi
               JOIN services s ON oi.service_id = s.id
               WHERE oi.order_id = ?";
$stmtItems = $db->prepare($queryItems);
$stmtItems->execute([$id_orden]);
$items = $stmtItems->fetchAll(PDO::FETCH_ASSOC);

// 4. Ticket layout dimensions (80mm wide)
$W   = 80;   // Page width (mm)
$ML  = 4;    // Left margin
$MR  = 4;    // Right margin
$IW  = $W - $ML - $MR; // Usable width = 72mm

// Helper function to format money in PHP
function formatMoney($val, $moneda) {
    $symbol = '$';
    if ($moneda === 'EUR') $symbol = '€';
    return $symbol . number_format((float)$val, 2);
}

// Process logo if exists
$logo_img = null;
$logo_type = '';
if (!empty($config['empresa_logo'])) {
    if (preg_match('/^data:image\/([a-zA-Z0-9\+\-\.]+);base64,(.+)$/s', $config['empresa_logo'], $matches)) {
        $mime_type = strtolower($matches[1]);
        $logo_img = base64_decode($matches[2]);
        if ($mime_type === 'svg+xml') {
            $logo_type = 'svg';
        } elseif ($mime_type === 'jpeg') {
            $logo_type = 'jpg';
        } else {
            $logo_type = $mime_type;
        }
    }
}

// Dynamic height calculation
$baseHeight = 125;
if ($logo_img) {
    $baseHeight += 16;
}
foreach ($items as $item) {
    $baseHeight += 12;
    if (!empty(trim($item['tag_code'] ?? ''))) {
        $baseHeight += 4;
    }
    if ((int)($item['garment_count'] ?? 1) > 1) {
        $baseHeight += 4;
    }
}
if (!empty(trim($orden['notes'] ?? ''))) {
    $baseHeight += 16;
}
// Add height for terms
$footer_lines_count = substr_count($recibo_footer, "\n") + 1;
$baseHeight += ($footer_lines_count * 4) + 12;
$baseHeight = max(145, $baseHeight);

$pdf = new TCPDF('P', 'mm', array($W, $baseHeight), true, 'UTF-8', false);
$pdf->SetMargins($ML, 4, $MR);
$pdf->SetAutoPageBreak(false);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();

$pdf->SetFont('freesans', '', 8);

// Render logo SVG or image if available (centered, 30mm width, 15mm height)
if ($logo_img) {
    if ($logo_type === 'svg') {
        $pdf->ImageSVG('@' . $logo_img, ($W - 30)/2, 4, 30, 15, '', '', '', 0, false);
    } else {
        $pdf->Image('@' . $logo_img, ($W - 30)/2, 4, 30, 15, $logo_type);
    }
    $pdf->Ln(16);
} else {
    $pdf->Ln(2);
}

// Find payment method used
$queryPayment = "SELECT method FROM payments WHERE order_id = ? LIMIT 1";
$stmtPayment = $db->prepare($queryPayment);
$stmtPayment->execute([$id_orden]);
$payment = $stmtPayment->fetch(PDO::FETCH_ASSOC);

$metodo_pago = '';
if ($payment) {
    $metodo_pago = $payment['method'];
}

// Determine status label and style
if ($orden['status'] === 'delivered') {
    $pago_texto = '[ PAGADO' . (!empty($metodo_pago) ? ' - ' . strtoupper($metodo_pago) : '') . ' ]';
    $pago_color = '#10b981'; // Green
} else {
    if ($payment) {
        $pago_texto = '[ PAGADO' . (!empty($metodo_pago) ? ' - ' . strtoupper($metodo_pago) : '') . ' ]';
        $pago_color = '#10b981';
    } else {
        $pago_texto = '[ PENDIENTE DE PAGO ]';
        $pago_color = '#ef4444';
    }
}

// Build HTML
$html_ticket = '
<style>
    .ticket-container { width: 100%; text-align: center; }
    .company-name { font-size: 11px; font-weight: bold; color: #0f172a; }
    .ticket-title { font-size: 7px; font-weight: bold; color: #64748b; letter-spacing: 0.5px; }
    .company-info { font-size: 6.5px; color: #475569; }
    .meta-table { width: 100%; font-size: 7px; margin-top: 4px; }
    .client-info { font-size: 7px; border-top: 1px dashed #cbd5e1; border-bottom: 1px dashed #cbd5e1; text-align: left; padding: 3px 0; margin-top: 3px; }
    .items-table { width: 100%; font-size: 7px; margin-top: 4px; border-collapse: collapse; }
    .item-header { font-weight: bold; background-color: #f1f5f9; }
    .totals-table { width: 100%; font-size: 7px; border-top: 1px solid #cbd5e1; margin-top: 4px; }
    .status-badge { font-weight: bold; font-size: 8px; text-align: center; margin-top: 4px; }
    .footer-text { font-size: 6px; color: #94a3b8; text-align: left; margin-top: 5px; }
</style>
<div class="ticket-container">
    <span class="company-name">' . htmlspecialchars($empresa_nombre) . '</span><br />
    <span class="ticket-title">COMPROBANTE DE SERVICIO</span><br />
    <span class="company-info">' . htmlspecialchars($empresa_direccion) . '<br />Tel: ' . htmlspecialchars($empresa_telefono) . '</span>
</div>

<table class="meta-table" cellpadding="1">
    <tr>
        <td style="width: 50%;"><b>ORDEN:</b> ' . htmlspecialchars($orden['order_number']) . '</td>
        <td style="width: 50%; text-align: right;"><b>FECHA:</b> ' . date($formato_fecha, strtotime($orden['created_at'])) . '</td>
    </tr>
    <tr>
        <td style="width: 50%;"><b>HORA:</b> ' . date('h:i A', strtotime($orden['created_at'])) . '</td>
        <td style="width: 50%; text-align: right;"><b>ATENDIÓ:</b> Admin</td>
    </tr>
</table>

<div class="client-info">
    <b>CLIENTE:</b> ' . htmlspecialchars(strtoupper($orden['cliente_nombre'])) . '<br />
    ' . (!empty($orden['cliente_telefono']) ? '<b>TEL:</b> ' . htmlspecialchars($orden['cliente_telefono']) . '<br />' : '') . '
    ' . (!empty($orden['cliente_email']) ? '<b>EMAIL:</b> ' . htmlspecialchars($orden['cliente_email']) . '<br />' : '') . '
</div>

<table class="items-table" cellpadding="2">
    <thead>
        <tr class="item-header">
            <th style="width: 55%; text-align: left;">DETALLE</th>
            <th style="width: 15%; text-align: center;">CANT</th>
            <th style="width: 30%; text-align: right;">TOTAL</th>
        </tr>
    </thead>
    <tbody>';

foreach ($items as $item) {
    $nota = trim($item['descripcion_item'] ?? '');
    $tag = trim($item['tag_code'] ?? '');
    $nota_html = '';
    $tag_html = '';
    if (!empty($tag)) {
        $tag_html = '<br /><span style="font-size: 6.5px; color: #0f172a; font-weight: bold;">&nbsp;&nbsp;Etiqueta: ' . htmlspecialchars($tag) . '</span>';
    }
    $garment_html = '<br /><span style="font-size: 6px; color: #475569; font-weight: normal;">&nbsp;&nbsp;Prendas: ' . (int)($item['garment_count'] ?? 1) . '</span>';
    if (!empty($nota)) {
        $nota_html = '<br /><span style="font-size: 6px; color: #64748b; font-style: italic; font-weight: normal;">&nbsp;&nbsp;* ' . htmlspecialchars($nota) . '</span>';
    }
    $html_ticket .= '
        <tr>
            <td style="width: 55%; text-align: left; font-weight: bold;">' . htmlspecialchars($item['servicio_nombre']) . $tag_html . $garment_html . $nota_html . '</td>
            <td style="width: 15%; text-align: center;">' . number_format((float)$item['quantity'], 1) . '</td>
            <td style="width: 30%; text-align: right;">' . formatMoney($item['subtotal'], $moneda) . '</td>
        </tr>';
}

$html_ticket .= '
    </tbody>
</table>

<table class="totals-table" cellpadding="1.5">
    <tr>
        <td style="width: 60%; text-align: right; color: #475569;">Subtotal:</td>
        <td style="width: 40%; text-align: right;">' . formatMoney($orden['subtotal'], $moneda) . '</td>
    </tr>';

if ($orden['discount'] > 0) {
    $html_ticket .= '
    <tr>
        <td style="width: 60%; text-align: right; color: #475569;">Descuento:</td>
        <td style="width: 40%; text-align: right;">-' . formatMoney($orden['discount'], $moneda) . '</td>
    </tr>';
}

// Calculate individual taxes based on stored rate or dynamically from JSON config
$subtotal_after_discount = (float)$orden['subtotal'] - (float)$orden['discount'];
foreach ($active_taxes as $tax) {
    $tax_rate = (float)$tax['rate'];
    $tax_amount = round($subtotal_after_discount * ($tax_rate / 100), 2);
    $html_ticket .= '
    <tr>
        <td style="width: 60%; text-align: right; color: #475569;">' . htmlspecialchars($tax['name']) . ' (' . $tax['rate'] . '%):</td>
        <td style="width: 40%; text-align: right;">' . formatMoney($tax_amount, $moneda) . '</td>
    </tr>';
}

$html_ticket .= '
    <tr style="font-weight: bold; font-size: 8.5px; background-color: #f8fafc;">
        <td style="width: 60%; text-align: right; color: #0000ff; border-top: 1px solid #cbd5e1; border-bottom: 1px solid #cbd5e1;">TOTAL:</td>
        <td style="width: 40%; text-align: right; color: #0000ff; border-top: 1px solid #cbd5e1; border-bottom: 1px solid #cbd5e1;">' . formatMoney($orden['total'], $moneda) . '</td>
    </tr>
</table>';

$html_ticket .= '
<div class="status-badge" style="color: ' . $pago_color . ';">
    ' . $pago_texto . '
</div>

<div style="font-size: 7px; text-align: center; border-top: 1px dashed #cbd5e1; padding-top: 2px; margin-top: 3px;">
    <b>ENTREGA ESTIMADA:</b><br />
    ' . (!empty($orden['delivery_date']) ? date(($formato_fecha === 'd/m/Y' ? 'd/m/Y h:i A' : 'm/d/Y h:i A'), strtotime($orden['delivery_date'])) : 'POR CONFIRMAR') . '
</div>';

$notaOrden = trim($orden['notes'] ?? '');
if (!empty($notaOrden)) {
    $html_ticket .= '
    <div style="font-size: 6.5px; text-align: left; border-top: 1px solid #e2e8f0; padding-top: 2px; margin-top: 3px;">
        <b>Notas:</b> ' . htmlspecialchars($notaOrden) . '
    </div>';
}

$footer_parts = explode("\n", $recibo_footer);
$first_line = trim(array_shift($footer_parts));
$remaining_lines = implode("\n", $footer_parts);

$html_ticket .= '
<div style="font-size: 6.5px; color: #475569; border-top: 1px solid #e2e8f0; border-bottom: 1px solid #e2e8f0; text-align: center; padding: 2px 0; margin-top: 5px;">
    ' . htmlspecialchars($first_line) . '
</div>';

if (!empty(trim($remaining_lines))) {
    $html_ticket .= '
    <div class="footer-text" style="padding-top: 2px;">
        ' . nl2br(htmlspecialchars($remaining_lines)) . '
    </div>';
}

$pdf->writeHTML($html_ticket, true, false, true, false, '');
$pdf->Output('Ticket_' . $orden['order_number'] . '.pdf', 'I');
exit;
?>
