<?php
declare(strict_types=1);
require_once dirname(__DIR__,2).'/config/functions.php';
require_role(['Admin','Ops']);

header('Content-Type: application/json');
$cid = current_user()['company_id'] ?? null; if(!$cid){ echo '[]'; exit; }

$stmt = db()->prepare("
  SELECT id, booking_ref, client_name, pickup_date, pickup_time, status
  FROM bookings
  WHERE company_id=:cid AND pickup_date IS NOT NULL
");
$stmt->execute([':cid'=>$cid]);
$rows = $stmt->fetchAll();

$events = [];
foreach($rows as $r){
  $start = $r['pickup_date'].'T'.($r['pickup_time'] ?: '00:00:00');
  $events[] = [
    'id' => (int)$r['id'],
    'title' => ($r['booking_ref'] ?: 'BKG').' — '.($r['client_name'] ?: 'Client'),
    'start' => $start,
    'color' => match($r['status']){
      'Confirmed'=>'#0d6efd','Assigned'=>'#198754','InProgress'=>'#fd7e14','Completed'=>'#6c757d','Invoiced'=>'#20c997','Paid'=>'#198754', default=>'#6f42c1'
    },
    'extendedProps' => ['editUrl' => url_modules('bookings/edit.php').'?id='.$r['id']]
  ];
}
echo json_encode($events);
