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

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

$type = $_GET['type'] ?? 'rewards';
$allowed = ['dashboard', 'rewards', 'members', 'customer'];
if (!in_array($type, $allowed, true)) $type = 'rewards';
$customerId = isset($_GET['customer_id']) ? (int)$_GET['customer_id'] : 0;

$conf = [];
try {
    $rs = $db->query("SELECT clave, valor FROM configuracion");
    if ($rs) while ($row = $rs->fetch(PDO::FETCH_ASSOC)) $conf[$row['clave']] = $row['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'] ?? 'Laundry App',
    'telefono' => $conf['empresa_telefono'] ?? '',
    'email' => $conf['empresa_email'] ?? '',
    'direccion' => $conf['empresa_direccion'] ?? '',
];
$moneda = $conf['moneda'] ?? 'USD';
$fmt_fecha = $conf['formato_fecha'] ?? 'm/d/Y';

function h($value) {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function money_pdf($value, $currency) {
    $symbol = $currency === 'EUR' ? 'EUR ' : '$';
    return $symbol . number_format((float)$value, 2);
}

function tier_label_pdf($tier) {
    if (!$tier) return 'Bronze';
    $labels = ['bronze' => 'Bronze', 'silver' => 'Silver', 'gold' => 'Gold', 'platinum' => 'Platinum'];
    return $labels[$tier] ?? ucfirst($tier);
}

function type_label_pdf($type) {
    $labels = [
        'dashboard' => 'REPORTE LOYALTY DASHBOARD',
        'rewards' => 'REPORTE DE REWARDS',
        'members' => 'REPORTE DE MIEMBROS',
        'customer' => 'REPORTE PERFIL DE CLIENTE',
    ];
    return $labels[$type] ?? 'REPORTE LOYALTY';
}

function render_header($empresa, $fmt_fecha, $title) {
    return '
    <table class="header" cellpadding="4">
      <tr>
        <td style="width: 55%;">
          <div class="company">' . h($empresa['nombre']) . '</div>
          <div class="meta">' . h($empresa['direccion']) . '<br />Tel: ' . h($empresa['telefono']) . ' | ' . h($empresa['email']) . '</div>
        </td>
        <td style="width: 45%; text-align: right;">
          <div class="title">' . h($title) . '</div>
          <div class="meta">Generado: ' . h(date($fmt_fecha . ' h:i A')) . '</div>
        </td>
      </tr>
    </table>';
}

function kpi_row($items) {
    $width = count($items) > 0 ? (100 / count($items)) : 25;
    $html = '<table class="kpis" cellpadding="0" cellspacing="0"><tr>';
    foreach ($items as $item) {
        $html .= '
        <td class="kpi" style="width:' . $width . '%;">
          <table class="kpi-inner" cellpadding="0" cellspacing="0">
            <tr><td class="kpi-label">' . h($item[0]) . '</td></tr>
            <tr><td class="kpi-value">' . h($item[1]) . '</td></tr>
          </table>
        </td>';
    }
    $html .= '</tr></table>';
    return $html;
}

function rewards_report($db, $moneda) {
    $stmt = $db->query("
        SELECT id, name, description, points_cost, discount_type, discount_value,
               min_order_value, tier_required, stock, is_active, created_at
        FROM loyalty_rewards
        ORDER BY is_active DESC, points_cost ASC, name ASC
    ");
    $rewards = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
    $activeCount = 0;
    $totalStock = 0;
    $unlimited = 0;
    foreach ($rewards as $reward) {
        if ((int)$reward['is_active'] === 1) $activeCount++;
        if ($reward['stock'] === null) $unlimited++;
        else $totalStock += (int)$reward['stock'];
    }

    $rows = '';
    if (!$rewards) {
        $rows = '<tr><td colspan="8" class="empty">No hay recompensas creadas.</td></tr>';
    } else {
        foreach ($rewards as $reward) {
            $discount = $reward['discount_type'] === 'percent'
                ? number_format((float)$reward['discount_value'], 2) . '%'
                : money_pdf($reward['discount_value'], $moneda);
            $stock = $reward['stock'] === null ? 'Ilimitado' : (string)$reward['stock'];
            $status = (int)$reward['is_active'] === 1 ? 'Activa' : 'Inactiva';
            $rows .= '<tr>
                <td>' . h($reward['name']) . '</td>
                <td>' . h($reward['description'] ?: 'N/A') . '</td>
                <td class="right">' . number_format((float)$reward['points_cost'], 0) . ' pts</td>
                <td class="right">' . h($discount) . '</td>
                <td class="right">' . money_pdf($reward['min_order_value'], $moneda) . '</td>
                <td>' . h(tier_label_pdf($reward['tier_required'])) . '</td>
                <td class="center">' . h($stock) . '</td>
                <td class="center">' . h($status) . '</td>
            </tr>';
        }
    }

    return kpi_row([
        ['Total Rewards', count($rewards)],
        ['Activas', $activeCount],
        ['Stock Definido', $totalStock],
        ['Ilimitadas', $unlimited],
    ]) . '
    <table class="data" cellpadding="4">
      <thead><tr>
        <th style="width:16%;">Reward</th><th style="width:25%;">Descripcion</th>
        <th class="right" style="width:10%;">Puntos</th><th class="right" style="width:10%;">Descuento</th>
        <th class="right" style="width:10%;">Min. Orden</th><th style="width:10%;">Nivel</th>
        <th class="center" style="width:9%;">Stock</th><th class="center" style="width:10%;">Estado</th>
      </tr></thead><tbody>' . $rows . '</tbody>
    </table>';
}

function dashboard_report($db, $moneda) {
    $tiers = $db->query("SELECT loyalty_tier AS tier, COUNT(*) AS count FROM customers GROUP BY loyalty_tier")->fetchAll(PDO::FETCH_ASSOC);
    $pts = $db->query("SELECT COALESCE(SUM(CASE WHEN type='earned' THEN points ELSE 0 END),0) AS earned, COALESCE(SUM(CASE WHEN type='redeemed' THEN ABS(points) ELSE 0 END),0) AS redeemed, COUNT(DISTINCT customer_id) AS active_members FROM loyalty_points")->fetch(PDO::FETCH_ASSOC);
    $red = $db->query("SELECT COUNT(*) AS total, COALESCE(SUM(discount_applied),0) AS total_discount FROM loyalty_redemptions")->fetch(PDO::FETCH_ASSOC);
    $top = $db->query("SELECT full_name, phone, loyalty_points_balance AS balance, loyalty_tier AS tier, loyalty_total_earned AS earned, loyalty_total_redeemed AS redeemed FROM customers WHERE loyalty_points_balance > 0 ORDER BY loyalty_points_balance DESC LIMIT 12")->fetchAll(PDO::FETCH_ASSOC);
    $activity = $db->query("SELECT lp.points, lp.type, lp.description, lp.created_at, c.full_name AS customer_name FROM loyalty_points lp JOIN customers c ON c.id = lp.customer_id ORDER BY lp.created_at DESC LIMIT 12")->fetchAll(PDO::FETCH_ASSOC);

    $tierRows = '';
    foreach ($tiers as $tier) {
        $tierRows .= '<tr><td style="width:70%;">' . h(tier_label_pdf($tier['tier'])) . '</td><td class="right" style="width:30%;">' . h($tier['count']) . '</td></tr>';
    }
    if (!$tierRows) $tierRows = '<tr><td colspan="2" class="empty">Sin niveles registrados.</td></tr>';

    $topRows = '';
    foreach ($top as $i => $c) {
        $topRows .= '<tr>
            <td class="center" style="width:7%;">' . ($i + 1) . '</td>
            <td style="width:28%;">' . h($c['full_name']) . '<br /><span class="muted">' . h($c['phone']) . '</span></td>
            <td style="width:15%;">' . h(tier_label_pdf($c['tier'])) . '</td>
            <td class="right" style="width:16%;">' . number_format((float)$c['balance'], 0) . '</td>
            <td class="right" style="width:17%;">' . number_format((float)$c['earned'], 0) . '</td>
            <td class="right" style="width:17%;">' . number_format((float)$c['redeemed'], 0) . '</td>
        </tr>';
    }
    if (!$topRows) $topRows = '<tr><td colspan="6" class="empty">Sin clientes con puntos.</td></tr>';

    $activityRows = '';
    foreach ($activity as $a) {
        $activityRows .= '<tr>
            <td style="width:17%;">' . h(date('m/d/Y', strtotime($a['created_at']))) . '</td>
            <td style="width:21%;">' . h($a['customer_name']) . '</td>
            <td style="width:16%;">' . h($a['type']) . '</td>
            <td style="width:34%;">' . h($a['description']) . '</td>
            <td class="right" style="width:12%;">' . h($a['points']) . '</td>
        </tr>';
    }
    if (!$activityRows) $activityRows = '<tr><td colspan="5" class="empty">Sin movimientos recientes.</td></tr>';

    return kpi_row([
        ['Miembros activos', (int)$pts['active_members']],
        ['Puntos emitidos', number_format((float)$pts['earned'], 0)],
        ['Puntos canjeados', number_format((float)$pts['redeemed'], 0)],
        ['Descuentos', money_pdf($red['total_discount'], $moneda)],
    ]) . '
    <table class="split" cellpadding="4"><tr>
      <td style="width:35%; vertical-align:top;">
        <h3>Distribucion por Nivel</h3>
        <table class="data" cellpadding="4"><thead><tr><th style="width:70%;">Nivel</th><th class="right" style="width:30%;">Miembros</th></tr></thead><tbody>' . $tierRows . '</tbody></table>
      </td>
      <td style="width:65%; vertical-align:top;">
        <h3>Top Clientes por Puntos</h3>
        <table class="data" cellpadding="4"><thead><tr><th class="center" style="width:7%;">#</th><th style="width:28%;">Cliente</th><th style="width:15%;">Nivel</th><th class="right" style="width:16%;">Balance</th><th class="right" style="width:17%;">Ganados</th><th class="right" style="width:17%;">Canjeados</th></tr></thead><tbody>' . $topRows . '</tbody></table>
      </td>
    </tr></table>
    <h3>Actividad Reciente</h3>
    <table class="data" cellpadding="4"><thead><tr><th style="width:17%;">Fecha</th><th style="width:21%;">Cliente</th><th style="width:16%;">Tipo</th><th style="width:34%;">Descripcion</th><th class="right" style="width:12%;">Puntos</th></tr></thead><tbody>' . $activityRows . '</tbody></table>';
}

function members_report($db) {
    $members = $db->query("SELECT id, full_name, phone, email, plan, loyalty_tier, loyalty_points_balance, loyalty_total_earned, loyalty_total_redeemed FROM customers ORDER BY loyalty_points_balance DESC, full_name ASC")->fetchAll(PDO::FETCH_ASSOC);
    $active = 0;
    $balance = 0;
    $earned = 0;
    $redeemed = 0;
    $rows = '';
    foreach ($members as $member) {
        if ((float)$member['loyalty_points_balance'] > 0) $active++;
        $balance += (float)$member['loyalty_points_balance'];
        $earned += (float)$member['loyalty_total_earned'];
        $redeemed += (float)$member['loyalty_total_redeemed'];
        $rows .= '<tr><td>' . h($member['full_name']) . '</td><td>' . h($member['phone']) . '</td><td>' . h($member['email']) . '</td><td>' . h(tier_label_pdf($member['loyalty_tier'])) . '</td><td class="right">' . number_format((float)$member['loyalty_points_balance'], 0) . '</td><td class="right">' . number_format((float)$member['loyalty_total_earned'], 0) . '</td><td class="right">' . number_format((float)$member['loyalty_total_redeemed'], 0) . '</td></tr>';
    }
    if (!$rows) $rows = '<tr><td colspan="7" class="empty">No hay miembros registrados.</td></tr>';

    return kpi_row([
        ['Miembros', count($members)],
        ['Con balance', $active],
        ['Balance total', number_format($balance, 0)],
        ['Canjeados', number_format($redeemed, 0)],
    ]) . '
    <table class="data" cellpadding="4">
      <thead><tr><th>Cliente</th><th>Telefono</th><th>Email</th><th>Nivel</th><th class="right">Balance</th><th class="right">Ganados</th><th class="right">Canjeados</th></tr></thead>
      <tbody>' . $rows . '</tbody>
    </table>';
}

function customer_report($db, $customerId, $moneda) {
    if ($customerId <= 0) return '<div class="empty">Seleccione un cliente para generar este reporte.</div>';
    $stmt = $db->prepare("SELECT id, full_name, phone, email, plan, loyalty_tier, loyalty_points_balance, loyalty_total_earned, loyalty_total_redeemed FROM customers WHERE id = ?");
    $stmt->execute([$customerId]);
    $customer = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$customer) return '<div class="empty">Cliente no encontrado.</div>';

    $historyStmt = $db->prepare("SELECT points, type, description, created_at, order_id FROM loyalty_points WHERE customer_id = ? ORDER BY created_at DESC LIMIT 30");
    $historyStmt->execute([$customerId]);
    $history = $historyStmt->fetchAll(PDO::FETCH_ASSOC);

    $couponStmt = $db->prepare("SELECT lr.coupon_code, lr.points_used, lr.discount_applied, lr.status, lr.expires_at, r.name AS reward_name FROM loyalty_redemptions lr JOIN loyalty_rewards r ON r.id = lr.reward_id WHERE lr.customer_id = ? ORDER BY lr.created_at DESC LIMIT 20");
    $couponStmt->execute([$customerId]);
    $coupons = $couponStmt->fetchAll(PDO::FETCH_ASSOC);

    $historyRows = '';
    foreach ($history as $item) {
        $historyRows .= '<tr><td>' . h(date('m/d/Y', strtotime($item['created_at']))) . '</td><td>' . h($item['type']) . '</td><td>' . h($item['description']) . '</td><td class="right">' . h($item['points']) . '</td></tr>';
    }
    if (!$historyRows) $historyRows = '<tr><td colspan="4" class="empty">Sin movimientos.</td></tr>';

    $couponRows = '';
    foreach ($coupons as $coupon) {
        $couponRows .= '<tr><td>' . h($coupon['coupon_code']) . '</td><td>' . h($coupon['reward_name']) . '</td><td class="right">' . h($coupon['points_used']) . '</td><td class="right">' . money_pdf($coupon['discount_applied'], $moneda) . '</td><td>' . h($coupon['status']) . '</td><td>' . h(date('m/d/Y', strtotime($coupon['expires_at']))) . '</td></tr>';
    }
    if (!$couponRows) $couponRows = '<tr><td colspan="6" class="empty">Sin cupones.</td></tr>';

    return kpi_row([
        ['Cliente', $customer['full_name']],
        ['Nivel', tier_label_pdf($customer['loyalty_tier'])],
        ['Balance', number_format((float)$customer['loyalty_points_balance'], 0)],
        ['Canjeados', number_format((float)$customer['loyalty_total_redeemed'], 0)],
    ]) . '
    <h3>Historial de Puntos</h3>
    <table class="data" cellpadding="4"><thead><tr><th>Fecha</th><th>Tipo</th><th>Descripcion</th><th class="right">Puntos</th></tr></thead><tbody>' . $historyRows . '</tbody></table>
    <h3>Cupones y Canjes</h3>
    <table class="data" cellpadding="4"><thead><tr><th>Cupon</th><th>Reward</th><th class="right">Puntos</th><th class="right">Descuento</th><th>Estado</th><th>Vence</th></tr></thead><tbody>' . $couponRows . '</tbody></table>';
}

$body = '';
if ($type === 'dashboard') $body = dashboard_report($db, $moneda);
if ($type === 'rewards') $body = rewards_report($db, $moneda);
if ($type === 'members') $body = members_report($db);
if ($type === 'customer') $body = customer_report($db, $customerId, $moneda);

$pdf = new TCPDF('L', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetTitle(type_label_pdf($type));
$pdf->SetMargins(10, 10, 10);
$pdf->SetAutoPageBreak(true, 14);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();

$html = '
<style>
  body { color: #0f172a; font-family: freesans; }
  .header { background-color: #0f1b2a; color: #ffffff; padding: 14px 18px; }
  .company { font-size: 16px; font-weight: bold; }
  .meta { font-size: 8px; color: #b7c6d9; }
  .title { font-size: 17px; font-weight: bold; text-align: right; }
  h3 { color: #0f172a; font-size: 10px; margin: 10px 0 6px; }
  .kpis { width: 100%; margin: 14px 0 18px; border-collapse: separate; border-spacing: 6px; }
  .kpi { background-color: #eef6ff; border-left: 3px solid #0877ff; padding: 8px 10px; }
  .kpi-inner { width: 100%; }
  .kpi-label { color: #64748b; font-size: 7.6px; font-weight: bold; text-transform: uppercase; text-align: center; padding-bottom: 3px; }
  .kpi-value { color: #0f172a; font-size: 13.5px; font-weight: bold; text-align: center; white-space: nowrap; }
  table.data { width: 100%; border-collapse: collapse; font-size: 7.2px; }
  table.data th { background-color: #0f1b2a; color: #ffffff; border: 1px solid #0f1b2a; padding: 5px; font-weight: bold; }
  table.data td { border-bottom: 1px solid #e2e8f0; padding: 4px; }
  table.data tr:nth-child(even) td { background-color: #f8fbff; }
  table.data th.right { text-align: right; }
  table.data th.center { text-align: center; }
  .right { text-align: right; }
  .center { text-align: center; }
  .muted { color: #64748b; font-size: 7px; }
  .empty { text-align: center; color: #64748b; padding: 18px; }
</style>' . render_header($empresa, $fmt_fecha, type_label_pdf($type)) . $body;

$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output('Reporte_Loyalty_' . $type . '_' . date('Y-m-d') . '.pdf', 'I');
exit;
?>
