<?php
declare(strict_types=1);

/**
 * public/index.php
 * Dashboard
 * - Stats cards
 * - Quick links
 * - Active bookings (compact list, quick actions)
 * - Cleared bookings (current month by default, month-by-month nav)
 * Notes:
 * - Assignment rows highlight green when a driver/vehicle is assigned
 * - Own-vehicle support via COALESCE(bv.vehicle_reg_no, vehicles.reg_no)
 * - Profit = (client + client extras) - (driver + driver extras) - partner_commission_amount
 */

////////////////////////////////////////////////////////////////
// PART 1 — Bootstrap & Guards
////////////////////////////////////////////////////////////////
require_once dirname(__DIR__) . '/config/functions.php';
require_login();

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

$role = (string)($user['role'] ?? $user['role_name'] ?? '');
$canComplete = in_array($role, ['Admin','Ops','Accounts'], true);
$canDelete   = in_array($role, ['Admin'], true);

////////////////////////////////////////////////////////////////
// PART 2 — Small Helpers
////////////////////////////////////////////////////////////////
if (!function_exists('status_badge_dash')) {
  function status_badge_dash(string $s): string {
    $map = [
      'New'        => 'secondary',
      'Confirmed'  => 'primary',
      'Assigned'   => 'info',
      'InProgress' => 'warning',
      'Completed'  => 'secondary',
      'Invoiced'   => 'info',
      'Paid'       => 'success',
    ];
    $cls = $map[$s] ?? 'secondary';
    return '<span class="badge text-bg-'.e($cls).'">'.e($s).'</span>';
  }
}

/**
 * For a set of bookings, return:
 *  - $map[booking_id] = [assignment rows...]
 *  - $phones[booking_id] = [phone1, phone2, ...]
 * Uses COALESCE to include own-vehicle free text when vehicle_id is NULL.
 */
function fetch_assignments_map(array $bookingRows): array {
  if (!$bookingRows) return [[], []];
  $ids = array_map(fn($r) => (int)$r['id'], $bookingRows);
  $ids = array_values(array_unique(array_filter($ids)));
  if (!$ids) return [[], []];

  $in = implode(',', array_map('intval', $ids));
  $sql = "
    SELECT
      bv.booking_id,
      d.name  AS driver_name,
      d.phone AS driver_phone,
      COALESCE(bv.vehicle_reg_no, v.reg_no) AS reg_no,
      COALESCE(bv.vehicle_type,   v.type)   AS vehicle_type,
      bv.sequence_order
    FROM booking_vehicles bv
    LEFT JOIN drivers  d ON d.id=bv.driver_id
    LEFT JOIN vehicles v ON v.id=bv.vehicle_id
    WHERE bv.booking_id IN ($in)
    ORDER BY bv.sequence_order ASC, bv.id ASC
  ";
  $m = []; $phones = [];
  $q = db()->query($sql);
  while ($a = $q->fetch()) {
    $bid = (int)$a['booking_id'];
    $m[$bid][] = $a;
    if (!empty($a['driver_phone'])) $phones[$bid][] = $a['driver_phone'];
  }
  return [$m, $phones];
}

function build_assignment_label(array $as): string {
  if (!$as) return '—';
  $parts = [];
  foreach ($as as $x) {
    $label = $x['driver_name'] ?: '—';
    if (!empty($x['reg_no'])) {
      $label .= ' — '.$x['reg_no'];
      if (!empty($x['vehicle_type'])) $label .= ' ('.$x['vehicle_type'].')';
    }
    $parts[] = $label;
  }
  return implode(' | ', $parts);
}

////////////////////////////////////////////////////////////////
// PART 3 — Dashboard Config (Stats Cards Labels)
////////////////////////////////////////////////////////////////
$stats = [
  'bookings' => 'Bookings',
  'drivers'  => 'Drivers',
  'vehicles' => 'Vehicles',
  'rentals'  => 'Active Rentals',
  'invoices' => 'Invoices',
  'partners' => 'Partners',
];

////////////////////////////////////////////////////////////////
// PART 4 — Data: Active Bookings (Upcoming)
////////////////////////////////////////////////////////////////
$activeStatuses = ['New','Confirmed','Assigned','InProgress'];
$inStatuses = "'" . implode("','", array_map('addslashes', $activeStatuses)) . "'";

