<?php
// api/payment_report.php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../config.php';

// -------------------- BRAND (Safe Step) --------------------
$brandName   = "Safe Step";
$brandLegal  = "Safe Step Properties Limited";
$brandPhone  = "+234 814 241 1113";
$brandWhats  = "+234 704 646 6653";
$brandAddr   = "Suite 02, Jahi Mall, Valentine Nwabuaeze Crescent, Jahi, FCT Abuja.";
$brandEmail  = "info@safestepproperties.com";
$brandTag    = "Sales, Investment & Property Management";

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

function parseDateOrNull($s) {
    if (!$s) return null;
    $t = strtotime((string)$s);
    return $t ? date('Y-m-d', $t) : null;
}

$start      = isset($_POST['start_date']) ? parseDateOrNull($_POST['start_date']) : null;
$end        = isset($_POST['end_date'])   ? parseDateOrNull($_POST['end_date'])   : null;
$quickRange = isset($_POST['quick_range']) ? trim((string)$_POST['quick_range']) : '';
$exportType = isset($_POST['export_type']) ? strtoupper(trim((string)$_POST['export_type'])) : 'HTML';

// -------------------- WHERE --------------------
$where  = ['(p.IsDeleted IS NULL OR p.IsDeleted = 0)'];
$params = [];

if ($start) {
    $where[] = 'p.PaymentDate >= :start';
    $params[':start'] = $start;
}
if ($end) {
    $where[] = 'p.PaymentDate <= :end';
    $params[':end'] = $end;
}

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

// -------------------- QUERY --------------------
$sql = "
    SELECT
        p.Id,
        p.PaymentDate,
        p.InvoiceNumber,
        p.Amount,
        p.Method,
        p.Reference,
        p.ProofFilePath,

        c.FullName    AS ClientName,
        c.ClientId    AS ClientCode,
        c.Phone       AS ClientPhone,
        c.Email       AS ClientEmail,

        a.Name        AS AreaName,
        pl.Code       AS PlotCode,
        cc.Id         AS ContractId,
        cc.FinalPrice AS ContractFinalPrice,
        cc.Status     AS ContractStatus
    FROM ClientPayments p
    INNER JOIN ClientContracts cc ON cc.Id = p.ContractId
    INNER JOIN Clients c          ON c.Id  = cc.ClientId
    INNER JOIN Plots pl           ON pl.Id = cc.PlotId
    INNER JOIN Areas a            ON a.Id  = pl.AreaId
    $whereSql
    ORDER BY p.PaymentDate DESC, p.Id DESC
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// -------------------- TOTALS --------------------
$totalReceived    = 0.0;
$totalExpected    = 0.0;
$totalOutstanding = 0.0;
$totalPayments    = count($rows);

$contractTotals = []; // contractId => ['finalPrice'=>x,'totalPaid'=>y,'status'=>s]

foreach ($rows as $r) {
    $amount = (float)($r['Amount'] ?? 0);
    $totalReceived += $amount;

    $contractId   = (int)($r['ContractId'] ?? 0);
    $finalPrice   = (float)($r['ContractFinalPrice'] ?? 0);
    $contractStat = (string)($r['ContractStatus'] ?? '');

    if (!isset($contractTotals[$contractId])) {
        $contractTotals[$contractId] = [
            'finalPrice' => $finalPrice,
            'totalPaid'  => 0.0,
            'status'     => $contractStat,
        ];
    }

    $contractTotals[$contractId]['totalPaid'] += $amount;
}

foreach ($contractTotals as $ct) {
    $finalPrice = (float)$ct['finalPrice'];
    $paid       = (float)$ct['totalPaid'];
    $status     = (string)$ct['status'];

    if (strcasecmp($status, 'Cancelled') === 0) {
        continue;
    }

    $totalExpected += $finalPrice;

    $outstanding = max($finalPrice - $paid, 0.0);
    if (strcasecmp($status, 'Completed') === 0) {
        $outstanding = 0.0;
    }
    $totalOutstanding += $outstanding;
}

