<?php
declare(strict_types=1);

/**
 * modules/payments/driver_receipt.php
 * Printable Driver Payment Receipt
 *
 * GET:
 *   - payout_id (required): driver_payouts.id
 *   - return (optional): URL to go back to (e.g., drivers.php?from=...&to=...)
 */

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 = [];
$payoutId  = (int)($_GET['payout_id'] ?? 0);
$returnUrl = (string)($_GET['return'] ?? url_modules('payments/drivers.php'));

/* -----------------------------
   Helpers
------------------------------*/
function decode_bank_receipt(?string $raw): array {
  $out = [
    'bank_name'=>'','account_name'=>'','account_number'=>'','sort_code'=>'',
    'iban'=>'','swift'=>'','notes'=>''
  ];
  if (!$raw) return $out;

  // Try JSON first
  $j = json_decode($raw, true);
  if (is_array($j)) {
    foreach ($out as $k => $_) {
      if (isset($j[$k]) && is_string($j[$k])) $out[$k] = trim((string)$j[$k]);
    }
    return $out;
  }

  // Fallback to "Label: value" lines
  foreach (preg_split('/\r\n|\r|\n/', (string)$raw) as $line) {
    $line = trim($line);
    if ($line === '') continue;
    if (preg_match('/^(bank\s*name)\s*[:\-]\s*(.+)$/i', $line, $m))          { $out['bank_name']      = trim($m[2]); continue; }
    if (preg_match('/^(account\s*name|account\s*holder)\s*[:\-]\s*(.+)$/i',$line,$m)) { $out['account_name']   = trim($m[2]); continue; }
    if (preg_match('/^(account\s*number|acc(?:ount)?\.?|acc)\s*[:\-]\s*(.+)$/i',$line,$m)) { $out['account_number'] = trim($m[2]); continue; }
    if (preg_match('/^(sort\s*code|sort)\s*[:\-]\s*([0-9\-\s]+)$/i', $line, $m)) { $out['sort_code']      = trim($m[2]); continue; }
    if (preg_match('/^(iban)\s*[:\-]\s*(.+)$/i', $line, $m))                 { $out['iban']           = trim($m[2]); continue; }
    if (preg_match('/^(swift|bic)\s*[:\-]\s*(.+)$/i', $line, $m))            { $out['swift']          = trim($m[2]); continue; }
    $out['notes'] .= ($out['notes'] ? "\n" : "") . $line;
  }
  return $out;
}

function driver_paid_sum_receipt(int $companyId, int $bookingId): float {
  try {
    $q = db()->prepare("SELECT COALESCE(SUM(amount),0) FROM driver_payouts WHERE company_id=:cid AND booking_id=:bid");
    $q->execute([':cid'=>$companyId, ':bid'=>$bookingId]);
    return (float)$q->fetchColumn();
  } catch (Throwable $e) { return 0.0; }
}

function app_logo_url(): string {
  if (defined('APP_LOGO_URL') && APP_LOGO_URL) return (string)APP_LOGO_URL;
  // Your logo lives at cmrs/public/assets/logo.png
  return url_public('assets/logo.png');
}

/* -----------------------------
   Load data
------------------------------*/
if ($payoutId <= 0) {
  $errors[] = 'Missing payout_id.';
}

$payout = $booking = $driver = [];
$driverBank = [];
$totals = ['base'=>0.0,'parking'=>0.0,'waiting'=>0.0,'due'=>0.0,'paid_this'=>0.0,'paid_to_date'=>0.0,'outstanding'=>0.0];