$activeStmt = db()->prepare("
  SELECT
    b.id, b.booking_ref, b.booking_type, b.status,
    b.client_name, b.client_phone,
    b.pickup_date, b.pickup_time, b.pickup_address, b.dropoff_address,
    b.total_client_price, b.total_driver_price,
    b.client_parking_fee, b.client_waiting_fee, b.driver_parking_fee, b.driver_waiting_fee,
    b.partner_commission_amount,
    b.pax_count, b.luggage_count,
    p.name AS partner_name
  FROM bookings b
  LEFT JOIN partners p ON p.id=b.partner_id
  WHERE b.company_id=:cid AND b.status IN ($inStatuses)
  ORDER BY b.pickup_date ASC, b.pickup_time ASC, b.id ASC
  LIMIT 15
");
$activeStmt->execute([':cid'=>$cid]);
$activeRows = $activeStmt->fetchAll();
[$activeAssign, $activePhones] = fetch_assignments_map($activeRows);

////////////////////////////////////////////////////////////////
// PART 5 — Data: Cleared Bookings (Month-by-Month)
////////////////////////////////////////////////////////////////
$monthParam = isset($_GET['month']) ? $_GET['month'] : ''; // format YYYY-MM
$today = new DateTimeImmutable('today');
if ($monthParam && preg_match('/^\d{4}-\d{2}$/', $monthParam)) {
  $monthStart = DateTimeImmutable::createFromFormat('Y-m-d', $monthParam.'-01') ?: $today->modify('first day of this month');
} else {
  $monthStart = $today->modify('first day of this month');
}
$monthEnd = $monthStart->modify('last day of this month');

$clearedStmt = db()->prepare("
  SELECT
    b.id, b.booking_ref, b.booking_type, b.status,
    b.client_name, b.client_phone,
    b.pickup_date, b.pickup_time, b.pickup_address, b.dropoff_address,
    b.total_client_price, b.total_driver_price,
    b.client_parking_fee, b.client_waiting_fee, b.driver_parking_fee, b.driver_waiting_fee,
    b.partner_commission_amount,
    b.pax_count, b.luggage_count,
    p.name AS partner_name
  FROM bookings b
  LEFT JOIN partners p ON p.id=b.partner_id
  WHERE b.company_id=:cid
    AND b.status = 'Completed'
    AND b.pickup_date BETWEEN :from AND :to
  ORDER BY b.pickup_date DESC, b.pickup_time DESC, b.id DESC
  LIMIT 20
");
$clearedStmt->execute([
  ':cid'=>$cid,
  ':from'=>$monthStart->format('Y-m-d'),
  ':to'  =>$monthEnd->format('Y-m-d'),
]);
$clearedRows = $clearedStmt->fetchAll();
[$clearedAssign, $clearedPhones] = fetch_assignments_map($clearedRows);

/* Month nav links & labels */
$prevMonth = $monthStart->modify('-1 month')->format('Y-m');
$nextMonth = $monthStart->modify('+1 month')->format('Y-m');
$prevLabelObj = DateTimeImmutable::createFromFormat('Y-m-d', $prevMonth.'-01');
$nextLabelObj = DateTimeImmutable::createFromFormat('Y-m-d', $nextMonth.'-01');

////////////////////////////////////////////////////////////////
// PART 6 — Render: Header
////////////////////////////////////////////////////////////////
include dirname(__DIR__) . '/includes/header.php';
?>
<h1 class="h4 mb-3">Dashboard</h1>
<p class="text-muted">Welcome, <?= e($user['full_name'] ?? $user['name'] ?? 'User') ?>.</p>

<?php
////////////////////////////////////////////////////////////////
// PART 7 — Render: Stats Cards
////////////////////////////////////////////////////////////////
?>
<div class="row g-3">
  <?php foreach ($stats as $table => $label): $count = table_count($table); ?>
    <div class="col-6 col-md-4 col-xl-3">
      <div class="card shadow-sm h-100">
        <div class="card-body d-flex justify-content-between align-items-center">
          <div>
            <div class="text-muted small"><?= e($label) ?></div>
            <div class="display-6 mb-0"><?= $count === null ? '—' : number_format($count) ?></div>
          </div>
          <span class="badge text-bg-dark"><?= e(strtoupper($table)) ?></span>
        </div>
      </div>
    </div>
  <?php endforeach; ?>
</div>

<?php
////////////////////////////////////////////////////////////////
// PART 8 — Render: Quick Links
////////////////////////////////////////////////////////////////
?>
<div class="card shadow-sm mt-3">
  <div class="card-body">
    <h2 class="h6 mb-2">Quick Links</h2>
    <div class="d-flex flex-wrap gap-2">
      <a href="<?= e(url_modules('bookings/add.php')) ?>" class="btn btn-dark">Create Booking</a>
      <a href="<?= e(url_modules('bookings/list.php')) ?>" class="btn btn-outline-secondary">All Bookings</a>
      <a href="<?= e(url_modules('bookings/list.php') . '?view=active') ?>" class="btn btn-outline-primary">Active Bookings</a>
      <?php $from = $monthStart->format('Y-m-d'); $to = $monthEnd->format('Y-m-d'); ?>
      <a href="<?= e(url_modules('bookings/list.php') . '?view=cleared&from='.$from.'&to='.$to) ?>" class="btn btn-outline-secondary">
        Cleared (<?= e($monthStart->format('M Y')) ?>)
      </a>
      <a href="<?= e(url_modules('bookings/calendar.php')) ?>" class="btn btn-outline-secondary">Calendar</a>
      <a href="<?= e(url_modules('payments/drivers.php')) ?>" class="btn btn-outline-secondary">Driver Payments</a>
    </div>
  </div>
</div>

<?php
////////////////////////////////////////////////////////////////
// PART 9 — Render: Active Bookings (Compact)
////////////////////////////////////////////////////////////////
?>
<div class="card shadow-sm mt-3">
  <div class="card-body">
    <div class="d-flex justify-content-between align-items-center mb-2">
      <h2 class="h6 mb-0">Active Bookings</h2>
      <a class="btn btn-sm btn-outline-primary" href="<?= e(url_modules('bookings/list.php') . '?view=active') ?>">View All</a>
    </div>

    <div class="table-responsive" style="overflow-x:auto;">
      <table class="table align-middle mb-0 bookings-table">
        <thead class="table-light">
          <tr>
            <th style="min-width:160px;">Ref</th>
            <th>Client</th>
            <th style="min-width:220px;">Pickup</th>
            <th style="min-width:220px;">Dropoff</th>
            <th>Status</th>
            <th style="min-width:260px;">Assignment</th>
            <th class="text-end">£ Client</th>
            <th class="text-end">£ Driver</th>
            <th class="text-end">£ Profit</th>
            <?php if ($canComplete || $canDelete): ?>
              <th class="text-end">Actions</th>
            <?php endif; ?>
          </tr>
        </thead>
        <tbody>
          <?php if ($activeRows): foreach ($activeRows as $r):
            $as = $activeAssign[(int)$r['id']] ?? [];
            $phones = $activePhones[(int)$r['id']] ?? [];
            $allPhones = $phones ? implode(', ', $phones) : '';

            $client  = (float)$r['total_client_price'];
            $driver  = (float)$r['total_driver_price'];
            $cExtras = (float)$r['client_parking_fee'] + (float)$r['client_waiting_fee'];
            $dExtras = (float)$r['driver_parking_fee'] + (float)$r['driver_waiting_fee'];
            $commission = (float)($r['partner_commission_amount'] ?? 0);
            $profit  = ($client + $cExtras) - ($driver + $dExtras) - $commission;
            $pBadge  = $profit > 0 ? 'success' : ($profit < 0 ? 'danger' : 'secondary');

            $pickupDT = trim(($r['pickup_date'] ?: '') . ' ' . ($r['pickup_time'] ?: ''));
            $summary = "Booking: ".$r['booking_ref']
              ."\nDate/Time: ".$pickupDT
              ."\nClient: ".($r['client_name'] ?: '—')." (".($r['client_phone'] ?: '—').")"
              ."\nRoute: ".($r['pickup_address'] ?: '—')." -> ".($r['dropoff_address'] ?: '—')
              ."\nVehicles: ".build_assignment_label($as)
              ."\nPax/Luggage: ".(int)$r['pax_count']." / ".(int)$r['luggage_count'];
          ?>
          <tr class="<?= $as ? 'table-success' : '' ?>">
            <td class="align-top">
              <div><strong><?= e($r['booking_ref']) ?></strong></div>
              <div class="d-flex flex-wrap gap-1 mt-1">
                <button type="button" class="btn btn-sm btn-outline-secondary js-copy" data-copy="<?= e($summary) ?>">Copy</button>
                <a class="btn btn-sm btn-outline-secondary" href="<?= e(url_modules('bookings/pdf.php')) . '?booking_id=' . (int)$r['id'] ?>">Journey</a>
                <a class="btn btn-sm btn-outline-primary" href="<?= e(url_modules('bookings/edit.php')) . '?id=' . (int)$r['id'] ?>">Edit</a>
              </div>
            </td>
            <td class="text-wrap">
              <?= e($r['client_name'] ?: '—') ?>
              <?php if ($r['client_phone']): ?><br><small class="text-muted"><?= e($r['client_phone']) ?></small><?php endif; ?>
            </td>
            <td class="text-wrap"><?= e($pickupDT . ($r['pickup_address'] ? ' | ' . $r['pickup_address'] : '')) ?></td>
            <td class="text-wrap"><?= e($r['dropoff_address'] ?: '—') ?></td>
            <td><?= status_badge_dash($r['status']) ?></td>
            <td class="text-wrap">
              <?php if ($as): ?>
                <ul class="list-unstyled mb-1 small">
                  <?php foreach ($as as $a): ?>
                    <li class="mb-1">
                      <strong><?= e($a['driver_name'] ?: '—') ?></strong>
                      <?php if (!empty($a['reg_no'])): ?>
                        <div class="text-muted"><?= e($a['reg_no']) ?><?= !empty($a['vehicle_type']) ? ' ('.e($a['vehicle_type']).')' : '' ?></div>
                      <?php endif; ?>
                      <?php if (!empty($a['driver_phone'])): ?>
                        <div class="d-flex gap-1">
                          <a class="btn btn-sm btn-outline-secondary btn-icon" href="tel:<?= e($a['driver_phone']) ?>">Call</a>
                          <button type="button" class="btn btn-sm btn-outline-secondary btn-icon js-copy" data-copy="<?= e($a['driver_phone']) ?>">📋</button>
                        </div>
                      <?php endif; ?>
                    </li>
                  <?php endforeach; ?>
                </ul>
                <?php if ($allPhones): ?>
                  <button type="button" class="btn btn-sm btn-outline-secondary js-copy" data-copy="<?= e($allPhones) ?>">Copy All Phones</button>
                <?php endif; ?>
              <?php else: ?>
                <span class="text-muted">—</span>
              <?php endif; ?>
            </td>
            <td class="text-end"><?= number_format($client, 2) ?></td>
            <td class="text-end"><?= number_format($driver, 2) ?></td>
            <td class="text-end"><span class="badge text-bg-<?= e($pBadge) ?>"><?= number_format($profit, 2) ?></span></td>
            <?php if ($canComplete || $canDelete): ?>
            <td class="text-end">
              <?php if ($canComplete): ?>
                <form method="post" action="<?= e(url_modules('bookings/complete.php')) ?>" class="d-inline">
                  <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                  <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                  <button class="btn btn-sm btn-outline-success">Complete</button>
                </form>
              <?php endif; ?>
              <?php if ($canDelete): ?>
                <form method="post" action="<?= e(url_modules('bookings/delete.php')) ?>" class="d-inline">
                  <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                  <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                  <button class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this booking?')">Delete</button>
                </form>
              <?php endif; ?>
            </td>
            <?php endif; ?>
          </tr>
          <?php endforeach; else: ?>
            <tr><td colspan="<?= ($canComplete || $canDelete) ? 10 : 9 ?>" class="text-center text-muted py-4">No active bookings.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php
////////////////////////////////////////////////////////////////
// PART 10 — Render: Cleared Bookings (Month Nav)
////////////////////////////////////////////////////////////////
?>
<div class="card shadow-sm mt-3">
  <div class="card-body">
    <div class="d-flex justify-content-between align-items-center mb-2">
      <h2 class="h6 mb-0">Cleared Bookings — <?= e($monthStart->format('F Y')) ?></h2>
      <div class="d-flex gap-2">
        <a class="btn btn-sm btn-outline-secondary" href="<?= e(url_public('index.php') . '?month=' . $prevMonth) ?>">
          &laquo; <?= e($prevLabelObj ? $prevLabelObj->format('M Y') : 'Prev') ?>
        </a>
        <a class="btn btn-sm btn-outline-secondary" href="<?= e(url_public('index.php') . '?month=' . $nextMonth) ?>">
          <?= e($nextLabelObj ? $nextLabelObj->format('M Y') : 'Next') ?> &raquo;
        </a>
        <?php $from = $monthStart->format('Y-m-d'); $to = $monthEnd->format('Y-m-d'); ?>
        <a class="btn btn-sm btn-outline-primary" href="<?= e(url_modules('bookings/list.php') . '?view=cleared&from='.$from.'&to='.$to) ?>">Open with Filters</a>
      </div>
    </div>

    <div class="table-responsive" style="overflow-x:auto;">
      <table class="table align-middle mb-0 bookings-table">
        <thead class="table-light">
          <tr>
            <th style="min-width:160px;">Ref</th>
            <th>Client</th>
            <th style="min-width:220px;">Pickup</th>
            <th style="min-width:220px;">Dropoff</th>
            <th>Status</th>
            <th style="min-width:260px;">Assignment</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($clearedRows): foreach ($clearedRows as $r):
            $as = $clearedAssign[(int)$r['id']] ?? [];
            $phones = $clearedPhones[(int)$r['id']] ?? [];
            $allPhones = $phones ? implode(', ', $phones) : '';
            $pickupDT = trim(($r['pickup_date'] ?: '') . ' ' . ($r['pickup_time'] ?: ''));
            $summary = "Booking: ".$r['booking_ref']
              ."\nDate/Time: ".$pickupDT
              ."\nClient: ".($r['client_name'] ?: '—')." (".($r['client_phone'] ?: '—').")"
              ."\nRoute: ".($r['pickup_address'] ?: '—')." -> ".($r['dropoff_address'] ?: '—')
              ."\nVehicles: ".build_assignment_label($as)
              ."\nPax/Luggage: ".(int)$r['pax_count']." / ".(int)$r['luggage_count'];
          ?>
          <tr>
            <td class="align-top">
              <div><strong><?= e($r['booking_ref']) ?></strong></div>
              <div class="d-flex flex-wrap gap-1 mt-1">
                <button type="button" class="btn btn-sm btn-outline-secondary js-copy" data-copy="<?= e($summary) ?>">Copy</button>
                <a class="btn btn-sm btn-outline-secondary" href="<?= e(url_modules('bookings/pdf.php')) . '?booking_id=' . (int)$r['id'] ?>">Journey</a>
                <a class="btn btn-sm btn-outline-primary" href="<?= e(url_modules('bookings/edit.php')) . '?id=' . (int)$r['id'] ?>">Edit</a>
              </div>
            </td>
            <td class="text-wrap">
              <?= e($r['client_name'] ?: '—') ?>
              <?php if ($r['client_phone']): ?><br><small class="text-muted"><?= e($r['client_phone']) ?></small><?php endif; ?>
            </td>
            <td class="text-wrap"><?= e($pickupDT . ($r['pickup_address'] ? ' | ' . $r['pickup_address'] : '')) ?></td>
            <td class="text-wrap"><?= e($r['dropoff_address'] ?: '—') ?></td>
            <td><?= status_badge_dash($r['status']) ?></td>
            <td class="text-wrap">
              <?php if ($as): ?>
                <ul class="list-unstyled mb-1 small">
                  <?php foreach ($as as $a): ?>
                    <li class="mb-1">
                      <strong><?= e($a['driver_name'] ?: '—') ?></strong>
                      <?php if (!empty($a['reg_no'])): ?>
                        <div class="text-muted"><?= e($a['reg_no']) ?><?= !empty($a['vehicle_type']) ? ' ('.e($a['vehicle_type']).')' : '' ?></div>
                      <?php endif; ?>
                      <?php if (!empty($a['driver_phone'])): ?>
                        <div class="d-flex gap-1">
                          <a class="btn btn-sm btn-outline-secondary btn-icon" href="tel:<?= e($a['driver_phone']) ?>">Call</a>
                          <button type="button" class="btn btn-sm btn-outline-secondary btn-icon js-copy" data-copy="<?= e($a['driver_phone']) ?>">📋</button>
                        </div>
                      <?php endif; ?>
                    </li>
                  <?php endforeach; ?>
                </ul>
                <?php if ($allPhones): ?>
                  <button type="button" class="btn btn-sm btn-outline-secondary js-copy" data-copy="<?= e($allPhones) ?>">Copy All Phones</button>
                <?php endif; ?>
              <?php else: ?>
                <span class="text-muted">—</span>
              <?php endif; ?>
            </td>
          </tr>
          <?php endforeach; else: ?>
            <tr><td colspan="6" class="text-center text-muted py-4">No cleared bookings in <?= e($monthStart->format('F Y')) ?>.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php
////////////////////////////////////////////////////////////////
// PART 11 — Footer
////////////////////////////////////////////////////////////////
include dirname(__DIR__) . '/includes/footer.php';
?>

<?php
////////////////////////////////////////////////////////////////
// PART 12 — Page Scripts (Copy-to-Clipboard)
////////////////////////////////////////////////////////////////
?>
<script>
document.addEventListener('click', function(e){
  const btn = e.target.closest('.js-copy');
  if (!btn) return;
  const text = btn.getAttribute('data-copy') || '';
  navigator.clipboard.writeText(text).then(()=>{ toast('Copied'); });
});
function toast(text){
  const t = document.createElement('div');
  t.textContent = text;
  t.style.position='fixed';
  t.style.right='1rem';
  t.style.bottom='1rem';
  t.style.background='#212529';
  t.style.color='#fff';
  t.style.padding='.5rem .75rem';
  t.style.borderRadius='8px';
  t.style.zIndex='1055';
  document.body.appendChild(t);
  setTimeout(()=>t.remove(),1200);
}
</script>