// -------------------- EXPORT: EXCEL (CSV) --------------------
if ($exportType === 'EXCEL') {
    $filename = 'safe_step_payments_report_' . date('Ymd_His') . '.csv';

    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');

    $out = fopen('php://output', 'w');
    fwrite($out, "\xEF\xBB\xBF"); // UTF-8 BOM

    fputcsv($out, [
        'Date',
        'Invoice',
        'Client',
        'Client ID',
        'Phone',
        'Email',
        'Area',
        'Plot',
        'Amount',
        'Method',
        'Reference',
        'Contract ID',
        'Contract Status',
        'Has Proof'
    ]);

    foreach ($rows as $r) {
        $date = !empty($r['PaymentDate']) ? date('d M Y', strtotime($r['PaymentDate'])) : '';
        fputcsv($out, [
            $date,
            (string)$r['InvoiceNumber'],
            (string)$r['ClientName'],
            (string)$r['ClientCode'],
            (string)$r['ClientPhone'],
            (string)$r['ClientEmail'],
            (string)$r['AreaName'],
            (string)$r['PlotCode'],
            number_format((float)$r['Amount'], 2, '.', ''),
            (string)$r['Method'],
            (string)$r['Reference'],
            (string)$r['ContractId'],
            (string)$r['ContractStatus'],
            !empty($r['ProofFilePath']) ? 'YES' : 'NO',
        ]);
    }

    fclose($out);
    exit;
}

