<?php
declare(strict_types=1);
/**
 * modules/rentals/calendar.php
 *
 * Rental Availability Calendar (FullCalendar)
 * - Inline JSON feed via ?feed=1
 * - Filters: vehicle, status
 * - Color coding: Active=green, Overdue=red, Completed=grey, Cancelled=dark
 * - Click event → open rental view
 */

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

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

/* ---------------- Feed endpoint ---------------- */
if (isset($_GET['feed']) && $_GET['feed'] === '1') {
  header('Content-Type: application/json; charset=utf-8');

  $vehicleId = isset($_GET['vehicle_id']) && $_GET['vehicle_id'] !== '' ? (int)$_GET['vehicle_id'] : null;
  $status    = isset($_GET['status']) && $_GET['status'] !== '' ? (string)$_GET['status'] : null;

  $where = ["r.company_id = :cid"];
  $args  = [':cid' => $cid];

  if ($vehicleId) { $where[] = "r.vehicle_id = :vid"; $args[':vid'] = $vehicleId; }
  if ($status)    { $where[] = "r.status = :st";      $args[':st']  = $status; }

  $sql = "
    SELECT r.*,
           v.reg_no, v.type, v.make, v.model
      FROM rentals r
      LEFT JOIN vehicles v ON v.id = r.vehicle_id
     WHERE ".implode(' AND ', $where)."
     ORDER BY r.start_date ASC, r.id ASC
     LIMIT 2000
  ";
  $q = db()->prepare($sql);
  $q->execute($args);

  $events = [];
  while ($r = $q->fetch()) {
    $id   = (int)$r['id'];
    $reg  = trim(($r['reg_no'] ?? ''));
    $type = trim(($r['type']   ?? ''));
    $title = ($reg !== '' ? $reg : 'Vehicle #'.$r['vehicle_id']) .
             ($type !== '' ? ' ('.$type.')' : '') .
             ' — ' . ($r['renter_name'] ?? 'Renter');

    // all-day spanning event; end must be exclusive
    $start = (string)$r['start_date'];
    $end   = (string)($r['end_date'] ?? '');
    if ($end === '' || $end === '0000-00-00') {
      // Visualize ongoing rentals as next 30 days from today or 30 days from start (whichever later)
      $startBase = $start !== '' ? new DateTimeImmutable($start) : new DateTimeImmutable('today');
      $endExcl = (new DateTimeImmutable('today'))->modify('+30 days');
      if ($endExcl < $startBase) $endExcl = $startBase->modify('+30 days');
    } else {
      $endExcl = (new DateTimeImmutable($end))->modify('+1 day');
    }

    $statusVal = (string)($r['status'] ?? 'Active');
    // Colors
    $colors = [
      'Active'    => ['bg' => '#22c55e', 'bd' => '#16a34a', 'tx' => '#052e16'],
      'Overdue'   => ['bg' => '#ef4444', 'bd' => '#dc2626', 'tx' => '#450a0a'],
      'Completed' => ['bg' => '#9ca3af', 'bd' => '#6b7280', 'tx' => '#111827'],
      'Cancelled' => ['bg' => '#111827', 'bd' => '#0f172a', 'tx' => '#f8fafc'],
    ];
    $col = $colors[$statusVal] ?? $colors['Active'];

    $events[] = [
      'id'    => $id,
      'title' => $title,
      'start' => $start ?: (new DateTimeImmutable('today'))->format('Y-m-d'),
      'end'   => $endExcl->format('Y-m-d'),
      'allDay' => true,
      'backgroundColor' => $col['bg'],
      'borderColor'     => $col['bd'],
      'textColor'       => $col['tx'],
      'url'             => url_modules('rentals/view.php') . '?id=' . $id,
      'extendedProps'   => [
        'status'            => $statusVal,
        'weekly_rate'       => (float)($r['weekly_rate'] ?? 0),
        'deposit_amount'    => (float)($r['deposit_amount'] ?? 0),
        'deposit_status'    => (string)($r['deposit_status'] ?? 'Held'),
        'payment_frequency' => (string)($r['payment_frequency'] ?? 'Weekly'),
        'phone'             => (string)($r['phone'] ?? ''),
        'notes'             => (string)($r['payment_notes'] ?? ''),
        'vehicle'           => trim(($r['make'] ?? '').' '.($r['model'] ?? '')),
      ],
    ];
  }

  echo json_encode($events, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  exit;
}

/* ---------------- Page (HTML) ---------------- */
$vehStmt = db()->prepare("SELECT id, reg_no, type FROM vehicles WHERE company_id=:cid ORDER BY reg_no");
$vehStmt->execute([':cid' => $cid]);
$vehicles = $vehStmt->fetchAll();

$initVehicle = isset($_GET['vehicle_id']) ? (int)$_GET['vehicle_id'] : 0;
$initStatus  = isset($_GET['status']) ? (string)$_GET['status'] : '';

include dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Rental Availability Calendar</h1>
  <div class="d-flex gap-2">
    <a href="<?= e(url_modules('rentals/list.php')) ?>" class="btn btn-outline-secondary">Back to Rentals</a>
    <a href="<?= e(url_modules('rentals/add.php')) ?>" class="btn btn-dark">Add Rental</a>
  </div>
</div>

<div class="card shadow-sm mb-3">
  <div class="card-body">
    <form class="row g-2 align-items-end" id="filters" onsubmit="return false;">
      <div class="col-md-4">
        <label class="form-label">Vehicle</label>
        <select class="form-select" id="fVehicle">
          <option value="">— All vehicles —</option>
          <?php foreach ($vehicles as $v): ?>
            <option value="<?= (int)$v['id'] ?>" <?= $initVehicle===(int)$v['id']?'selected':'' ?>>
              <?= e(($v['reg_no'] ?? '—').' ('.($v['type'] ?? '—').')') ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">Status</label>
        <select class="form-select" id="fStatus">
          <option value="">— All —</option>
          <?php foreach (['Active','Completed','Overdue','Cancelled'] as $st): ?>
            <option value="<?= e($st) ?>" <?= $initStatus===$st?'selected':'' ?>><?= e($st) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-2 d-grid">
        <button type="button" id="btnApply" class="btn btn-primary">Apply</button>
      </div>
      <div class="col-md-3 d-flex gap-2 justify-content-end">
        <div class="btn-group" role="group" aria-label="view switch">
          <button type="button" class="btn btn-outline-secondary" data-view="dayGridMonth">Month</button>
          <button type="button" class="btn btn-outline-secondary" data-view="timeGridWeek">Week</button>
          <button type="button" class="btn btn-outline-secondary" data-view="listMonth">List</button>
        </div>
      </div>
    </form>
  </div>
</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.15/index.global.min.css">
<style>
  /* Slightly rounded event pills for readability */
  .fc .fc-h-event { border-radius: 8px; }
  .fc .fc-toolbar-title { font-size: 1.1rem; }
</style>

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

<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.15/index.global.min.js"></script>
<script>
(function(){
  const calendarEl = document.getElementById('calendar');
  const fVehicle = document.getElementById('fVehicle');
  const fStatus  = document.getElementById('fStatus');
  const btnApply = document.getElementById('btnApply');

  function feedUrl() {
    const params = new URLSearchParams();
    params.set('feed', '1');
    if (fVehicle.value) params.set('vehicle_id', fVehicle.value);
    if (fStatus.value)  params.set('status', fStatus.value);
    return 'calendar.php?' + params.toString();
  }

  const calendar = new FullCalendar.Calendar(calendarEl, {
    initialView: 'dayGridMonth',
    height: 'auto',
    firstDay: 1,
    headerToolbar: {
      left: 'prev,next today',
      center: 'title',
      right: ''
    },
    weekends: true,
    navLinks: true,
    eventSources: [{
      url: feedUrl(),
      failure: () => { console.error('Failed to load rental events'); }
    }],
    eventClick: (info) => {
      // open view in same tab
      if (info.event.url) {
        window.location.href = info.event.url;
        info.jsEvent.preventDefault();
      }
    },
    eventDidMount: (info) => {
      const p = info.event.extendedProps || {};
      const lines = [
        info.event.title,
        'Status: ' + (p.status || ''),
        'Weekly: £ ' + (Number(p.weekly_rate||0).toFixed(2)),
        'Deposit: £ ' + (Number(p.deposit_amount||0).toFixed(2)) + ' ('+(p.deposit_status||'')+')',
        (p.phone ? 'Phone: ' + p.phone : ''),
        (p.vehicle ? 'Vehicle: ' + p.vehicle : ''),
        (p.notes ? 'Notes: ' + p.notes : '')
      ].filter(Boolean);
      info.el.title = lines.join('\n');
    }
  });

  calendar.render();

  btnApply.addEventListener('click', () => {
    calendar.getEventSources().forEach(s => s.remove());
    calendar.addEventSource({ url: feedUrl() });
  });

  // View switchers
  document.querySelectorAll('[data-view]').forEach(btn=>{
    btn.addEventListener('click', () => {
      calendar.changeView(btn.getAttribute('data-view'));
    });
  });
})();
</script>

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