<?php
declare(strict_types=1);

/**
 * modules/payments/partner_receipt.php
 *
 * Standalone printable receipt for a BULK partner payment (batch_ref).
 * No app chrome included — clean single-page print/PDF.
 */

require_once dirname(__DIR__, 2) . '/config/functions.php';
require_role(['MD','Accounts','Admin','Management']);

$user = current_user();
$cid  = (int)($user['company_id'] ?? 0);
if ($cid <= 0) redirect(url_public('login.php'));

$errors = [];
$batchRef = trim((string)($_GET['batch_ref'] ?? ''));

function tbl_exists(string $t): bool {
  try { db()->query("SELECT 1 FROM `{$t}` LIMIT 1"); return true; }
  catch (Throwable) { return false; }
}
function decode_bank(?string $json): array {
  $defaults = ['bank_name'=>'','account_name'=>'','account_number'=>'','sort_code'=>'','iban'=>'','swift'=>'','notes'=>''];
  if (!$json) return $defaults;
  $arr = json_decode($json, true);
  return is_array($arr) ? array_merge($defaults, array_intersect_key($arr, $defaults)) : $defaults;
}
/** Build a safe SQL expression for partner due using only existing bookings columns. */
function partner_due_expr(string $alias='partner_due'): string {
  static $cache = null;
  if ($cache === null) {
    $cache = [];
    try {
      $rs = db()->query("SHOW COLUMNS FROM bookings");
      foreach ($rs->fetchAll() as $c) $cache[strtolower((string)$c['Field'])] = true;
    } catch (Throwable) { $cache = []; }
  }
  $cands = [
    'partner_due',
    'partner_amount',
    'partner_commission_amount',
    'partner_commission',
    'partner_fee',
    'partner_total',
    'total_partner_price',
  ];
  $use = [];
  foreach ($cands as $c) if (isset($cache[strtolower($c)])) $use[] = "b.`{$c}`";
  if (!$use) return "0 AS {$alias}";
  return 'COALESCE(' . implode(',', $use) . ") AS {$alias}";
}

if ($batchRef === '') {
  $errors[] = 'Missing batch reference.';
}

$header = null;
$partner = null;
$partnerBank = [];
$rows   = [];