function formatPeriod($start, $end): string {
    if ($start && $end) {
        return date('d M Y', strtotime($start)) . ' - ' . date('d M Y', strtotime($end));
    }
    if ($start) {
        return 'From ' . date('d M Y', strtotime($start));
    }
    if ($end) {
        return 'Up to ' . date('d M Y', strtotime($end));
    }
    return 'All time';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Payments Report | <?php echo h($brandLegal); ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    :root {
      --brand-blue: #125db8;
      --brand-blue-dark: #07356f;
      --brand-blue-soft: #eaf3ff;
      --brand-green: #3baa15;
      --brand-green-dark: #257b0b;
      --ink: #0b1b33;
      --muted: #5d6a7c;
      --line: #dbe4ef;
      --surface: #f6f9fc;
      --surface-strong: #eef5fb;
      --white: #ffffff;
      --footer: #06172d;
      --shadow: 0 18px 50px rgba(7, 53, 111, 0.12);
      --shadow-soft: 0 10px 28px rgba(7, 53, 111, 0.08);
      --radius: 8px;
      --container: 1180px;
    }

    body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      background:
        radial-gradient(circle at top left, rgba(59,170,21,0.08), transparent 22%),
        radial-gradient(circle at bottom right, rgba(18,93,184,0.08), transparent 24%),
        var(--surface);
      color: var(--ink);
      padding: 20px;
    }

    .page {
      max-width: 1180px;
      margin: 0 auto;
      position: relative;
    }

    .watermark {
      position: fixed;
      top: 52%;
      left: 50%;
      transform: translate(-50%, -50%);
      opacity: 0.04;
      z-index: 0;
      pointer-events: none;
    }

    .watermark img {
      width: 52vw;
      max-width: 560px;
      height: auto;
      display: block;
    }

    .actions {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
      margin-bottom: 14px;
      position: relative;
      z-index: 2;
    }

    .btn {
      display: inline-block;
      border: 1px solid var(--brand-blue);
      background: linear-gradient(135deg, var(--brand-blue), var(--brand-green));
      color: #fff;
      padding: 10px 16px;
      border-radius: 12px;
      font-size: 12px;
      font-weight: 800;
      text-transform: uppercase;
      letter-spacing: .14em;
      cursor: pointer;
      box-shadow: 0 10px 20px rgba(18,93,184,.14);
    }

    .btn.alt {
      background: #fff;
      color: var(--brand-blue);
      border-color: rgba(15,23,42,.14);
      box-shadow: none;
    }

    .report-shell {
      position: relative;
      z-index: 1;
      background: rgba(255,255,255,0.98);
      border: 1px solid var(--line);
      border-radius: 24px;
      padding: 26px;
      box-shadow: 0 18px 44px rgba(2,8,23,.06);
      overflow: hidden;
    }

    .report-shell::before {
      content: "";
      position: absolute;
      inset: 0;
      pointer-events: none;
      background:
        radial-gradient(circle at top right, rgba(59,170,21,.05), transparent 18%),
        radial-gradient(circle at bottom left, rgba(18,93,184,.04), transparent 18%);
    }

    .topbar {
      position: relative;
      z-index: 1;
      display: flex;
      justify-content: space-between;
      gap: 20px;
      border-bottom: 1px solid var(--line);
      padding-bottom: 18px;
      margin-bottom: 18px;
    }

    .brand {
      display: flex;
      align-items: flex-start;
      gap: 16px;
      min-width: 0;
    }

    .brand-logo {
      width: 88px;
      height: auto;
      object-fit: contain;
      flex-shrink: 0;
      display: block;
    }

    .brand-copy h1 {
      font-size: 18px;
      font-weight: 900;
      letter-spacing: .16em;
      text-transform: uppercase;
      color: var(--ink);
      margin-bottom: 4px;
    }

    .brand-copy .tag {
      font-size: 11px;
      font-weight: 800;
      color: var(--brand-blue);
      margin-bottom: 6px;
      text-transform: uppercase;
      letter-spacing: .12em;
    }

    .brand-copy p {
      font-size: 11px;
      line-height: 1.6;
      color: var(--muted);
    }

    .meta {
      text-align: right;
      min-width: 250px;
    }

    .meta .chip {
      display: inline-block;
      padding: 7px 12px;
      border-radius: 999px;
      background: var(--brand-blue-soft);
      border: 1px solid rgba(59,170,21,.18);
      color: var(--brand-blue);
      font-size: 10px;
      font-weight: 900;
      letter-spacing: .14em;
      text-transform: uppercase;
      margin-bottom: 10px;
    }

    .meta h2 {
      font-size: 13px;
      font-weight: 900;
      text-transform: uppercase;
      letter-spacing: .20em;
      color: var(--ink);
      margin-bottom: 8px;
    }

    .meta p {
      font-size: 11px;
      line-height: 1.6;
      color: var(--muted);
    }

    .section {
      position: relative;
      z-index: 1;
      margin-bottom: 20px;
    }

    .section-title {
      font-size: 10px;
      text-transform: uppercase;
      letter-spacing: .22em;
      color: var(--muted);
      font-weight: 900;
      margin-bottom: 10px;
    }

    .summary-grid {
      display: grid;
      grid-template-columns: repeat(4, minmax(0, 1fr));
      gap: 14px;
    }

    .summary-card {
      background: #fff;
      border: 1px solid var(--line);
      border-radius: 18px;
      padding: 14px;
    }

    .summary-label {
      font-size: 10px;
      font-weight: 900;
      letter-spacing: .15em;
      text-transform: uppercase;
      color: var(--muted);
      margin-bottom: 8px;
    }

    .summary-value {
      font-size: 22px;
      font-weight: 900;
      color: var(--ink);
      line-height: 1.1;
    }

    .summary-value.success { color: var(--brand-green-dark); }
    .summary-value.danger { color: #b42318; }

    .meta-grid {
      display: grid;
      grid-template-columns: repeat(3, minmax(0, 1fr));
      gap: 14px;
    }

    .meta-card {
      background: var(--brand-blue-soft);
      border: 1px solid rgba(59,170,21,.14);
      border-radius: 16px;
      padding: 14px;
    }

    .meta-card .k {
      font-size: 10px;
      text-transform: uppercase;
      letter-spacing: .14em;
      font-weight: 900;
      color: var(--muted);
      margin-bottom: 6px;
    }

    .meta-card .v {
      font-size: 13px;
      font-weight: 800;
      color: var(--ink);
    }

    .table-wrap {
      border: 1px solid var(--line);
      border-radius: 18px;
      overflow: hidden;
      background: #fff;
    }

    table {
      width: 100%;
      border-collapse: collapse;
      font-size: 12px;
    }

    thead th {
      background: var(--brand-blue-soft);
      color: var(--muted);
      padding: 12px 10px;
      text-align: left;
      font-size: 10px;
      font-weight: 900;
      text-transform: uppercase;
      letter-spacing: .12em;
      border-bottom: 1px solid var(--line);
      white-space: nowrap;
    }

    tbody td {
      padding: 11px 10px;
      border-top: 1px solid rgba(15,23,42,.06);
      color: #0f172a;
      vertical-align: top;
    }

    tbody tr:nth-child(even) {
      background: #fcfeff;
    }

    .amount {
      text-align: right;
      white-space: nowrap;
      font-variant-numeric: tabular-nums;
      font-weight: 800;
    }

    .plot-code {
      font-weight: 900;
      color: var(--brand-blue);
      letter-spacing: .04em;
      white-space: nowrap;
    }

    .status-badge {
      display: inline-block;
      padding: 5px 10px;
      border-radius: 999px;
      font-size: 9px;
      font-weight: 900;
      text-transform: uppercase;
      letter-spacing: .14em;
      white-space: nowrap;
      border: 1px solid transparent;
    }

    .status-active {
      background: #ecfdf3;
      color: var(--brand-green-dark);
      border-color: #abefc6;
    }

    .status-pending {
      background: #fff6ed;
      color: #b54708;
      border-color: #fed7aa;
    }

    .status-cancelled {
      background: #fef3f2;
      color: #b42318;
      border-color: #fecaca;
    }

    .footer {
      position: relative;
      z-index: 1;
      border-top: 1px solid var(--line);
      padding-top: 12px;
      margin-top: 12px;
      color: var(--muted);
      font-size: 10px;
      line-height: 1.6;
    }

    @media print {
      body {
        background: #fff;
        padding: 0;
      }

      .actions {
        display: none;
      }

      .page {
        max-width: none;
        margin: 0;
      }

      .report-shell {
        border: none;
        border-radius: 0;
        box-shadow: none;
      }
    }

    @media (max-width: 980px) {
      .summary-grid,
      .meta-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
      }
    }

    @media (max-width: 760px) {
      .topbar {
        flex-direction: column;
      }

      .meta {
        text-align: left;
        min-width: 0;
      }

      .brand {
        flex-direction: column;
      }

      .brand-logo {
        width: 72px;
      }

      .summary-grid,
      .meta-grid {
        grid-template-columns: 1fr;
      }

      body {
        padding: 12px;
      }

      .report-shell {
        padding: 18px;
      }
    }
  </style>