if (!$errors) {
  try {
    // 1) Payout row
    $qp = db()->prepare("
      SELECT dp.*
        FROM driver_payouts dp
       WHERE dp.id=:pid AND dp.company_id=:cid
       LIMIT 1
    ");
    $qp->execute([':pid'=>$payoutId, ':cid'=>$cid]);
    $payout = $qp->fetch() ?: [];
    if (!$payout) throw new RuntimeException('Payout not found or access denied.');

    $bid = (int)$payout['booking_id'];
    $did = (int)$payout['driver_id'];

    // 2) Booking (these columns exist in your schema)
    $qb = db()->prepare("
      SELECT
        id, booking_ref, client_name,
        pickup_date, pickup_time,
        pickup_address, dropoff_address,
        COALESCE(total_driver_price,0) AS driver_price,
        COALESCE(driver_parking_fee,0) AS driver_parking,
        COALESCE(driver_waiting_fee,0) AS driver_waiting
      FROM bookings
      WHERE id=:bid AND company_id=:cid
      LIMIT 1
    ");
    $qb->execute([':bid'=>$bid, ':cid'=>$cid]);
    $booking = $qb->fetch() ?: [];

    // 3) Driver + bank
    $qdv = db()->prepare("SELECT name, email, phone, bank_details FROM drivers WHERE id=:id AND company_id=:cid LIMIT 1");
    $qdv->execute([':id'=>$did, ':cid'=>$cid]);
    $driver = $qdv->fetch() ?: [];
    $driverBank = decode_bank_receipt((string)($driver['bank_details'] ?? ''));

    // 4) Totals
    $base    = (float)($booking['driver_price']   ?? 0.0);
    $parking = (float)($booking['driver_parking'] ?? 0.0);
    $waiting = (float)($booking['driver_waiting'] ?? 0.0);
    $due     = $base + $parking + $waiting;

    $paidThis    = (float)($payout['amount'] ?? 0.0);
    $paidToDate  = driver_paid_sum_receipt($cid, $bid);
    $outstanding = max(0.0, round($due - $paidToDate, 2));

    $totals = [
      'base'         => $base,
      'parking'      => $parking,
      'waiting'      => $waiting,
      'due'          => $due,
      'paid_this'    => $paidThis,
      'paid_to_date' => $paidToDate,
      'outstanding'  => $outstanding,
    ];
  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV==='dev') ? $e->getMessage() : 'Unable to load receipt.';
  }
}

include dirname(__DIR__, 2) . '/includes/header.php';
?>
<style>
  .receipt-container { max-width: 900px; margin: 0 auto; }
  .receipt-header { display:flex; align-items:center; justify-content:space-between; gap:16px; }
  .receipt-logo img { height:56px; }
  .receipt-title { font-size:1.5rem; font-weight:700; }
  .meta-grid { display:grid; grid-template-columns: 1fr 1fr; gap:10px; }
  @media (max-width: 576px){ .meta-grid { grid-template-columns: 1fr; } }
  .line-items th, .line-items td { padding: .5rem .75rem; }
  .line-items tfoot td { font-weight:700; }

  /* PRINT: show only the receipt subtree, regardless of your layout wrappers */
  @media print {
    @page { margin: 12mm; size: A4; }
    body { background:#fff !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
    body * { visibility: hidden !important; }
    #receipt-root, #receipt-root * { visibility: visible !important; }
    #receipt-root { position: static !important; }
    .no-print { display:none !important; }
  }
</style>

<div id="receipt-root">
  <div class="receipt-container">
    <div class="d-flex justify-content-between align-items-center mb-3 no-print">
      <a class="btn btn-outline-secondary" href="<?= e($returnUrl) ?>">← Back</a>
      <div class="d-flex gap-2">
        <button class="btn btn-primary" onclick="window.print()">🖨️ Print / Save PDF</button>
      </div>
    </div>

    <div class="card shadow-sm">
      <div class="card-body">
        <?php if ($errors): ?>
          <div class="alert alert-danger">
            <ul class="mb-0"><?php foreach ($errors as $er) echo '<li>'.e($er).'</li>'; ?></ul>
          </div>
        <?php else: ?>
          <div class="receipt-header mb-3">
            <div class="receipt-logo">
              <img src="<?= e(app_logo_url()) ?>" alt="Company Logo" onerror="this.style.display='none'">
            </div>
            <div class="text-end">
              <div class="receipt-title">Payment Receipt</div>
              <div class="text-muted">Subject: Driver Payment</div>
            </div>
          </div>

          <div class="row g-3 mb-3">
            <div class="col-md-6">
              <div class="border rounded p-3 h-100">
                <div class="fw-semibold mb-1">Driver</div>
                <div><?= e($driver['name'] ?? '—') ?></div>
                <div class="text-muted small">
                  <?= e($driver['email'] ?? '') ?><?= !empty($driver['phone']) ? ' · '.e($driver['phone']) : '' ?>
                </div>
                <hr>
                <div class="fw-semibold mb-1">Bank Details</div>
                <div class="small">
                  <div>Bank: <?= e($driverBank['bank_name'] ?: '—') ?></div>
                  <div>Account Name: <?= e($driverBank['account_name'] ?: '—') ?></div>
                  <div>Account Number: <?= e($driverBank['account_number'] ?: '—') ?></div>
                  <div>Sort Code: <?= e($driverBank['sort_code'] ?: '—') ?></div>
                  <?php if (!empty($driverBank['iban'])): ?><div>IBAN: <?= e($driverBank['iban']) ?></div><?php endif; ?>
                  <?php if (!empty($driverBank['swift'])): ?><div>SWIFT: <?= e($driverBank['swift']) ?></div><?php endif; ?>
                  <?php if (!empty($driverBank['notes'])): ?><div class="small text-muted"><?= nl2br(e($driverBank['notes'])) ?></div><?php endif; ?>
                </div>
              </div>
            </div>

            <div class="col-md-6">
              <div class="border rounded p-3 h-100">
                <div class="fw-semibold mb-1">Payment & Job</div>
                <div class="meta-grid small">
                  <div><span class="text-muted">Reference:</span> <strong><?= e($booking['booking_ref'] ?? ('#'.($booking['id'] ?? ''))) ?></strong></div>
                  <div><span class="text-muted">Paid At:</span> <?= e((string)$payout['paid_at']) ?></div>
                  <div><span class="text-muted">Method:</span> <?= e($payout['method'] ?? '—') ?></div>
                  <div><span class="text-muted">Payout ID:</span> <?= (int)$payout['id'] ?></div>
                </div>
                <hr>
                <div class="small">
                  <?php $pdt = trim((string)($booking['pickup_date'] ?? '') . ' ' . (string)($booking['pickup_time'] ?? '')); ?>
                  <div><span class="text-muted">Pickup:</span> <?= e($pdt ?: '—') ?></div>
                  <?php if (!empty($booking['pickup_address'])): ?>
                    <div class="text-truncate"><span class="text-muted">From:</span> <?= e($booking['pickup_address']) ?></div>
                  <?php endif; ?>
                  <?php if (!empty($booking['dropoff_address'])): ?>
                    <div class="text-truncate"><span class="text-muted">To:</span> <?= e($booking['dropoff_address']) ?></div>
                  <?php endif; ?>
                  <?php if (!empty($payout['reference'])): ?>
                    <div><span class="text-muted">Internal Ref:</span> <?= e($payout['reference']) ?></div>
                  <?php endif; ?>
                  <?php if (!empty($payout['notes'])): ?>
                    <div class="mt-1"><span class="text-muted">Notes:</span> <?= nl2br(e((string)$payout['notes'])) ?></div>
                  <?php endif; ?>
                </div>
              </div>
            </div>
          </div>

          <div class="table-responsive">
            <table class="table table-sm table-bordered line-items mb-0">
              <thead class="table-light">
                <tr>
                  <th style="width:60%">Description</th>
                  <th class="text-end" style="width:20%">Amount (£)</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>Driver Total Price</td>
                  <td class="text-end"><?= number_format($totals['base'], 2) ?></td>
                </tr>
                <?php if ($totals['parking'] > 0): ?>
                  <tr>
                    <td>Car Parking (if applicable)</td>
                    <td class="text-end"><?= number_format($totals['parking'], 2) ?></td>
                  </tr>
                <?php endif; ?>
                <?php if ($totals['waiting'] > 0): ?>
                  <tr>
                    <td>Waiting (if applicable)</td>
                    <td class="text-end"><?= number_format($totals['waiting'], 2) ?></td>
                  </tr>
                <?php endif; ?>
              </tbody>
              <tfoot>
                <tr>
                  <td class="text-end">Total Due for Job</td>
                  <td class="text-end"><?= number_format($totals['due'], 2) ?></td>
                </tr>
                <tr>
                  <td class="text-end">Paid This Receipt</td>
                  <td class="text-end fw-bold"><?= number_format($totals['paid_this'], 2) ?></td>
                </tr>
                <tr>
                  <td class="text-end">Paid to Date</td>
                  <td class="text-end"><?= number_format($totals['paid_to_date'], 2) ?></td>
                </tr>
                <tr>
                  <td class="text-end">Outstanding</td>
                  <td class="text-end"><?= number_format($totals['outstanding'], 2) ?></td>
                </tr>
              </tfoot>
            </table>
          </div>

          <div class="mt-3 small text-muted">
            This is a system-generated receipt for your records.
          </div>
        <?php endif; ?>
      </div>
    </div>

    <div class="d-flex justify-content-end gap-2 mt-3 no-print">
      <a class="btn btn-outline-secondary" href="<?= e($returnUrl) ?>">← Back to Driver Payments</a>
      <button class="btn btn-primary" onclick="window.print()">🖨️ Print / Save PDF</button>
    </div>
  </div>
</div>

<?php include dirname(__DIR__, 2) . '/includes/footer.php'; ?>
