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

$user=current_user(); $cid=isset($user['company_id'])?(int)$user['company_id']:0; if(!$cid) redirect(url_public('index.php'));

$rows = db()->prepare("
  SELECT id, booking_ref, client_name, pickup_date, pickup_time, pickup_address, dropoff_address
  FROM bookings WHERE company_id=:cid
");
$rows->execute(array(':cid'=>$cid)); $events=array();
while($r=$rows->fetch()){
  $start = $r['pickup_date'].'T'.($r['pickup_time']?:'00:00:00');
  $title = ($r['client_name']?:'—').' • '.($r['pickup_address']?:'');
  $events[] = array(
    'id' => (int)$r['id'],
    'title' => $title,
    'start' => $start,
    'url' => url_modules('bookings/edit.php').'?id='.(int)$r['id'],
  );
}

include dirname(__DIR__,2).'/includes/header.php';
?>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.11/index.global.min.css">
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.11/index.global.min.js"></script>

<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Calendar</h1>
  <a href="list.php" class="btn btn-outline-secondary">Back to Bookings</a>
</div>

<div class="card shadow-sm">
  <div class="card-body">
    <div id="calendar"></div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function(){
  var calendarEl=document.getElementById('calendar');
  var calendar=new FullCalendar.Calendar(calendarEl,{
    initialView:'dayGridMonth',
    height:'auto',             // no internal scrollbars
    dayMaxEventRows:3,         // "+more" link when busy
    headerToolbar:{ left:'prev,next today', center:'title', right:'dayGridMonth,dayGridWeek,dayGridDay' },
    events: <?= json_encode($events) ?>
  });
  calendar.render();
});
</script>
<?php include dirname(__DIR__,2).'/includes/footer.php'; ?>
