<?php
// GET /api/slips/report.php?token=XXX&date_from=&date_to=&status=&my_only=
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

// Override JSON header set by auth.php — this page returns HTML
header('Content-Type: text/html; charset=utf-8');

$token = $_GET['token'] ?? '';
if ($token) {
    $db  = getDB();
    $ts  = $db->prepare("SELECT u.* FROM user_tokens ut JOIN users u ON u.id = ut.user_id WHERE ut.token = ? AND ut.expires_at > NOW() AND u.is_active = 1");
    $ts->execute([$token]);
    $user = $ts->fetch();
    if (!$user) { http_response_code(401); die('Unauthorised'); }
} else {
    $user = requireAuth();
}

$db      = getDB();
$isAdmin = in_array($user['role_id'], [1, 5]);

$dateFrom = $_GET['date_from'] ?? date('Y-m-01');
$dateTo   = $_GET['date_to']   ?? date('Y-m-d');
$status   = $_GET['status']    ?? '';
$myOnly   = ($_GET['my_only'] ?? '0') === '1';

// Build slip query
$slipWhere  = ['s.slip_date BETWEEN ? AND ?'];
$slipParams = [$dateFrom, $dateTo];
if ($myOnly || !$isAdmin) { $slipWhere[] = 's.user_id = ?'; $slipParams[] = $user['id']; }
if ($status && $status !== 'fuel') { $slipWhere[] = 's.status = ?'; $slipParams[] = $status; }
$showFuelOnly = ($status === 'fuel');
$showSlips    = !$showFuelOnly;
$showFuel     = ($status === '' || $status === 'fuel');

$fuelWhere  = ["fc.cost_type = 'fuel'", 'fc.cost_date BETWEEN ? AND ?'];
$fuelParams = [$dateFrom, $dateTo];
if ($myOnly || !$isAdmin) { $fuelWhere[] = 'fc.created_by = ?'; $fuelParams[] = $user['id']; }

$parts = []; $params = [];
if ($showSlips) {
    $parts[] = "SELECT s.id, s.slip_date, s.merchant, s.category, s.amount, s.vat_amount, s.payment_method, s.description, s.status, u.full_name AS user_name, p.name AS project_name, jc.job_number, NULL AS vehicle_reg, 'slip' AS source_type FROM slips s JOIN users u ON u.id = s.user_id LEFT JOIN projects p ON p.id = s.project_id LEFT JOIN job_cards jc ON jc.id = s.job_card_id WHERE " . implode(' AND ', $slipWhere);
    $params = array_merge($params, $slipParams);
}
if ($showFuel) {
    $parts[] = "SELECT fc.id, fc.cost_date AS slip_date, v.registration AS merchant, 'Fuel' AS category, fc.amount, NULL AS vat_amount, 'card' AS payment_method, fc.description, 'fuel' AS status, u.full_name AS user_name, NULL AS project_name, NULL AS job_number, v.registration AS vehicle_reg, 'fuel' AS source_type FROM fleet_costs fc JOIN fleet_vehicles v ON v.id = fc.vehicle_id LEFT JOIN users u ON u.id = fc.created_by WHERE " . implode(' AND ', $fuelWhere);
    $params = array_merge($params, $fuelParams);
}

$slips = [];
if ($parts) {
    $stmt = $db->prepare(implode(' UNION ALL ', $parts) . ' ORDER BY slip_date DESC, id DESC');
    $stmt->execute($params);
    $slips = $stmt->fetchAll();
}

$total    = array_sum(array_column($slips, 'amount'));
$totalVat = array_sum(array_column($slips, 'vat_amount'));

// Company name
$coStmt = $db->query("SELECT setting_value FROM settings WHERE setting_key='company_name' LIMIT 1");
$company = $coStmt ? ($coStmt->fetchColumn() ?: 'Elegant Work') : 'Elegant Work';

// Category summary
$catSummary = [];
foreach ($slips as $s) {
    $cat = $s['category'] ?: 'Uncategorised';
    $catSummary[$cat] = ($catSummary[$cat] ?? 0) + (float)$s['amount'];
}
arsort($catSummary);

$statusLabel = $status ? ucfirst($status) : 'All';
$dateLabel   = date('d M Y', strtotime($dateFrom)) . ' – ' . date('d M Y', strtotime($dateTo));
$generated   = date('d M Y H:i');

