<?php
// GET /api/cashflow/report.php?token=XXX&month_id=X
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
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();
$monthId = (int)($_GET['month_id'] ?? 0);
if (!$monthId) die('Month ID required.');

$mStmt = $db->prepare("SELECT * FROM cashflow_months WHERE id = ? LIMIT 1");
$mStmt->execute([$monthId]);
$month = $mStmt->fetch();
if (!$month) die('Month not found.');

// Income
$incStmt = $db->prepare("SELECT ci.*, c.company_name AS client_name, jc.job_number FROM cashflow_income ci LEFT JOIN clients c ON c.id=ci.client_id LEFT JOIN job_cards jc ON jc.id=ci.job_card_id WHERE ci.month_id=? ORDER BY ci.type, ci.id");
$incStmt->execute([$monthId]);
$income = $incStmt->fetchAll();

// Expenses
$expStmt = $db->prepare("SELECT ce.*, s.merchant AS slip_merchant FROM cashflow_expenses ce LEFT JOIN slips s ON s.id=ce.slip_id WHERE ce.month_id=? ORDER BY ce.type, ce.id");
$expStmt->execute([$monthId]);
$expenses = $expStmt->fetchAll();

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

function fmt($n) { return 'R '.number_format((float)$n,2); }

function coalesce(...$vals) { foreach ($vals as $v) { if ($v !== null && $v !== '') return $v; } return 0; }