</head>
<body>
<div class="page">

  <div class="watermark">
    <img src="logo-safe-step.png" alt="<?php echo h($brandLegal); ?> Watermark">
  </div>

  <div class="actions">
    <button class="btn alt" onclick="window.print()">Print</button>
    <button class="btn" onclick="window.print()">Download PDF</button>
  </div>

  <div class="report-shell">
    <div class="topbar">
      <div class="brand">
        <img src="logo-safe-step.png" alt="<?php echo h($brandLegal); ?>" class="brand-logo">
        <div class="brand-copy">
          <h1><?php echo h($brandName); ?></h1>
          <div class="tag"><?php echo h($brandTag); ?></div>
          <p><?php echo h($brandLegal); ?></p>
          <p><?php echo h($brandAddr); ?></p>
          <p>
            Contact: <?php echo h($brandPhone); ?><br>
            WhatsApp: <?php echo h($brandWhats); ?><br>
            Email: <?php echo h($brandEmail); ?>
          </p>
        </div>
      </div>

      <div class="meta">
        <div class="chip">Payments Report</div>
        <h2>Collection Summary</h2>
        <p><strong>Period:</strong> <?php echo h(formatPeriod($start, $end)); ?></p>
        <p><strong>Quick Range:</strong> <?php echo h($quickRange ?: 'N/A'); ?></p>
        <p><strong>Generated:</strong> <?php echo h(date('d M Y H:i')); ?></p>
      </div>
    </div>

    <div class="section">
      <div class="section-title">Performance Summary</div>
      <div class="summary-grid">
        <div class="summary-card">
          <div class="summary-label">Payments Count</div>
          <div class="summary-value"><?php echo h(number_format($totalPayments)); ?></div>
        </div>
        <div class="summary-card">
          <div class="summary-label">Total Received</div>
          <div class="summary-value success">₦<?php echo h(number_format($totalReceived, 2)); ?></div>
        </div>
        <div class="summary-card">
          <div class="summary-label">Total Expected</div>
          <div class="summary-value">₦<?php echo h(number_format($totalExpected, 2)); ?></div>
        </div>
        <div class="summary-card">
          <div class="summary-label">Outstanding</div>
          <div class="summary-value danger">₦<?php echo h(number_format($totalOutstanding, 2)); ?></div>
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-title">Report Metadata</div>
      <div class="meta-grid">
        <div class="meta-card">
          <div class="k">Export Type</div>
          <div class="v"><?php echo h($exportType); ?></div>
        </div>
        <div class="meta-card">
          <div class="k">Active Date Filter</div>
          <div class="v"><?php echo h(formatPeriod($start, $end)); ?></div>
        </div>
        <div class="meta-card">
          <div class="k">Contracts Considered</div>
          <div class="v"><?php echo h(number_format(count($contractTotals))); ?></div>
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-title">Payment Transactions</div>
      <div class="table-wrap">
        <table>
          <thead>
            <tr>
              <th>Date</th>
              <th>Invoice</th>
              <th>Client</th>
              <th>Client ID</th>
              <th>Area</th>
              <th>Plot</th>
              <th class="amount">Amount (₦)</th>
              <th>Method</th>
              <th>Reference</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
          <?php if (!count($rows)): ?>
            <tr>
              <td colspan="10" style="text-align:center; color:#64748b; padding:14px;">
                No payments found for the selected period.
              </td>
            </tr>
          <?php else: ?>
            <?php foreach ($rows as $r): ?>
              <?php
                $date = !empty($r['PaymentDate']) ? date('d M Y', strtotime($r['PaymentDate'])) : '';
                $status = trim((string)($r['ContractStatus'] ?? ''));
                $statusLower = strtolower($status);

                $statusClass = 'status-pending';
                if ($statusLower === 'completed') $statusClass = 'status-active';
                if ($statusLower === 'cancelled') $statusClass = 'status-cancelled';
              ?>
              <tr>
                <td><?php echo h($date); ?></td>
                <td><?php echo h($r['InvoiceNumber']); ?></td>
                <td><?php echo h($r['ClientName']); ?></td>
                <td><?php echo h($r['ClientCode']); ?></td>
                <td><?php echo h($r['AreaName']); ?></td>
                <td class="plot-code"><?php echo h($r['PlotCode']); ?></td>
                <td class="amount">₦<?php echo h(number_format((float)$r['Amount'], 2)); ?></td>
                <td><?php echo h($r['Method']); ?></td>
                <td><?php echo h($r['Reference']); ?></td>
                <td>
                  <span class="status-badge <?php echo h($statusClass); ?>">
                    <?php echo h($status ?: 'N/A'); ?>
                  </span>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

    <div class="footer">
      <p>This report summarizes payment transactions recorded in the <?php echo h($brandLegal); ?> system.</p>
      <p>All figures are subject to verification against underlying contracts and payment records.</p>
      <p>Address: <?php echo h($brandAddr); ?> · Phone: <?php echo h($brandPhone); ?> / <?php echo h($brandWhats); ?> · Email: <?php echo h($brandEmail); ?></p>
    </div>
  </div>
</div>
</body>
</html>