if (!$errors) {
  if (!tbl_exists('partner_payouts')) {
    $errors[] = 'partner_payouts table missing.';
  } else {
    try {
      // Batch meta (one partner per batch)
      $h = db()->prepare("
        SELECT
          pp.partner_id,
          MIN(pp.paid_at) AS paid_at,
          COALESCE(MAX(pp.method), NULL) AS method,
          COALESCE(MAX(pp.reference), NULL) AS reference,
          SUM(pp.amount) AS total_paid
        FROM partner_payouts pp
        WHERE pp.company_id=:cid AND pp.batch_ref=:br
        GROUP BY pp.partner_id
        LIMIT 1
      ");
      $h->execute([':cid'=>$cid, ':br'=>$batchRef]);
      $header = $h->fetch() ?: null;
      if (!$header) throw new RuntimeException('Batch not found or access denied.');

      // Partner + bank
      $p = db()->prepare("SELECT id, name, email, phone, address, bank_details FROM partners WHERE company_id=:cid AND id=:pid LIMIT 1");
      $p->execute([':cid'=>$cid, ':pid'=>(int)$header['partner_id']]);
      $partner = $p->fetch() ?: [];
      $partnerBank = decode_bank((string)($partner['bank_details'] ?? ''));

      // Bookings included in this batch
      $q = db()->prepare("
        SELECT
          pp.booking_id,
          pp.amount AS paid_now,
          b.booking_ref,
          b.client_name,
          b.pickup_date,
          b.pickup_time,
          " . partner_due_expr('partner_due') . "
        FROM partner_payouts pp
        JOIN bookings b ON b.id=pp.booking_id AND b.company_id=pp.company_id
        WHERE pp.company_id=:cid AND pp.batch_ref=:br
        ORDER BY b.pickup_date ASC, b.pickup_time ASC, pp.booking_id ASC
        LIMIT 2000
      ");
      $q->execute([':cid'=>$cid, ':br'=>$batchRef]);
      $rows = $q->fetchAll() ?: [];
    } catch (Throwable $e) {
      $errors[] = (defined('APP_ENV') && APP_ENV==='dev') ? $e->getMessage() : 'Unable to load receipt.';
    }
  }
}

// Convenience totals
$sumDue = 0.0; $sumNow = 0.0;
foreach ($rows as $r) {
  $sumDue += (float)($r['partner_due'] ?? 0);
  $sumNow += (float)($r['paid_now'] ?? 0);
}

// Company logo URL (public)
$logoUrl = url_public('assets/logo.png');

// A friendly title for the window/tab
$title = 'Payment Receipt — Partner Payment — ' . $batchRef;
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title><?= e($title) ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    :root { --fg:#222; --muted:#6c757d; --line:#e9ecef; }
    html,body{margin:0;padding:0;background:#fff;color:var(--fg);font:14px/1.4 system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,"Apple Color Emoji","Segoe UI Emoji";}

    .wrap { max-width:1000px; margin:24px auto; padding:0 16px; }
    .head { display:flex; align-items:center; justify-content:space-between; gap:24px; }
    .logo img { max-height:64px; }
    .meta { text-align:right; }
    .title { font-size:22px; font-weight:700; margin-bottom:2px; }
    .muted { color:var(--muted); }
    .card { border:1px solid var(--line); border-radius:8px; padding:12px; }
    .grid { display:grid; gap:16px; grid-template-columns: 1fr 1fr; }
    .h6 { font-size:14px; font-weight:700; margin:0 0 6px; }

    table { width:100%; border-collapse:collapse; }
    thead th { background:#f8f9fa; border-bottom:1px solid var(--line); text-align:left; padding:8px; font-weight:600; }
    tbody td { border-bottom:1px solid var(--line); padding:8px; }
    tfoot th { background:#f8f9fa; border-top:2px solid var(--line); padding:8px; text-align:right; }
    .text-end { text-align:right; }
    .no-print { margin-top:12px; display:flex; justify-content:flex-end; gap:8px; }
    .btn { appearance:none; border:1px solid #333; background:#fff; color:#333; padding:8px 12px; border-radius:6px; cursor:pointer; }
    .btn:hover { background:#f3f3f3; }

    @media print {
      .no-print { display:none !important; }
      body { -webkit-print-color-adjust:exact; print-color-adjust:exact; }
      @page { margin: 12mm; }
    }
  </style>
</head>
<body>
  <div class="wrap">
    <?php if ($errors): ?>
      <div class="card" style="border-color:#f5c2c7;background:#fff0f1;color:#842029;">
        <strong>Unable to render receipt:</strong>
        <ul style="margin:6px 0 0 18px;">
          <?php foreach($errors as $er): ?><li><?= e($er) ?></li><?php endforeach; ?>
        </ul>
      </div>
    <?php else: ?>
      <div class="head" style="margin-bottom:14px;">
        <div class="logo">
          <img src="<?= e($logoUrl) ?>" alt="Company Logo">
        </div>
        <div class="meta">
          <div class="title">Payment Receipt</div>
          <div>Subject: <strong>Partner Payment</strong></div>
          <div>Batch Ref: <strong><?= e($batchRef) ?></strong></div>
          <div>Paid At: <?= e((string)$header['paid_at']) ?></div>
          <div>Method: <?= e((string)($header['method'] ?? '—')) ?></div>
          <div>Reference: <?= e((string)($header['reference'] ?? '—')) ?></div>
          <div>Total Paid: <strong>£<?= number_format((float)$header['total_paid'], 2) ?></strong></div>
        </div>
      </div>

      <div class="grid" style="margin-bottom:14px;">
        <div class="card">
          <div class="h6">Partner</div>
          <div style="font-weight:600"><?= e($partner['name'] ?? '—') ?></div>
          <?php if (!empty($partner['email']) || !empty($partner['phone'])): ?>
            <div class="muted">
              <?= e($partner['email'] ?? '') ?><?= (!empty($partner['email']) && !empty($partner['phone'])) ? ' · ' : '' ?><?= e($partner['phone'] ?? '') ?>
            </div>
          <?php endif; ?>
          <?php if (!empty($partner['address'])): ?>
            <div class="muted" style="white-space:pre-wrap; margin-top:4px;"><?= e($partner['address']) ?></div>
          <?php endif; ?>
        </div>
        <div class="card">
          <div class="h6">Bank Details</div>
          <div><span class="muted">Bank:</span> <?= e($partnerBank['bank_name'] ?: '—') ?></div>
          <div><span class="muted">Account Name:</span> <?= e($partnerBank['account_name'] ?: '—') ?></div>
          <div><span class="muted">Account No:</span> <?= e($partnerBank['account_number'] ?: '—') ?></div>
          <div><span class="muted">Sort Code:</span> <?= e($partnerBank['sort_code'] ?: '—') ?></div>
          <?php if (!empty($partnerBank['iban'])): ?><div><span class="muted">IBAN:</span> <?= e($partnerBank['iban']) ?></div><?php endif; ?>
          <?php if (!empty($partnerBank['swift'])): ?><div><span class="muted">SWIFT:</span> <?= e($partnerBank['swift']) ?></div><?php endif; ?>
          <?php if (!empty($partnerBank['notes'])): ?><div class="muted" style="white-space:pre-wrap; margin-top:4px;"><?= e($partnerBank['notes']) ?></div><?php endif; ?>
        </div>
      </div>

      <div class="card" style="margin-bottom:14px;">
        <table>
          <thead>
            <tr>
              <th>Booking Ref</th>
              <th>Client</th>
              <th>Pickup</th>
              <th class="text-end">£ Partner Due</th>
              <th class="text-end">£ Paid (This Receipt)</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($rows as $r): ?>
              <tr>
                <td><?= e($r['booking_ref'] ?? ('#'.$r['booking_id'])) ?></td>
                <td><?= e($r['client_name'] ?? '—') ?></td>
                <td><?= e(trim((string)($r['pickup_date'] ?? '') . ' ' . (string)($r['pickup_time'] ?? ''))) ?></td>
                <td class="text-end">£<?= number_format((float)($r['partner_due'] ?? 0), 2) ?></td>
                <td class="text-end" style="font-weight:600;">£<?= number_format((float)($r['paid_now'] ?? 0), 2) ?></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
          <tfoot>
            <tr>
              <th colspan="3">Totals:</th>
              <th class="text-end">£<?= number_format($sumDue, 2) ?></th>
              <th class="text-end">£<?= number_format($sumNow, 2) ?></th>
            </tr>
          </tfoot>
        </table>
      </div>

      <div class="muted" style="margin-bottom:8px;">
        This receipt aggregates multiple bookings paid together under the batch reference above.
      </div>

      <div class="no-print">
        <button class="btn" onclick="window.print()">🖨️ Print / Save PDF</button>
        <button class="btn" onclick="history.back()">← Back</button>
      </div>
    <?php endif; ?>
  </div>
</body>
</html>
