<?php
declare(strict_types=1);
/**
 * modules/payments/partners_report_print.php
 *
 * Browser-printable Partner Commission Monthly Report
 * - Minimal layout (no sidebar/header from app)
 * - A4 portrait with professional branding
 * - Fields:
 *     1) Job number (booking_ref)
 *     2) Client name
 *     3) Pickup Date (date + time)
 *     4) Pickup From (pickup_address)
 *     5) Drop off (dropoff_address)
 *     6) Client Price (EXCLUDES client parking/waiting)
 *     7) Commission (calculated as on partners.php)
 */

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'));

/* -------------------------------------------------------
   Company branding (adjust to your assets)
------------------------------------------------------- */
$companyName    = "Brownhill Group Limited";
$companyAddress = "Suite 109, 4-6 Wadsworth Road, Perivale, UB6 7JJ";
$companyWebsite = "www.brown-hillchauffeurs.co.uk";
$logoPath       = url_public('assets/logo.png'); // change if needed

/* -------------------------------------------------------
   Inputs
------------------------------------------------------- */
$today      = new DateTimeImmutable('today');
$monthStart = $today->modify('first day of this month');
$monthEnd   = $today->modify('last day of this month');

$from    = (string)($_GET['from']    ?? $monthStart->format('Y-m-01'));
$to      = (string)($_GET['to']      ?? $monthEnd->format('Y-m-d'));
$partner = (int)   ($_GET['partner'] ?? 0);
$status  = (string)($_GET['status']  ?? 'all'); // for completeness; report doesn’t need paid/unpaid filter by default
$q       = trim((string)($_GET['q']  ?? ''));

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $from)) $from = $monthStart->format('Y-m-d');
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $to))   $to   = $monthEnd->format('Y-m-d');
if (!in_array($status, ['unpaid','paid','all'], true)) $status = 'all';

