<?php
// api/controllers/reportes_general.php — PREMIUM EDITION
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';

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

// ─── Params & Validation ──────────────────────────────────────────────────────
$start  = $_GET['start']  ?? date('Y-m-01');
$end    = $_GET['end']    ?? date('Y-m-d');
$status = $_GET['status'] ?? '';
$status_group = $_GET['status_group'] ?? '';
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $start)) $start = date('Y-m-01');
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $end))   $end   = date('Y-m-d');

// ─── Config ───────────────────────────────────────────────────────────────────
$conf = [];
try {
    $rs = $db->query("SELECT clave, valor FROM configuracion");
    if ($rs) while ($r = $rs->fetch(PDO::FETCH_ASSOC)) $conf[$r['clave']] = $r['valor'];
} catch (Exception $e) {}

if (!empty($conf['zona_horaria'])) date_default_timezone_set($conf['zona_horaria']);
else date_default_timezone_set('America/Puerto_Rico');

$empresa = [
    'nombre'    => $conf['empresa_nombre']    ?? 'Lavandería y Sastrería PR',
    'telefono'  => $conf['empresa_telefono']  ?? '(787) 555-0000',
    'email'     => $conf['empresa_email']     ?? 'contacto@laundryapp.com',
    'direccion' => $conf['empresa_direccion'] ?? 'Calle 34 #7534, Puerto Rico',
];
$moneda      = $conf['moneda']      ?? 'USD';
$fmt_fecha   = $conf['formato_fecha'] ?? 'm/d/Y';
$taxes_json  = $conf['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"]];

// ─── Helpers ─────────────────────────────────────────────────────────────────
function fmtM($v, $m) {
    return ($m === 'EUR' ? '€' : '$') . number_format((float)$v, 2);
}
function fmtD($v, $f) {
    if (!$v) return '—';
    $t = strtotime($v);
    return $t ? date($f, $t) : $v;
}

$STATUS_LABELS = [
    'received'=>'Recibida','washing'=>'Lavando','drying'=>'Secando',
    'folding'=>'Doblando','ready'=>'Lista','delivered'=>'Entregada','cancelled'=>'Cancelada',
];
$STATUS_GROUPS = [
    'pendiente'  => ['label' => 'Pendiente',  'statuses' => ['received']],
    'en_proceso' => ['label' => 'En Proceso', 'statuses' => ['washing', 'drying', 'folding']],
    'listo'      => ['label' => 'Listo',      'statuses' => ['ready']],
    'entregado'  => ['label' => 'Entregado',  'statuses' => ['delivered']],
    'cancelado'  => ['label' => 'Cancelado',  'statuses' => ['cancelled']],
];
$STATUS_COLORS = [  // [R,G,B text], [R,G,B bg]
    'received'  => [[8,119,255],[231,244,255]],
    'washing'   => [[2,132,199],[224,242,254]],
    'drying'    => [[217,119,6],[255,247,237]],
    'folding'   => [[124,58,237],[243,240,255]],
    'ready'     => [[5,150,105],[209,250,229]],
    'delivered' => [[21,128,61],[220,252,231]],
    'cancelled' => [[220,38,38],[254,226,226]],
];

// ─── Query ────────────────────────────────────────────────────────────────────
$where  = ["DATE(o.created_at) BETWEEN ? AND ?"];
$params = [$start, $end];
$active_status_label = 'Todos los estados';
if (!empty($status_group) && isset($STATUS_GROUPS[$status_group])) {
    $group_statuses = $STATUS_GROUPS[$status_group]['statuses'];
    $placeholders = implode(',', array_fill(0, count($group_statuses), '?'));
    $where[] = "o.status IN ($placeholders)";
    foreach ($group_statuses as $group_status) $params[] = $group_status;
    $active_status_label = $STATUS_GROUPS[$status_group]['label'];
} elseif (!empty($status)) {
    $where[] = "o.status = ?";
    $params[] = $status;
    $active_status_label = $STATUS_LABELS[$status] ?? $status;
}

$sql = "SELECT o.id, o.order_number, o.status, o.subtotal, o.tax, o.discount, o.total,
               o.created_at, c.full_name AS customer_name,
               (SELECT COUNT(*) FROM payments WHERE order_id = o.id) AS is_paid
        FROM orders o
        JOIN customers c ON o.customer_id = c.id
        WHERE " . implode(' AND ', $where) . "
        ORDER BY o.created_at ASC, o.id ASC";
$stmt = $db->prepare($sql);
$stmt->execute($params);
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

$tot_sub = $tot_tax = $tot_disc = $tot_total = $tot_paid = $tot_pend = 0;
foreach ($orders as $o) {
    $tot_sub   += (float)$o['subtotal'];
    $tot_tax   += (float)$o['tax'];
    $tot_disc  += (float)$o['discount'];
    $tot_total += (float)$o['total'];
    if ($o['is_paid']) $tot_paid++; else $tot_pend++;
}

// ─── Logo ─────────────────────────────────────────────────────────────────────
$logo_img = null; $logo_type = '';
if (!empty($conf['empresa_logo'])) {
    if (preg_match('/^data:image\/([a-zA-Z0-9\+\-\.]+);base64,(.+)$/s', $conf['empresa_logo'], $m)) {
        $mt = strtolower($m[1]);
        $logo_img  = base64_decode($m[2]);
        $logo_type = ($mt === 'svg+xml') ? 'svg' : (($mt === 'jpeg') ? 'jpg' : $mt);
    }
}

// ─── Column widths (total must = pageW = 273mm) ───────────────────────────────
// A4 landscape = 297mm; margins 12+12=24; pageW = 273mm
$cols = [
    ['label' => '#',         'w' => 8,  'align' => 'C'],
    ['label' => 'ORDEN',     'w' => 30, 'align' => 'L'],
    ['label' => 'CLIENTE',   'w' => 55, 'align' => 'L'],
    ['label' => 'FECHA',     'w' => 24, 'align' => 'C'],
    ['label' => 'SUBTOTAL',  'w' => 27, 'align' => 'R'],
    ['label' => 'ITBIS',     'w' => 23, 'align' => 'R'],
    ['label' => 'DESCUENTO', 'w' => 26, 'align' => 'R'],
    ['label' => 'TOTAL',     'w' => 27, 'align' => 'R'],
    ['label' => 'ESTADO',    'w' => 29, 'align' => 'C'],
    ['label' => 'PAGO',      'w' => 24, 'align' => 'C'],
]; // Total = 8+30+55+24+27+23+26+27+29+24 = 273 ✓

// ─── TCPDF ───────────────────────────────────────────────────────────────────
$pdf = new TCPDF('L', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetMargins(12, 10, 12);
$pdf->SetAutoPageBreak(true, 14);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();

$pageW = 273; // 297-12-12
$lm    = 12;

// ══════════════════════════════════════════════════════════════════════════════
// SECTION 1: PREMIUM DARK HEADER BAND
// ══════════════════════════════════════════════════════════════════════════════
$pdf->SetFillColor(11, 27, 63);   // dark navy
$pdf->Rect(0, 0, 297, 38, 'F');   // full-width bar

// Accent line at bottom of header
$pdf->SetFillColor(8, 119, 255);  // primary blue
$pdf->Rect(0, 38, 297, 2, 'F');

// Logo inside header
if ($logo_img) {
    if ($logo_type === 'svg') $pdf->ImageSVG('@' . $logo_img, 8, 5, 26, 12, '', '', '', 0, false);
    else                      $pdf->Image('@' . $logo_img, 8, 5, 26, 12, $logo_type);
    $nameX = 38;
} else {
    // Draw a white circle as placeholder logo
    $pdf->SetFillColor(255,255,255);
    $pdf->Ellipse(20, 19, 8, 8, 0, 0, 360, 'F');
    $pdf->SetFont('freesans','B',9);
    $pdf->SetTextColor(11,27,63);
    $pdf->SetXY(16,16); $pdf->Cell(8,6,'L&S',0,0,'C');
    $nameX = 38;
}

// Company name
$pdf->SetFont('freesans', 'B', 16);
$pdf->SetTextColor(255, 255, 255);
$pdf->SetXY($nameX, 6);
$pdf->Cell(130, 9, htmlspecialchars($empresa['nombre']), 0, 1, 'L');

// Company details in white/light
$pdf->SetFont('freesans', '', 8);
$pdf->SetTextColor(176, 196, 222); // light steel blue
$pdf->SetXY($nameX, 16);
$pdf->Cell(130, 5, htmlspecialchars($empresa['direccion']), 0, 1, 'L');
$pdf->SetXY($nameX, 21);
$pdf->Cell(130, 5, 'Tel: ' . htmlspecialchars($empresa['telefono']) . '   ' . htmlspecialchars($empresa['email']), 0, 1, 'L');

// Report title on right side of header
$pdf->SetFont('freesans', 'B', 15);
$pdf->SetTextColor(255, 255, 255);
$pdf->SetXY(170, 9);
$pdf->Cell(115, 10, 'REPORTE DE VENTAS', 0, 1, 'R');

$pdf->SetFont('freesans', '', 7.5);
$pdf->SetTextColor(136, 176, 232);
$pdf->SetXY(170, 20);
$label_start = date($fmt_fecha, strtotime($start));
$label_end   = date($fmt_fecha, strtotime($end));
$st_label    = $active_status_label;
$pdf->Cell(115, 5, "Periodo: $label_start — $label_end   ·   Estado: $st_label", 0, 1, 'R');
$pdf->SetXY(170, 26);
$pdf->Cell(115, 5, "Generado: " . date('m/d/Y h:i A'), 0, 1, 'R');

// ══════════════════════════════════════════════════════════════════════════════
// SECTION 2: KPI CARDS (all at same Y level)
// ══════════════════════════════════════════════════════════════════════════════
$cardY   = 46;
$gap     = 4;
$cardH   = 26;
$cardW   = ($pageW - 3 * $gap) / 4;

$kpis = [
    ['ÓRDENES TOTALES',  count($orders),            [8,119,255],  [231,244,255], '📋'],
    ['INGRESOS NETOS',   fmtM($tot_total, $moneda), [5,150,105],  [209,250,229], '💰'],
    ['PAGADAS',          "$tot_paid",               [21,128,61],  [220,252,231], '✅'],
    ['PENDIENTES PAGO',  "$tot_pend",               [217,119,6],  [255,247,237], '⏳'],
];

foreach ($kpis as $i => [$label, $value, $textRGB, $bgRGB]) {
    $cx = $lm + $i * ($cardW + $gap);

    // Card background
    $pdf->SetFillColor($bgRGB[0], $bgRGB[1], $bgRGB[2]);
    $pdf->RoundedRect($cx, $cardY, $cardW, $cardH, 3, '1111', 'F');

    // Left accent stripe
    $pdf->SetFillColor($textRGB[0], $textRGB[1], $textRGB[2]);
    $pdf->Rect($cx, $cardY, 3, $cardH, 'F');

    // Label
    $pdf->SetFont('freesans', 'B', 6.5);
    $pdf->SetTextColor(100, 120, 150);
    $pdf->SetXY($cx + 6, $cardY + 4);
    $pdf->Cell($cardW - 8, 5, $label, 0, 0, 'L');

    // Value
    $pdf->SetFont('freesans', 'B', 14);
    $pdf->SetTextColor($textRGB[0], $textRGB[1], $textRGB[2]);
    $pdf->SetXY($cx + 6, $cardY + 11);
    $pdf->Cell($cardW - 8, 9, $value, 0, 0, 'L');

    // Subtext
    if ($i === 0) $sub = count($orders) > 0 ? "en el periodo" : "sin registros";
    elseif ($i === 1) $sub = "subtotal " . fmtM($tot_sub, $moneda);
    elseif ($i === 2) $sub = number_format($tot_paid > 0 && count($orders) > 0 ? ($tot_paid/count($orders))*100 : 0, 0) . "% del total";
    else             $sub = fmtM(count($orders) > 0 ? $tot_total - ($tot_total * $tot_paid / max(count($orders),1)) : 0, $moneda);

    $pdf->SetFont('freesans', '', 6);
    $pdf->SetTextColor(130, 150, 170);
    $pdf->SetXY($cx + 6, $cardY + 20);
    $pdf->Cell($cardW - 8, 4, $sub, 0, 0, 'L');
}

$pdf->SetY($cardY + $cardH + 8);

// ══════════════════════════════════════════════════════════════════════════════
// SECTION 3: TABLE HEADER
// ══════════════════════════════════════════════════════════════════════════════
$tableY = $pdf->GetY();

// Table header gradient (solid dark navy, then blue band)
$pdf->SetFillColor(11, 27, 63);
$pdf->Rect($lm, $tableY, $pageW, 9, 'F');

$pdf->SetFont('freesans', 'B', 7);
$pdf->SetTextColor(255, 255, 255);
$pdf->SetXY($lm, $tableY + 0.5);
foreach ($cols as $col) {
    $pdf->Cell($col['w'], 8, $col['label'], 0, 0, $col['align']);
}
$pdf->Ln(9);

// ══════════════════════════════════════════════════════════════════════════════
// SECTION 4: TABLE ROWS
// ══════════════════════════════════════════════════════════════════════════════
$pdf->SetFont('freesans', '', 7.5);
$rowH  = 7.5;
$rowBg = false;

// Determine text height needed for page break check
$footerH = 22;

foreach ($orders as $i => $o) {
    // Page break with re-draw header
    if ($pdf->GetY() + $rowH > $pdf->getPageHeight() - $footerH) {
        // Footer on current page (drawFooter disables auto-break)
        drawFooter($pdf, $empresa, $pageW, $lm);
        $pdf->AddPage();
        $pdf->SetAutoPageBreak(true, $footerH); // re-enable for new page
        // Re-draw table header
        $ty = $pdf->GetY();
        $pdf->SetFillColor(11, 27, 63);
        $pdf->Rect($lm, $ty, $pageW, 9, 'F');
        $pdf->SetFont('freesans', 'B', 7);
        $pdf->SetTextColor(255,255,255);
        $pdf->SetXY($lm, $ty + 0.5);
        foreach ($cols as $col) $pdf->Cell($col['w'], 8, $col['label'], 0, 0, $col['align']);
        $pdf->Ln(9);
        $pdf->SetFont('freesans', '', 7.5);
        $rowBg = false;
    }

    $cy = $pdf->GetY();

    // Row background
    if ($rowBg) {
        $pdf->SetFillColor(245, 249, 255);
        $pdf->Rect($lm, $cy, $pageW, $rowH, 'F');
    } else {
        $pdf->SetFillColor(255, 255, 255);
        $pdf->Rect($lm, $cy, $pageW, $rowH, 'F');
    }
    $rowBg = !$rowBg;

    // Thin divider line
    $pdf->SetDrawColor(220, 230, 245);
    $pdf->Line($lm, $cy, $lm + $pageW, $cy);

    $pdf->SetXY($lm, $cy);

    // # col
    $pdf->SetFont('freesans', '', 7);
    $pdf->SetTextColor(150, 160, 180);
    $pdf->Cell($cols[0]['w'], $rowH, $i + 1, 0, 0, 'C');

    // ORDER col (blue link style)
    $pdf->SetFont('freesans', 'B', 7.5);
    $pdf->SetTextColor(8, 119, 255);
    $pdf->Cell($cols[1]['w'], $rowH, htmlspecialchars($o['order_number']), 0, 0, 'L');

    // CLIENTE col
    $pdf->SetFont('freesans', '', 7.5);
    $pdf->SetTextColor(20, 30, 60);
    $cname = mb_strimwidth($o['customer_name'], 0, 24, '…');
    $pdf->Cell($cols[2]['w'], $rowH, htmlspecialchars($cname), 0, 0, 'L');

    // FECHA col
    $pdf->SetFont('freesans', '', 7);
    $pdf->SetTextColor(100, 115, 140);
    $pdf->Cell($cols[3]['w'], $rowH, fmtD($o['created_at'], $fmt_fecha), 0, 0, 'C');

    // SUBTOTAL
    $pdf->SetFont('freesans', '', 7.5);
    $pdf->SetTextColor(40, 55, 80);
    $pdf->Cell($cols[4]['w'], $rowH, fmtM($o['subtotal'], $moneda), 0, 0, 'R');

    // ITBIS
    $pdf->SetTextColor(100, 115, 140);
    $pdf->Cell($cols[5]['w'], $rowH, fmtM($o['tax'], $moneda), 0, 0, 'R');

    // DESCUENTO (red if negative)
    if ((float)$o['discount'] > 0) {
        $pdf->SetFont('freesans', 'B', 7.5);
        $pdf->SetTextColor(204, 50, 50);
        $pdf->Cell($cols[6]['w'], $rowH, '-' . fmtM($o['discount'], $moneda), 0, 0, 'R');
    } else {
        $pdf->SetTextColor(180, 190, 210);
        $pdf->Cell($cols[6]['w'], $rowH, '—', 0, 0, 'R');
    }

    // TOTAL (bold primary)
    $pdf->SetFont('freesans', 'B', 8);
    $pdf->SetTextColor(8, 119, 255);
    $pdf->Cell($cols[7]['w'], $rowH, fmtM($o['total'], $moneda), 0, 0, 'R');

    // ESTADO badge-style
    $sc = $STATUS_COLORS[$o['status']] ?? [[100,100,100],[245,245,245]];
    $sx = $pdf->GetX(); $sy = $pdf->GetY();
    $bw = $cols[8]['w'] - 4; $bh = 5; $bx = $sx + 2; $by = $sy + 1.3;
    $pdf->SetFillColor($sc[1][0], $sc[1][1], $sc[1][2]);
    $pdf->RoundedRect($bx, $by, $bw, $bh, 1.5, '1111', 'F');
    $pdf->SetFont('freesans', 'B', 6.5);
    $pdf->SetTextColor($sc[0][0], $sc[0][1], $sc[0][2]);
    $pdf->SetXY($bx, $by);
    $pdf->Cell($bw, $bh, $STATUS_LABELS[$o['status']] ?? $o['status'], 0, 0, 'C');
    $pdf->SetXY($sx + $cols[8]['w'], $sy);

    // PAGO badge
    $ppaid = (bool)$o['is_paid'];
    $pcol  = $ppaid ? [[21,128,61],[220,252,231]] : [[217,119,6],[255,247,237]];
    $plbl  = $ppaid ? 'Pagado' : 'Pendiente';
    $px = $pdf->GetX(); $py = $pdf->GetY();
    $pdf->SetFillColor($pcol[1][0], $pcol[1][1], $pcol[1][2]);
    $pdf->RoundedRect($px + 1, $py + 1.3, $cols[9]['w'] - 2, 5, 1.5, '1111', 'F');
    $pdf->SetFont('freesans', 'B', 6.5);
    $pdf->SetTextColor($pcol[0][0], $pcol[0][1], $pcol[0][2]);
    $pdf->SetXY($px + 1, $py + 1.3);
    $pdf->Cell($cols[9]['w'] - 2, 5, $plbl, 0, 0, 'C');

    $pdf->SetXY($lm, $cy + $rowH);
}

// ══════════════════════════════════════════════════════════════════════════════
// SECTION 5: TOTALS ROW
// ══════════════════════════════════════════════════════════════════════════════
$pdf->Ln(1);
$ty2 = $pdf->GetY();

// Dark total background
$pdf->SetFillColor(11, 27, 63);
$pdf->Rect($lm, $ty2, $pageW, 9.5, 'F');

$leadW = $cols[0]['w'] + $cols[1]['w'] + $cols[2]['w'] + $cols[3]['w'];

$pdf->SetFont('freesans', 'B', 7.5);
$pdf->SetTextColor(136, 176, 232);
$pdf->SetXY($lm, $ty2 + 1);
$pdf->Cell($leadW, 7.5, 'TOTALES DEL PERIODO:', 0, 0, 'R');

$pdf->SetTextColor(255, 255, 255);
$pdf->Cell($cols[4]['w'], 7.5, fmtM($tot_sub,  $moneda), 0, 0, 'R');
$pdf->SetTextColor(136, 176, 232);
$pdf->Cell($cols[5]['w'], 7.5, fmtM($tot_tax,  $moneda), 0, 0, 'R');

$pdf->SetTextColor(255, 150, 150);
$pdf->Cell($cols[6]['w'], 7.5, $tot_disc > 0 ? '-'.fmtM($tot_disc,$moneda) : '—', 0, 0, 'R');

$pdf->SetFont('freesans', 'B', 9);
$pdf->SetTextColor(37, 199, 217); // aqua for total
$pdf->Cell($cols[7]['w'], 7.5, fmtM($tot_total, $moneda), 0, 0, 'R');

$pdf->SetFont('freesans', 'B', 7.5);
$pdf->SetTextColor(200, 215, 240);
$pdf->Cell($cols[8]['w'] + $cols[9]['w'], 7.5, count($orders) . ' orden' . (count($orders)!=1?'es':''), 0, 0, 'C');

$pdf->Ln(10);

// ══════════════════════════════════════════════════════════════════════════════
// SECTION 6: SUMMARY ANALYTICS BOX
// ══════════════════════════════════════════════════════════════════════════════
if (count($orders) > 0) {
    $ay = $pdf->GetY();
    $halfW = ($pageW - 6) / 2;

    // Left box: Tax breakdown
    $pdf->SetFillColor(248, 251, 255);
    $pdf->SetDrawColor(208, 225, 248);
    $pdf->RoundedRect($lm, $ay, $halfW, 28, 3, '1111', 'DF');

    $pdf->SetFont('freesans', 'B', 8);
    $pdf->SetTextColor(11, 27, 63);
    $pdf->SetXY($lm + 4, $ay + 4);
    $pdf->Cell($halfW - 8, 6, 'DESGLOSE DE IMPUESTOS', 0, 1, 'L');

    $taxableBase = $tot_sub - $tot_disc;
    $pdf->SetFont('freesans', '', 7.5);
    foreach ($active_taxes as $tax) {
        $rate   = (float)$tax['rate'];
        $amount = round($taxableBase * ($rate / 100), 2);
        $pdf->SetTextColor(80, 100, 130);
        $pdf->SetXY($lm + 4, $pdf->GetY());
        $pdf->Cell($halfW - 50, 5.5, htmlspecialchars($tax['name']) . " ({$tax['rate']}%)", 0, 0, 'L');
        $pdf->SetFont('freesans', 'B', 7.5);
        $pdf->SetTextColor(8, 119, 255);
        $pdf->Cell(40, 5.5, fmtM($amount, $moneda), 0, 1, 'R');
        $pdf->SetFont('freesans', '', 7.5);
    }

    // Divider line
    $pdf->SetDrawColor(208, 225, 248);
    $pdf->SetXY($lm + 4, $pdf->GetY());
    $pdf->Line($lm + 4, $pdf->GetY(), $lm + $halfW - 4, $pdf->GetY());
    $pdf->SetFont('freesans', 'B', 8);
    $pdf->SetTextColor(11, 27, 63);
    $pdf->SetXY($lm + 4, $pdf->GetY() + 1.5);
    $pdf->Cell($halfW - 50, 6, 'TOTAL IMPUESTOS:', 0, 0, 'L');
    $pdf->SetTextColor(8, 119, 255);
    $pdf->Cell(40, 6, fmtM($tot_tax, $moneda), 0, 1, 'R');

    // Right box: Payment stats
    $rx = $lm + $halfW + 6;
    $pdf->SetFillColor(248, 251, 255);
    $pdf->SetDrawColor(208, 225, 248);
    $pdf->RoundedRect($rx, $ay, $halfW, 28, 3, '1111', 'DF');

    $pdf->SetFont('freesans', 'B', 8);
    $pdf->SetTextColor(11, 27, 63);
    $pdf->SetXY($rx + 4, $ay + 4);
    $pdf->Cell($halfW - 8, 6, 'RESUMEN DE COBROS', 0, 1, 'L');

    $pct_paid = count($orders) > 0 ? round(($tot_paid / count($orders)) * 100) : 0;
    $avg_ord  = count($orders) > 0 ? $tot_total / count($orders) : 0;

    $pdf->SetFont('freesans', '', 7.5);
    $stats = [
        ['Órdenes pagadas:',    "$tot_paid ($pct_paid%)",          [21,128,61]],
        ['Órdenes pendientes:', "$tot_pend (" . (100-$pct_paid) . "%)", [217,119,6]],
        ['Promedio por orden:', fmtM($avg_ord, $moneda),           [8,119,255]],
        ['Base gravable:',      fmtM($taxableBase, $moneda),       [100,115,140]],
    ];
    foreach ($stats as [$lbl, $val, $clr]) {
        $pdf->SetXY($rx + 4, $pdf->GetY());
        $pdf->SetTextColor(80, 100, 130);
        $pdf->Cell($halfW - 50, 5.5, $lbl, 0, 0, 'L');
        $pdf->SetFont('freesans', 'B', 7.5);
        $pdf->SetTextColor($clr[0], $clr[1], $clr[2]);
        $pdf->Cell(40, 5.5, $val, 0, 1, 'R');
        $pdf->SetFont('freesans', '', 7.5);
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// FOOTER
// ══════════════════════════════════════════════════════════════════════════════
$pdf->SetAutoPageBreak(false); // prevent blank page after last content
drawFooter($pdf, $empresa, $pageW, $lm);

// ─── Footer function ──────────────────────────────────────────────────────────
function drawFooter($pdf, $empresa, $pageW, $lm) {
    $fh = $pdf->getPageHeight();
    $pdf->SetAutoPageBreak(false); // must be off while drawing absolute footer
    $pdf->SetFillColor(11, 27, 63);
    $pdf->Rect(0, $fh - 12, 297, 12, 'F');
    $pdf->SetFont('freesans', '', 7);
    $pdf->SetTextColor(136, 176, 232);
    $pdf->SetXY($lm, $fh - 9);
    $pdf->Cell($pageW * 0.6, 6, htmlspecialchars($empresa['nombre']) . '  ·  ' . htmlspecialchars($empresa['email']) . '  ·  ' . htmlspecialchars($empresa['telefono']), 0, 0, 'L');
    $pdf->SetXY($lm + $pageW * 0.6, $fh - 9);
    $pdf->SetTextColor(200, 215, 240);
    $pdf->SetFont('freesans', 'B', 7);
    $pdf->Cell($pageW * 0.4, 6, 'Página ' . $pdf->getPage() . '   Generado: ' . date('m/d/Y h:i A'), 0, 0, 'R');
}

$pdf->Output('Reporte_Ventas_' . $start . '_' . $end . '.pdf', 'I');
exit;
?>