function fmt($n) { return 'R ' . number_format((float)$n, 2); }
function statusColor($s) {
    return ['linked'=>'#1d4ed8','reimbursed'=>'#15803d','rejected'=>'#dc2626','unlinked'=>'#92400e','fuel'=>'#6d28d9'][$s] ?? '#374151';
}
function statusBg($s) {
    return ['linked'=>'#eff6ff','reimbursed'=>'#f0fdf4','rejected'=>'#fff1f2','unlinked'=>'#fffbeb','fuel'=>'#f5f3ff'][$s] ?? '#f3f4f6';
}
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Slip Report — <?= htmlspecialchars($company) ?></title>
<style>
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif; font-size: 11pt; color: #1f2937; background: #fff; }
  .toolbar { position: fixed; top: 0; left: 0; right: 0; background: #fff; border-bottom: 1px solid #e5e7eb; padding: 10px 24px; display: flex; gap: 10px; align-items: center; z-index: 100; }
  .page { padding: 32px 40px; max-width: 960px; margin: 0 auto; padding-top: 72px; }
  .header-row { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 24px; padding-bottom: 16px; border-bottom: 2px solid #1b4b8a; }
  .company-name { font-size: 22px; font-weight: 800; color: #1b4b8a; }
  .report-title { font-size: 14px; color: #6b7280; margin-top: 2px; }
  .meta { text-align: right; font-size: 11px; color: #6b7280; line-height: 1.8; }
  .stats-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-bottom: 24px; }
  .stat-box { border: 1px solid #e5e7eb; border-radius: 8px; padding: 14px 16px; }
  .stat-label { font-size: 10px; font-weight: 700; color: #6b7280; text-transform: uppercase; letter-spacing: .5px; margin-bottom: 4px; }
  .stat-value { font-size: 20px; font-weight: 800; color: #1b4b8a; }
  .stat-sub { font-size: 11px; color: #9ca3af; margin-top: 2px; }
  .two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 24px; }
  .section-title { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: .5px; color: #6b7280; margin-bottom: 8px; }
  table { width: 100%; border-collapse: collapse; font-size: 10.5pt; }
  thead th { background: #1b4b8a; color: #fff; padding: 8px 10px; text-align: left; font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .4px; }
  tbody tr:nth-child(even) { background: #f9fafb; }
  tbody td { padding: 7px 10px; border-bottom: 1px solid #f3f4f6; vertical-align: top; }
  .amount { font-weight: 700; text-align: right; white-space: nowrap; }
  .badge { display: inline-block; padding: 2px 7px; border-radius: 10px; font-size: 9.5px; font-weight: 700; }
  .total-row td { font-weight: 700; background: #f0f7ff; border-top: 2px solid #1b4b8a; }
  .cat-table td { padding: 6px 10px; }
  .cat-bar-wrap { background: #f3f4f6; border-radius: 4px; height: 8px; width: 100%; overflow: hidden; }
  .cat-bar { background: #1b4b8a; height: 100%; border-radius: 4px; }
  .footer { margin-top: 32px; padding-top: 12px; border-top: 1px solid #e5e7eb; font-size: 10px; color: #9ca3af; display: flex; justify-content: space-between; }
  @media print {
    .toolbar { display: none !important; }
    .page { padding-top: 24px; }
    body { font-size: 10pt; }
    thead th { background: #1b4b8a !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
    tbody tr:nth-child(even) { background: #f9fafb !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
    .total-row td { background: #f0f7ff !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
    .stat-box { break-inside: avoid; }
  }
</style>
</head>
<body>

<div class="toolbar">
  <button onclick="window.print()" style="background:#1b4b8a;color:#fff;border:none;padding:8px 20px;border-radius:6px;font-weight:700;cursor:pointer;font-size:11pt">🖨️ Print / Save as PDF</button>
  <button onclick="window.close()" style="background:#f3f4f6;color:#374151;border:none;padding:8px 14px;border-radius:6px;cursor:pointer;font-size:11pt">✕ Close</button>
  <span style="margin-left:auto;font-size:11px;color:#6b7280"><?= count($slips) ?> records · <?= htmlspecialchars($dateLabel) ?></span>
</div>

<div class="page">

  <!-- Header -->
  <div class="header-row">
    <div>
      <div class="company-name">⚡ <?= htmlspecialchars($company) ?></div>
      <div class="report-title">Expense Slip Report</div>
    </div>
    <div class="meta">
      <strong>Period:</strong> <?= htmlspecialchars($dateLabel) ?><br>
      <strong>Filter:</strong> <?= htmlspecialchars($statusLabel) ?><br>
      <strong>Generated:</strong> <?= $generated ?><br>
      <?php if (!$isAdmin || $myOnly): ?><strong>Employee:</strong> <?= htmlspecialchars($user['full_name']) ?><?php endif; ?>
    </div>
  </div>

  <!-- Stats -->
  <div class="stats-grid">
    <div class="stat-box">
      <div class="stat-label">Total Expenses</div>
      <div class="stat-value"><?= fmt($total) ?></div>
      <div class="stat-sub"><?= count($slips) ?> records in period</div>
    </div>
    <div class="stat-box">
      <div class="stat-label">VAT Amount</div>
      <div class="stat-value"><?= fmt($totalVat) ?></div>
      <div class="stat-sub">Total VAT across slips</div>
    </div>
    <div class="stat-box">
      <div class="stat-label">Excl. VAT</div>
      <div class="stat-value"><?= fmt($total - $totalVat) ?></div>
      <div class="stat-sub">Net amount</div>
    </div>
  </div>

  <!-- Category summary + breakdown -->
  <?php if ($catSummary): ?>
  <div class="two-col" style="margin-bottom:24px">
    <div>
      <div class="section-title">By Category</div>
      <table class="cat-table">
        <tbody>
          <?php $maxCat = max(array_values($catSummary)); foreach ($catSummary as $cat => $amt): ?>
          <tr>
            <td style="color:#374151;font-size:10.5pt"><?= htmlspecialchars($cat) ?></td>
            <td style="width:120px">
              <div class="cat-bar-wrap"><div class="cat-bar" style="width:<?= round(($amt/$maxCat)*100) ?>%"></div></div>
            </td>
            <td style="text-align:right;font-weight:700;font-size:10.5pt"><?= fmt($amt) ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <div>
      <div class="section-title">By Status</div>
      <?php
      $statusSummary = [];
      foreach ($slips as $s) { $statusSummary[$s['status']] = ($statusSummary[$s['status']] ?? 0) + (float)$s['amount']; }
      arsort($statusSummary);
      ?>
      <table class="cat-table">
        <tbody>
          <?php foreach ($statusSummary as $st => $amt): ?>
          <tr>
            <td><span class="badge" style="background:<?= statusBg($st) ?>;color:<?= statusColor($st) ?>"><?= ucfirst($st) ?></span></td>
            <td style="text-align:right;font-weight:700"><?= fmt($amt) ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
  <?php endif; ?>

  <!-- Detail table -->
  <div class="section-title">Slip Detail</div>
  <table>
    <thead>
      <tr>
        <th>Date</th>
        <th>Merchant</th>
        <th>Category</th>
        <th>Description</th>
        <th>Method</th>
        <th>Linked To</th>
        <?php if ($isAdmin && !$myOnly): ?><th>Employee</th><?php endif; ?>
        <th>Status</th>
        <th style="text-align:right">Amount</th>
        <th style="text-align:right">VAT</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($slips as $s): ?>
      <tr>
        <td style="white-space:nowrap"><?= date('d M Y', strtotime($s['slip_date'])) ?></td>
        <td><?= htmlspecialchars($s['merchant'] ?? '—') ?></td>
        <td><?= htmlspecialchars($s['category'] ?? '—') ?></td>
        <td style="color:#6b7280;max-width:160px"><?= htmlspecialchars($s['description'] ?? '') ?></td>
        <td><?= ucfirst($s['payment_method'] ?? '—') ?></td>
        <td class="text-sm"><?= $s['project_name'] ? '📁 '.htmlspecialchars($s['project_name']) : ($s['job_number'] ? '🔧 '.$s['job_number'] : ($s['vehicle_reg'] ? '🚗 '.$s['vehicle_reg'] : '—')) ?></td>
        <?php if ($isAdmin && !$myOnly): ?><td><?= htmlspecialchars($s['user_name'] ?? '—') ?></td><?php endif; ?>
        <td><span class="badge" style="background:<?= statusBg($s['status']) ?>;color:<?= statusColor($s['status']) ?>"><?= ucfirst($s['status']) ?></span></td>
        <td class="amount"><?= $s['amount'] ? fmt($s['amount']) : '—' ?></td>
        <td class="amount" style="color:#6b7280"><?= $s['vat_amount'] ? fmt($s['vat_amount']) : '—' ?></td>
      </tr>
      <?php endforeach; ?>
      <tr class="total-row">
        <td colspan="<?= ($isAdmin && !$myOnly) ? 8 : 7 ?>">TOTAL</td>
        <td class="amount"><?= fmt($total) ?></td>
        <td class="amount"><?= fmt($totalVat) ?></td>
      </tr>
    </tbody>
  </table>

  <div class="footer">
    <span>Elegant Work — Expense Slip Report</span>
    <span>Generated <?= $generated ?></span>
  </div>

</div>
</body>
</html>