/* -------------------------------------------------------
   Helpers
------------------------------------------------------- */
function tbl_exists_print(string $t): bool {
  try { db()->query("SELECT 1 FROM `{$t}` LIMIT 1"); return true; } catch (Throwable) { return false; }
}
function n2p($v): string { return '£'.number_format((float)$v, 2); }
if (!function_exists('e')) {
  function e($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
}

/* -------------------------------------------------------
   Query rows (mirror partners.php logic for commission)
------------------------------------------------------- */
$rows = [];
$totClient = 0.0;  // ONLY base client price (no extras)
$totComm   = 0.0;

try {
  $hasPayouts = tbl_exists_print('partner_payouts');

  $where = [
    "b.company_id = :cid",
    "b.pickup_date BETWEEN :from AND :to",
    "b.status = 'Completed'",
    "b.partner_id IS NOT NULL"
  ];
  $args = [':cid'=>$cid, ':from'=>$from, ':to'=>$to];

  if ($partner > 0) {
    $where[] = "b.partner_id = :pid";
    $args[':pid'] = $partner;
  }
  if ($q !== '') {
    // Separate placeholders to avoid HY093
    $like = '%'.$q.'%';
    $where[] = "(b.booking_ref LIKE :q1 OR b.client_name LIKE :q2 OR p.name LIKE :q3)";
    $args[':q1'] = $like;
    $args[':q2'] = $like;
    $args[':q3'] = $like;
  }

  // Inner: compute commission_due (EXACTLY like partners.php)
  $inner = "
    SELECT
      b.id,
      b.booking_ref,
      b.client_name,
      b.pickup_date,
      b.pickup_time,
      b.pickup_address,
      b.dropoff_address,
      p.id   AS partner_id,
      p.name AS partner_name,
      p.commission_type,
      p.commission_value,

      -- Client base price (no extras)
      COALESCE(b.total_client_price,0) AS client_price_base,

      -- Commission calculation
      GREATEST(0.00,
        ROUND(
          CASE
            WHEN p.commission_type = 'percent'
              THEN (COALESCE(p.commission_value,0) / 100.0) * COALESCE(b.total_client_price,0)
            ELSE
              COALESCE(b.partner_commission_amount,0)
          END, 2
        )
      ) AS commission_due

    FROM bookings b
    INNER JOIN partners p ON p.id = b.partner_id
    WHERE ".implode(' AND ', $where)."
    ORDER BY b.pickup_date DESC, b.pickup_time DESC, b.id DESC
    LIMIT 1000
  ";

  $stmt = db()->prepare($inner);
  $stmt->execute($args);
  $rows = $stmt->fetchAll();

  foreach ($rows as $r) {
    $totClient += (float)$r['client_price_base'];
    $totComm   += (float)$r['commission_due'];
  }

  // Find partner label for header (if filtered)
  $partnerName = 'All Partners';
  if ($partner > 0) {
    $ps = db()->prepare("SELECT name FROM partners WHERE id=:id AND company_id=:cid LIMIT 1");
    $ps->execute([':id'=>$partner, ':cid'=>$cid]);
    $pn = $ps->fetchColumn();
    if ($pn) $partnerName = (string)$pn;
  }
} catch (Throwable $e) {
  http_response_code(500);
  exit('Unable to render report.');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Partner Commission Report — <?= e($from) ?> to <?= e($to) ?></title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
  :root{
    --ink:#111;
    --muted:#666;
    --brand:#111; /* dark brand accent */
    --grid:#dcdcdc;
    --grid2:#f6f6f6;
  }
  *{ box-sizing:border-box; }
  html,body{ margin:0; padding:0; color:var(--ink); background:#fff; font:12px/1.45 "Segoe UI", Roboto, Arial, sans-serif; }
  .wrap{ padding:18mm 14mm; }
  .header{
    display:flex; align-items:center; justify-content:space-between; border-bottom:2px solid var(--brand); padding-bottom:10px; margin-bottom:16px;
  }
  .logo{ height:60px; }
  .co{text-align:right;}
  .co .name{ font-weight:700; font-size:14px; }
  .co .addr, .co .web{ color:var(--muted); font-size:11px; }
  h1{
    text-transform:uppercase; font-size:16px; letter-spacing:0.5px; margin:0 0 4px;
    text-align:center;
  }
  .sub{ text-align:center; color:var(--muted); font-size:12px; margin-bottom:14px; }
  table{ width:100%; border-collapse:collapse; }
  th,td{ border:1px solid var(--grid); padding:6px 8px; vertical-align:top; }
  th{ background:#fafafa; font-weight:600; text-align:left; }
  tbody tr:nth-child(even) td{ background:var(--grid2); }
  .text-end{ text-align:right; }
  .w-job{ width:16%; }
  .w-client{ width:15%; }
  .w-date{ width:15%; }
  .w-from{ width:22%; }
  .w-to{ width:22%; }
  .w-money{ width:10%; }

  tfoot td{ font-weight:700; background:#f2f2f2; }
  .footnote{ margin-top:10px; color:var(--muted); font-size:11px; display:flex; justify-content:space-between; }
  .brandbar{ height:3px; background:var(--brand); margin-top:2px; }

  @media print {
    @page { size: A4 portrait; margin: 12mm; }
    .wrap{ padding:0; }
    .no-print{ display:none !important; }
    a:link, a:visited{ color:inherit; text-decoration:none; }
  }

  /* Tidy long addresses */
  .addr{ white-space:pre-line; }
</style>
</head>
<body onload="window.print()">
  <div class="wrap">
    <div class="header">
      <img class="logo" src="<?= e($logoPath) ?>" alt="Logo">
      <div class="co">
        <div class="name"><?= e($companyName) ?></div>
        <div class="addr"><?= e($companyAddress) ?></div>
        <div class="web"><?= e($companyWebsite) ?></div>
      </div>
    </div>

    <h1>Partner Commission Report</h1>
    <div class="sub">
      Partner: <?= e(isset($partnerName)?$partnerName:'All Partners') ?> &nbsp; | &nbsp;
      Period: <?= e($from) ?> → <?= e($to) ?>
    </div>

    <table>
      <thead>
        <tr>
          <th class="w-job">Job No</th>
          <th class="w-client">Client Name</th>
          <th class="w-date">Pickup Date</th>
          <th class="w-from">Pickup From</th>
          <th class="w-to">Drop Off</th>
          <th class="w-money text-end">Client Price</th>
          <th class="w-money text-end">Commission</th>
        </tr>
      </thead>
      <tbody>
        <?php if ($rows): foreach ($rows as $r): ?>
          <tr>
            <td><?= e($r['booking_ref']) ?></td>
            <td><?= e($r['client_name'] ?? '—') ?></td>
            <td>
              <?php
                $dt = trim((string)($r['pickup_date'] ?? '') . ' ' . (string)($r['pickup_time'] ?? ''));
                echo e($dt !== '' ? $dt : '—');
              ?>
            </td>
            <td class="addr"><?= nl2br(e((string)($r['pickup_address']  ?? '—'))) ?></td>
            <td class="addr"><?= nl2br(e((string)($r['dropoff_address'] ?? '—'))) ?></td>
            <td class="text-end"><?= e(n2p($r['client_price_base'] ?? 0)) ?></td>
            <td class="text-end"><?= e(n2p($r['commission_due']    ?? 0)) ?></td>
          </tr>
        <?php endforeach; else: ?>
          <tr><td colspan="7" class="text-center" style="color:#999;">No results for the selected period.</td></tr>
        <?php endif; ?>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="5" class="text-end">Totals</td>
          <td class="text-end"><?= e(n2p($totClient)) ?></td>
          <td class="text-end"><?= e(n2p($totComm)) ?></td>
        </tr>
      </tfoot>
    </table>

    <div class="footnote">
      <div>Report generated on <?= e(date('Y-m-d H:i')) ?> by <?= e($user['name'] ?? 'System') ?>.</div>
      <div>&copy; <?= date('Y') ?> <?= e($companyName) ?></div>
    </div>
    <div class="brandbar"></div>

    <div class="no-print" style="margin-top:14px;text-align:center;">
      <a class="btn" href="<?= e(url_modules('payments/partners.php') . '?' . http_build_query(['from'=>$from,'to'=>$to,'partner'=>$partner,'status'=>$status,'q'=>$q])) ?>" style="display:inline-block;padding:7px 12px;border:1px solid #ccc;border-radius:6px;text-decoration:none;color:#000;">
        ← Back to Partner Payments
      </a>
    </div>
  </div>
</body>
</html>