// Single amount per line: actual_amount if set, else expected_amount
$opening       = (float)$month['opening_balance'];
$totalIncome   = array_sum(array_map(fn($r)=>(float)coalesce($r['actual_amount'],$r['expected_amount']), $income));
$totalExpenses = array_sum(array_map(fn($r)=>(float)coalesce($r['actual_amount'],$r['expected_amount']), $expenses)) + (float)$month['payroll_amount'];
$pendingIncome = array_sum(array_map(fn($r)=>!$r['is_paid']?(float)coalesce($r['actual_amount'],$r['expected_amount']):0, $income));
$pendingExpenses=array_sum(array_map(fn($r)=>!$r['is_paid']?(float)coalesce($r['actual_amount'],$r['expected_amount']):0, $expenses)) + (float)$month['payroll_amount'];
$net           = $pendingIncome - $pendingExpenses;
$closing       = $opening + $net;
$generated     = date('d M Y H:i');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><title><?= htmlspecialchars($month['label']) ?> — Cash Flow Report</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:72px 40px 40px;max-width:960px;margin:0 auto }
.header-row { display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:24px;padding-bottom:16px;border-bottom:2px solid #1b4b8a }
.stats-grid { display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:28px }
.stat { 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:18px;font-weight:800 }
.section { margin-bottom:28px }
.section-title { font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:#6b7280;margin-bottom:8px;padding-bottom:6px;border-bottom:1px solid #f3f4f6 }
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 }
.paid { color:#15803d;font-weight:700 }
.unpaid { color:#9ca3af }
.carried { color:#6d28d9;font-size:10px }
.amount { text-align:right;font-weight:700;white-space:nowrap }
.total-row td { font-weight:700;background:#f0f7ff!important;border-top:2px solid #1b4b8a }
.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 } thead th,tbody tr:nth-child(even),.total-row td { -webkit-print-color-adjust:exact;print-color-adjust:exact } }
</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 PDF</button>
  <button onclick="window.close()" style="background:#f3f4f6;color:#374151;border:none;padding:8px 14px;border-radius:6px;cursor:pointer">✕ Close</button>
  <span style="margin-left:auto;font-size:11px;color:#6b7280"><?= htmlspecialchars($month['label']) ?> · <?= $month['status'] === 'closed' ? '🔒 Closed' : '🟢 Active' ?></span>
</div>

<div class="page">
  <div class="header-row">
    <div>
      <div style="font-size:22px;font-weight:800;color:#1b4b8a">⚡ <?= htmlspecialchars($company) ?></div>
      <div style="font-size:14px;color:#6b7280">Cash Flow Report — <?= htmlspecialchars($month['label']) ?></div>
    </div>
    <div style="text-align:right;font-size:11px;color:#6b7280;line-height:1.8">
      <strong>Opening Balance:</strong> <?= fmt($opening) ?><br>
      <?php if ($month['payroll_amount'] > 0): ?><strong>Payroll:</strong> <?= fmt($month['payroll_amount']) ?><br><?php endif; ?>
      <strong>Generated:</strong> <?= $generated ?>
    </div>
  </div>

  <div class="stats-grid" style="grid-template-columns:repeat(4,1fr)">
    <div class="stat">
      <div class="stat-label">In Bank (Opening)</div>
      <div class="stat-value" style="color:#1b4b8a"><?= fmt($opening) ?></div>
    </div>
    <div class="stat">
      <div class="stat-label">Income Total</div>
      <div class="stat-value" style="color:#15803d"><?= fmt($totalIncome) ?></div>
    </div>
    <div class="stat">
      <div class="stat-label">Expenses Total</div>
      <div class="stat-value" style="color:#dc2626"><?= fmt($totalExpenses) ?></div>
    </div>
    <div class="stat">
      <div class="stat-label">Still to Receive</div>
      <div class="stat-value" style="color:#0369a1"><?= fmt($pendingIncome) ?></div>
    </div>
    <div class="stat">
      <div class="stat-label">Still to Pay</div>
      <div class="stat-value" style="color:#b45309"><?= fmt($pendingExpenses) ?></div>
    </div>
    <div class="stat">
      <div class="stat-label">Net Pending</div>
      <div class="stat-value" style="color:<?= $net >= 0 ? '#15803d' : '#dc2626' ?>"><?= fmt($net) ?></div>
    </div>
    <div class="stat" style="grid-column:span 2">
      <div class="stat-label">Projected Balance (In Bank + Net Pending)</div>
      <div class="stat-value" style="color:<?= $closing >= 0 ? '#15803d' : '#dc2626' ?>"><?= fmt($closing) ?></div>
    </div>
  </div>
  <div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:6px;padding:10px 16px;margin-bottom:28px;font-size:11px;color:#6b7280">
    ℹ️ <strong>Net Pending</strong> = unpaid income minus unpaid expenses. Paid items are excluded as they are already reflected in your In Bank figure.
  </div>

  <!-- Income -->
  <div class="section">
    <div class="section-title">Income</div>
    <table>
      <thead><tr><th>Description</th><th>Client</th><th>JC</th><th>Recurring</th><th>Status</th><th style="text-align:right">Amount</th></tr></thead>
      <tbody>
        <?php foreach ($income as $r):
          $amt = coalesce($r['actual_amount'], $r['expected_amount']);
        ?>
        <tr>
          <td style="font-weight:600"><?= htmlspecialchars($r['description']) ?><?php if($r['is_carried_over']): ?><br><span class="carried">↩ from <?= $r['carried_from'] ?></span><?php endif; ?></td>
          <td><?= htmlspecialchars($r['client_name']??'—') ?></td>
          <td><?= $r['job_number']??'—' ?></td>
          <td><?= $r['is_recurring'] ? '🔁'.($r['recur_end_month']?' until '.$r['recur_end_month']:'') : '—' ?></td>
          <td class="<?= $r['is_paid']?'paid':'unpaid' ?>"><?= $r['is_paid']?'✅ Paid':'Pending' ?></td>
          <td class="amount"><?= $amt ? fmt($amt) : '—' ?></td>
        </tr>
        <?php endforeach; ?>
        <tr class="total-row"><td colspan="5">TOTAL INCOME</td><td class="amount"><?= fmt($totalIncome) ?></td></tr>
      </tbody>
    </table>
  </div>

  <!-- Expenses -->
  <div class="section">
    <div class="section-title">Expenses</div>
    <table>
      <thead><tr><th>Description</th><th>Category</th><th>Recurring</th><th>Slip</th><th>Status</th><th style="text-align:right">Amount</th></tr></thead>
      <tbody>
        <?php if ($month['payroll_amount'] > 0): ?>
        <tr>
          <td style="font-weight:600">Payroll</td>
          <td>Salaries</td><td>—</td><td>—</td>
          <td class="paid">✅ Confirmed</td>
          <td class="amount"><?= fmt($month['payroll_amount']) ?></td>
        </tr>
        <?php endif; ?>
        <?php foreach ($expenses as $r):
          $amt = coalesce($r['actual_amount'], $r['expected_amount']);
        ?>
        <tr>
          <td style="font-weight:600"><?= htmlspecialchars($r['description']) ?><?php if($r['is_carried_over']): ?><br><span class="carried">↩ from <?= $r['carried_from'] ?></span><?php endif; ?></td>
          <td><?= htmlspecialchars($r['category']??'—') ?></td>
          <td><?= $r['is_recurring'] ? '🔁'.($r['recur_end_month']?' until '.$r['recur_end_month']:'') : '—' ?></td>
          <td><?= $r['slip_merchant'] ? '🧾 '.$r['slip_merchant'] : '—' ?></td>
          <td class="<?= $r['is_paid']?'paid':'unpaid' ?>"><?= $r['is_paid']?'✅ Paid':'Pending' ?></td>
          <td class="amount"><?= $amt ? fmt($amt) : '—' ?></td>
        </tr>
        <?php endforeach; ?>
        <tr class="total-row"><td colspan="5">TOTAL EXPENSES</td><td class="amount"><?= fmt($totalExpenses) ?></td></tr>
      </tbody>
    </table>
  </div>

  <!-- Net summary -->
  <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:28px">
    <div style="border:1px solid #e5e7eb;border-radius:8px;padding:14px 16px">
      <div style="font-size:10px;font-weight:700;color:#6b7280;text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px">Net P/L</div>
      <div style="font-size:20px;font-weight:800;color:<?= $net >= 0 ? '#15803d' : '#dc2626' ?>"><?= fmt($net) ?></div>
    </div>
    <div style="border:1px solid #e5e7eb;border-radius:8px;padding:14px 16px">
      <div style="font-size:10px;font-weight:700;color:#6b7280;text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px">Closing Balance</div>
      <div style="font-size:20px;font-weight:800;color:<?= $closing >= 0 ? '#15803d' : '#dc2626' ?>"><?= fmt($closing) ?></div>
    </div>
  </div>

  <div class="footer">
    <span><?= htmlspecialchars($company) ?> — Cash Flow Report — <?= htmlspecialchars($month['label']) ?></span>
    <span>Generated <?= $generated ?></span>
  </div>
</div>
</body>
</html>