<?php
error_reporting(-1);
ini_set('display_errors', 1);

include_once('header.php');
if (!check_login()) {
  header("Location: " . WEB_URL . "logout.php");
  die();
}
include_once(ROOT_PATH.'language/'.$lang_code_global.'/lang_admin_dashboard.php');

/* --------------------------------
   Counters & defaults
---------------------------------*/
$total_floor = 0;
$total_units = 0;
$total_owner = 0;
$total_rent = 0;
$total_service = 0;
$total_taxes = 0;
$total_payables = 0;
$total_maintenance = 0;
$total_tenants = 0;
$total_mc = 0;
$total_tmc = 0;
$total_c = 0;
$total_occupied_units = 0;
$total_owner_utility = 0;
$total_fund = 0;
$total_salary = 0;
$total_branch = 0;
$monthly_bill_data = '0,0,0,0,0,0,0,0,0,0,0,0';
$monthly_rent_data = '0,0,0,0,0,0,0,0,0,0,0,0';

/* --------------------------------
   Helpers
---------------------------------*/
function is_valid_ymd($d) { return preg_match('/^\d{4}-\d{2}-\d{2}$/', $d); }
function plus_one_day($ymd) { return date('Y-m-d', strtotime($ymd . ' +1 day')); }
function each_day_between($start,$end){ $out=[]; $s=strtotime($start); $e=strtotime($end); for($t=$s;$t<=$e;$t+=86400){ $out[] = date('Y-m-d',$t); } return $out; }
function ordinal($n){ if (in_array($n % 100, [11,12,13])) return $n.'th'; $m=$n%10; return $n.($m===1?'st':($m===2?'nd':($m===3?'rd':'th'))); }
function format_words_range($s,$e){
  $sd = strtotime($s); $ed = strtotime($e);
  return ordinal((int)date('j',$sd)).' '.date('F, Y',$sd).' to '.ordinal((int)date('j',$ed)).' '.date('F, Y',$ed);
}
function ordinal_suffix($n){
  if (in_array($n % 100, [11,12,13])) return $n.'th';
  switch ($n % 10) { case 1: return $n.'st'; case 2: return $n.'nd'; case 3: return $n.'rd'; default: return $n.'th'; }
}
function human_date($ymd){
  $ts = strtotime($ymd); if (!$ts) return $ymd;
  return ordinal_suffix((int)date('j',$ts)).' '.date('F, Y',$ts);
}
function human_range($start,$end){ return human_date($start) . ' - ' . human_date($end); }
function format_words_date($d){
  $ts = strtotime($d); if (!$ts) return $d;
  $day = (int)date('j',$ts);
  return ordinal($day) . ' ' . date('F, Y',$ts);
}
function max_date($a,$b){ return (strcmp($a,$b) >= 0) ? $a : $b; }
function min_date($a,$b){ return (strcmp($a,$b) <= 0) ? $a : $b; }
function short_exit_date($d){ $ts=strtotime($d); return $ts?date('j-M-y',$ts):$d; }

/* --------------------------------
   Inputs for calendar / grid
---------------------------------*/
$default_start = date('Y-m-01');
$default_end   = date('Y-m-t');
$range_start   = isset($_GET['range_start']) && is_valid_ymd($_GET['range_start']) ? $_GET['range_start'] : $default_start;
$range_end     = isset($_GET['range_end'])   && is_valid_ymd($_GET['range_end'])   ? $_GET['range_end']   : $default_end;
$filter_used   = (isset($_GET['range_start']) || isset($_GET['range_end']));
$selected_mode = $filter_used || (isset($_GET['sel']) && $_GET['sel'] === '1');

/* --------------------------------
   Unit count
---------------------------------*/
$result_unit = $link->query("SELECT count(uid) as total_unit FROM unit_view");
if ($row_unit_total = mysqli_fetch_array($result_unit)) $total_units = $row_unit_total['total_unit'];

/* --------------------------------
   Total Rent (Current Year & All)
---------------------------------*/
$current_year = (int)date('Y');

$total_rent  = 0.0; // current year
$total_rentt = 0.0; // all-time

$start_of_year = sprintf('%04d-01-01', $current_year);
$end_of_year   = sprintf('%04d-12-31', $current_year);

if ($stmt = $link->prepare("
    SELECT COALESCE(SUM(total_rent),0) AS total_year
    FROM rent_tenant_cedi_units_view
    WHERE issue_date IS NOT NULL
      AND issue_date >= ? AND issue_date <= ?
")) {
    $stmt->bind_param('ss', $start_of_year, $end_of_year);
    $stmt->execute();
    $stmt->bind_result($total_year_val);
    if ($stmt->fetch()) $total_rent = (float)$total_year_val;
    $stmt->close();
}

$result_all = $link->query("SELECT COALESCE(SUM(total_rent),0) AS total_all FROM rent_tenant_cedi_units_view");
if ($result_all && ($row_all = $result_all->fetch_assoc())) $total_rentt = (float)$row_all['total_all'];

$current_year = date("Y");
$result_service = $link->query("SELECT SUM(amount) as total_service FROM foreign_currency_service_main_account WHERE fiscal_year = $current_year AND rent_id IS NOT NULL AND trans_type = 'debit'");
if ($row_rent_service = mysqli_fetch_array($result_service)) $total_service = $row_rent_service['total_service'];
$result_rent = $link->query("SELECT SUM(amount) as total_rent FROM foreign_currency_service_main_account WHERE rent_id IS NOT NULL AND trans_type = 'debit'");
if ($row_rent_service = mysqli_fetch_array($result_service)) $total_servicee = $row_rent_service['total_service'];

/* --------------------------------
   Taxes (Current Year)
---------------------------------*/
$result_tax = $link->query("SELECT SUM(amount) as total_tax FROM main_account WHERE fiscal_year = $current_year AND rent_id IS NOT NULL AND trans_type = 'credit'");
if ($row_tax_total = mysqli_fetch_array($result_tax)) $total_taxes = $row_tax_total['total_tax'];

/* --------------------------------
   Receivables (Current Year)
---------------------------------*/
$result_balance = $link->query("
  SELECT SUM(total_rent - amt_paid) AS total_balance 
  FROM rent_tenant_cedi_units_view
  WHERE YEAR(issue_date) = '$current_year'
");
if ($row_balance_total = mysqli_fetch_array($result_balance)) $total_payables = $row_balance_total['total_balance'];

/* --------------------------------
   Maintenance (Current Year & All)
---------------------------------*/
$result_maintenance = $link->query("SELECT SUM(m_amount) as total_maintenance FROM maintenance WHERE xyear = $current_year");
if ($row_maintenance = mysqli_fetch_array($result_maintenance)) $total_maintenance = $row_maintenance['total_maintenance'] ?: 0;
$result_mc = $link->query("SELECT sum(m_amount) as total FROM maintenance where xyear = $current_year");
if ($row_mc_total = mysqli_fetch_array($result_mc)) if ($row_mc_total['total'] > 0) $total_mc = $row_mc_total['total'];
$result_tmc = $link->query("SELECT sum(m_amount) as total FROM maintenance");
if ($row_mc_total = mysqli_fetch_array($result_tmc)) if ($row_mc_total['total'] > 0) $total_tmc = $row_mc_total['total'];

/* --------------------------------
   Tenants & occupied units
---------------------------------*/
$result_tenants = $link->query("SELECT count(tid) as total_tenants FROM tenants");
if ($row_tenants = mysqli_fetch_array($result_tenants)) $total_tenants = $row_tenants['total_tenants'];

/* >>> FIX: MariaDB-safe JSON_CONTAINS (no CAST ... AS JSON) */
$result_occupied = $link->query("
  SELECT COUNT(DISTINCT u.uid) AS occupied_count
  FROM rent r
  JOIN unit_view u ON JSON_CONTAINS(r.uid, CAST(u.uid AS CHAR), '$')
  WHERE CURDATE() BETWEEN r.start_date AND r.end_date
");
if ($row_occupied = mysqli_fetch_array($result_occupied)) $total_occupied_units = $row_occupied['occupied_count'];

/* --------------------------------
   Bills graph data (year)
---------------------------------*/
$_graph_deposit = array();
$result_deposit = $link->query("
  SELECT sum(total_amount) as total, m.month_name, y.xyear, b.bill_month
  FROM bills b
  INNER JOIN bill_types bt ON bt.bt_id = b.bill_type
  INNER JOIN tbl_add_month_setup m ON m.m_id = b.bill_month
  INNER JOIN tbl_add_year_setup y ON y.y_id = b.bill_year
  WHERE y.xyear = ".date('Y')."
  GROUP BY b.bill_month
  ORDER BY b.bill_month ASC
");
while ($row_deposit_total = mysqli_fetch_assoc($result_deposit)) {
  $_graph_deposit[$row_deposit_total['bill_month']] = $row_deposit_total;
}
$grapth_data = '';
for ($i=1; $i<=12; $i++) { $grapth_data .= isset($_graph_deposit[$i]) ? ($_graph_deposit[$i]['total'].',') : '0,'; }
$monthly_bill_data = trim($grapth_data, ',');

/* --------------------------------
   Calendar dataset (range)
---------------------------------*/
$range_start_sql = mysqli_real_escape_string($link, $range_start);
$range_end_sql   = mysqli_real_escape_string($link, $range_end);

/* All units */
$units = [];
$uRs = $link->query("SELECT uid, b_name, unit_no FROM unit_view ORDER BY b_name ASC, unit_no ASC");
while ($u = mysqli_fetch_assoc($uRs)) { $units[(int)$u['uid']] = $u; }

/* --------- Per-unit payment status (JSON-aware) ---------- */
function payment_status_for_exit(mysqli $link, int $uid, string $exit_date){
  $ps = ['label' => '—', 'class' => 'unknown', 'detail'=> ''];
  if (!is_valid_ymd($exit_date)) return $ps;

  $sum_tr = 0.0;
  $sum_ap = 0.0;

  // We'll pass the candidate as a JSON document string (e.g. "1" => JSON number 1)
  $uid_json = (string)intval($uid);

  // exact end_date
  $sql1 = "
    SELECT
      COALESCE(SUM(r.total_rent / GREATEST(NULLIF(JSON_LENGTH(r.uid),0),1)),0) AS tr,
      COALESCE(SUM(
        (
          r.amt_paid
          + COALESCE(p.paid,0)
          + CASE WHEN COALESCE(p.paid,0)=0 THEN COALESCE(ta.paid,0) ELSE 0 END
        ) / GREATEST(NULLIF(JSON_LENGTH(r.uid),0),1)
      ),0) AS ap
    FROM rent r
    LEFT JOIN (
      SELECT rent_id, SUM(amount) AS paid
      FROM rent_payment_updates
      GROUP BY rent_id
    ) p ON p.rent_id = r.id
    LEFT JOIN (
      SELECT rid, SUM(CASE WHEN trans_type='debit' THEN transaction_amt ELSE 0 END) AS paid
      FROM tenant_accounts
      GROUP BY rid
    ) ta ON ta.rid = r.id
    WHERE (
      (JSON_VALID(r.uid) AND JSON_CONTAINS(r.uid, ?, '$'))
      OR (NOT JSON_VALID(r.uid) AND CAST(r.uid AS UNSIGNED) = ?)
    )
    AND r.end_date = ?
  ";
  if ($stmt = $link->prepare($sql1)) {
    $stmt->bind_param('sis', $uid_json, $uid, $exit_date);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($row = $res->fetch_assoc()) { $sum_tr += (float)$row['tr']; $sum_ap += (float)$row['ap']; }
    $stmt->close();
  }

  // fallback: cumulative up to exit_date
  if ($sum_tr <= 0 && $sum_ap <= 0) {
    $sql2 = "
      SELECT
        COALESCE(SUM(r.total_rent / GREATEST(NULLIF(JSON_LENGTH(r.uid),0),1)),0) AS tr,
        COALESCE(SUM(
          (
            r.amt_paid
            + COALESCE(p.paid,0)
            + CASE WHEN COALESCE(p.paid,0)=0 THEN COALESCE(ta.paid,0) ELSE 0 END
          ) / GREATEST(NULLIF(JSON_LENGTH(r.uid),0),1)
        ),0) AS ap
      FROM rent r
      LEFT JOIN (
        SELECT rent_id, SUM(amount) AS paid
        FROM rent_payment_updates
        GROUP BY rent_id
      ) p ON p.rent_id = r.id
      LEFT JOIN (
        SELECT rid, SUM(CASE WHEN trans_type='debit' THEN transaction_amt ELSE 0 END) AS paid
        FROM tenant_accounts
        GROUP BY rid
      ) ta ON ta.rid = r.id
      WHERE (
        (JSON_VALID(r.uid) AND JSON_CONTAINS(r.uid, ?, '$'))
        OR (NOT JSON_VALID(r.uid) AND CAST(r.uid AS UNSIGNED) = ?)
      )
      AND r.issue_date IS NOT NULL AND r.issue_date <= ?
    ";
    if ($stmt = $link->prepare($sql2)) {
      $stmt->bind_param('sis', $uid_json, $uid, $exit_date);
      $stmt->execute();
      $res = $stmt->get_result();
      if ($row = $res->fetch_assoc()) { $sum_tr += (float)$row['tr']; $sum_ap += (float)$row['ap']; }
      $stmt->close();
    }
  }

  if ($sum_tr <= 0 && $sum_ap <= 0) return $ps;
  if ($sum_ap >= ($sum_tr - 0.00001)) return ['label'=>'Paid','class'=>'paid','detail'=>'Fully settled'];
  if ($sum_ap > 0)                   return ['label'=>'Partial Payment','class'=>'partial','detail'=>'Partially paid'];
  return ['label'=>'Unpaid','class'=>'due','detail'=>'No payment recorded'];
}

/* --------- Bookings overlapping the selected range (JSON-aware per unit) ---------- */
$calendar_rs = $link->query("
  SELECT 
    u.uid,
    t.r_name,
    u.unit_no,
    r.start_date,
    r.end_date
  FROM rent r
  LEFT JOIN tenants t ON t.tid = r.tid
  INNER JOIN unit_view u ON JSON_CONTAINS(r.uid, CAST(u.uid AS CHAR), '$')
  WHERE NOT (r.end_date < '$range_start_sql' OR r.start_date > '$range_end_sql')
  ORDER BY r.start_date ASC, t.r_name ASC, u.unit_no ASC
");

/* Palette for distinct tenant colors */
$palette = [
  '#8b5cf6','#22c55e','#f59e0b','#3b82f6','#ef4444',
  '#06b6d4','#84cc16','#eab308','#a855f7','#10b981',
  '#0ea5e9','#f43f5e','#14b8a6','#f97316','#60a5fa',
  '#34d399','#38bdf8','#fb7185','#c084fc','#bef264'
];
$tenantColor = []; $paletteIdx = 0;

$events = [];
$unitBookings = [];

$all_dates_in_range = each_day_between($range_start, $range_end);

while ($bk = mysqli_fetch_assoc($calendar_rs)) {
  $name = trim($bk['r_name']);
  if (!isset($tenantColor[$name])) {
    $tenantColor[$name] = ($paletteIdx < count($palette)) ? $palette[$paletteIdx++] : '#'.substr(md5($name), 0, 6);
  }
  $color = $tenantColor[$name];
  $uid = (int)$bk['uid'];
  $pay = payment_status_for_exit($link, $uid, $bk['end_date']);

  $events[] = [
    'title'          => $name . ' • ' . $bk['unit_no'],
    'start'          => $bk['start_date'],
    'end'            => plus_one_day($bk['end_date']),
    'backgroundColor'=> $color,
    'borderColor'    => $color,
    'textColor'      => '#ffffff',
    'extendedProps'  => [
      'tenant'    => $name,
      'unit'      => $bk['unit_no'],
      'exitDate'  => $bk['end_date'],
      'enterDate' => $bk['start_date'],
      'payLabel'  => $pay['label'],
      'payClass'  => $pay['class'],
      'payDetail' => $pay['detail']
    ],
  ];

  if (!isset($unitBookings[$uid])) $unitBookings[$uid] = [];
  $unitBookings[$uid][] = [
    'tenant' => $name,
    'start'  => $bk['start_date'],
    'end'    => $bk['end_date'],
    'color'  => $color,
    'pay'    => $pay
  ];
}

$events_json = json_encode($events);
?>
<!-- Content Header -->
<section class="content-header">
  <h1><?= $building_name . ' ' . $_data['dashboard_title']; ?></h1>
  <ol class="breadcrumb">
    <li><a href="<?= WEB_URL; ?>dashboard.php"><i class="fa fa-dashboard"></i> <?= $_data['home_breadcam']; ?></a></li>
    <li class="active"><?= $_data['home_breadcam']; ?></li>
  </ol>
</section>

<!-- Smart, clean UI theme -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
<style>
  :root{
    --bg:#f6f7fb; --card:#ffffff; --ink:#0f172a; --ink2:#334155; --muted:#64748b; --line:#e5e7eb;
    --brand:#3b82f6; --ok:#16a34a; --warn:#f59e0b; --danger:#ef4444;
    --shadow:0 10px 28px rgba(2,6,23,.08);
  }
  body, .content-wrapper, .box, .table, .btn, input, select { font-family:'Inter',system-ui,Segoe UI,Roboto,Helvetica,Arial; color:var(--ink2); }
  .content { background: var(--bg); }
  .content-header>h1{ font-weight:800; color:var(--ink); letter-spacing:.2px; }

  .box { border:1px solid var(--line); border-radius:16px; box-shadow:var(--shadow); overflow:hidden; }
  .box .box-header { background:linear-gradient(180deg,#f2f4f8,#fff); border-bottom:1px solid var(--line); }
  .box .box-header h3, .box .box-header h2 { font-weight:800; color:var(--ink); margin:0; }

  .table thead th{ background:#fafafa; color:var(--ink); font-weight:800; border-bottom:1px solid var(--line) !important; }
  .table td, .table th{ vertical-align:middle !important; }
  .table>tbody>tr:hover{ background:#f9fafb; }

  .btn { border:none; border-radius:10px; font-weight:700; }
  .btn-primary{ background:var(--brand); }
  .btn-success{ background:var(--ok); }
  .btn-warning{ background:var(--warn); color:#111827; }
  .btn-danger{ background:var(--danger); }
  .btn-soft { background:#f1f5f9; color:#0f172a; border:1px solid var(--line); }
  .btn:hover{ filter:brightness(.97); }

  .filter-card{ background:linear-gradient(135deg,#f8fafc,#eef2ff); border:1px solid var(--line); border-radius:12px; padding:10px 12px; }
  .filter-card label{ font-weight:700; color:#334155; margin-right:6px; }
  .quick-range .btn{ border-radius:999px; }

  #booking-calendar .fc .fc-button { border-radius:10px; border:1px solid var(--line); background:#fff; color:#0f172a; font-weight:700; }
  #booking-calendar .fc .fc-button-primary:not(:disabled).fc-button-active,
  #booking-calendar .fc .fc-button-primary:not(:disabled):active { background:var(--brand); border-color:var(--brand); color:#fff; }
  #booking-calendar .fc-col-header-cell-cushion{ padding:8px 0; font-weight:800; color:#0f172a; }
  #booking-calendar .fc-theme-standard td, 
  #booking-calendar .fc-theme-standard th { border-color:#e6eaf0; border-width:1px; }
  #booking-calendar .fc-daygrid-day-frame { padding:6px; }
  #booking-calendar .fc-event { border-radius:8px; box-shadow:0 1px 6px rgba(0,0,0,.12); }
  #booking-calendar .fc-event .fc-event-title { font-weight:700; }

  .legend { display:flex; flex-wrap:wrap; gap:10px; }
  .legend-chip { display:inline-flex; align-items:center; gap:8px; padding:6px 10px; border-radius:999px; background:#f8fafc; border:1px solid var(--line); }
  .legend-swatch { width:14px; height:14px; border-radius:3px; display:inline-block; }

  .roster-wrap { display:flex; flex-direction:column; gap:10px; }
  .unit-card { border:1px solid var(--line); border-radius:12px; padding:12px 14px; background:#fff; box-shadow:0 2px 10px rgba(0,0,0,.04); }
  .unit-title { font-weight:800; color:#0f172a; margin:0 0 6px; }
  .pill { display:inline-flex; align-items:center; gap:10px; padding:8px 12px; border-radius:999px; background:#f8fafc; border:1px solid var(--line); margin:6px 6px 0 0; }
  .pill .dot { width:12px; height:12px; border-radius:50%; display:inline-block; }
  .pill small { color:#334155; font-weight:700; }
  .pill .exit { font-size:12px; color:#334155; padding-left:8px; border-left:1px dashed #cbd5e1; }
  .pay-badge { font-size:11px; padding:3px 8px; border-radius:999px; font-weight:800; letter-spacing:.2px; border:1px solid; }
  .pay-badge.paid    { background:#ecfdf5; color:#065f46; border-color:#a7f3d0; }
  .pay-badge.partial { background:#fff7ed; color:#9a3412; border-color:#fed7aa; }
  .pay-badge.due     { background:#fef2f2; color:#7f1d1d; border-color:#fecaca; }
  .pay-badge.unknown { background:#f1f5f9; color:#334155; border-color:#cbd5e1; }

  .schedule-wrap{ overflow-x:auto; border:1px solid var(--line); border-radius:12px; background:#fff; box-shadow:0 2px 10px rgba(0,0,0,.04); }
  table.schedule-grid{ border-collapse:separate; border-spacing:0; min-width: 960px; }
  .schedule-grid th, .schedule-grid td{ border:1px solid #e6eaf0; padding:8px 10px; white-space:nowrap; }
  .schedule-grid thead th{ background:#fafafa; font-weight:800; }
  .schedule-grid .dow{ text-align:center; font-size:12px; }
  .schedule-grid .dom{ text-align:center; font-size:12px; color:#475569; }
  .schedule-grid .tenant-col{ width:260px; max-width:260px; }
  .schedule-grid .exit-col{ width:160px; text-align:left; }
  .schedule-grid .date-col{ min-width:72px; text-align:center; }

  .sticky-left{ position:sticky; left:0; z-index:3; background:#fff; }
  .sticky-right{ position:sticky; right:0; z-index:3; background:#fff; }

  .tenant-dot{ width:10px; height:10px; border-radius:50%; display:inline-block; margin-right:6px; }
  .tenant-chip{ cursor:default; }
  .occ{ height:26px; border-radius:4px; box-shadow: inset 0 0 0 1px rgba(0,0,0,.06); }
</style>

<section class="content">

  <!-- Calendar + Filters + Legend + Roster -->
  <div class="row">
    <div class="col-xs-12">
      <div class="box box-success">
        <div class="box-header with-border">
          <h3><i class="fa fa-calendar"></i> Bookings Calendar</h3>
          <?php if ($selected_mode): ?>
            <div style="margin-top:6px;display:flex;align-items:center;justify-content:space-between;gap:10px;">
              <div style="font-weight:800;color:#0f172a;">
                Period: <?= htmlspecialchars(human_range($range_start,$range_end)) ?>
              </div>
              <a class="btn btn-soft" href="<?= htmlspecialchars(basename($_SERVER['PHP_SELF'])) ?>">
                <i class="fa fa-calendar-o"></i> Switch to Calendar View
              </a>
            </div>
          <?php endif; ?>
        </div>
        <div class="box-body">
          <div class="filter-card" style="display:flex; flex-wrap:wrap; align-items:center; gap:14px;">
            <form method="get" class="form-inline" style="display:inline-flex; flex-wrap:wrap; gap:10px;">
              <div class="form-group">
                <label for="range_start">From</label>
                <input type="text" class="form-control date-input" id="range_start" name="range_start" value="<?= htmlspecialchars($range_start); ?>" placeholder="YYYY-MM-DD" inputmode="none">
              </div>
              <div class="form-group">
                <label for="range_end">To</label>
                <input type="text" class="form-control date-input" id="range_end" name="range_end" value="<?= htmlspecialchars($range_end); ?>" placeholder="YYYY-MM-DD" inputmode="none">
              </div>
              <input type="hidden" name="sel" id="sel" value="1">
              <button type="submit" class="btn btn-primary"><i class="fa fa-filter"></i> Filter</button>
              <a class="btn btn-soft" href="<?= htmlspecialchars(basename($_SERVER['PHP_SELF'])) ?>"><i class="fa fa-refresh"></i> Reset</a>
            </form>

            <div class="quick-range" style="display:flex; gap:8px; flex-wrap:wrap;">
              <button class="btn btn-soft" data-qrange="7">Next 7 Days</button>
              <button class="btn btn-soft" data-qrange="30">Next 1 Month</button>
              <button class="btn btn-soft" data-qrange="90">Next 3 Months</button>
              <button class="btn btn-soft" data-qrange="365">Next 1 Year</button>
            </div>
          </div>

          <div class="row" style="margin-top:12px;">
            <div class="col-md-7">
              <?php if ($selected_mode): ?>
                <!-- CUSTOM CALENDAR GRID -->
                <div class="box" style="border-radius:12px;">
                  <div class="box-header with-border">
                    <h3 style="margin:0; font-weight:800;">
                      <?= htmlspecialchars(human_range($range_start,$range_end)) ?>
                    </h3>
                  </div>
                  <div class="box-body">
                    <div class="schedule-wrap">
                      <table class="schedule-grid">
                        <thead>
                          <tr>
                            <th class="tenant-col sticky-left">Tenant • Unit</th>
                            <?php
                              $dates = $all_dates_in_range;
                              $dayNames = ['Sun','Mon','Tues','Wed','Thurs','Fri','Sat'];
                              foreach ($dates as $d) {
                                $dow = $dayNames[(int)date('w', strtotime($d))];
                                echo '<th class="date-col dow">'.$dow.'</th>';
                              }
                            ?>
                            <th class="exit-col sticky-right">Exit Date</th>
                          </tr>
                          <tr>
                            <th class="tenant-col sticky-left"></th>
                            <?php
                              foreach ($dates as $d) {
                                $day = (int)date('j', strtotime($d));
                                echo '<th class="date-col dom">'.ordinal($day).'</th>';
                              }
                            ?>
                            <th class="exit-col sticky-right"></th>
                          </tr>
                        </thead>
                        <tbody>
                          <?php
                          foreach ($units as $uid => $uinfo) {
                            $occ = [];
                            $tenantInfos = [];
                            $exitDates = [];

                            if (isset($unitBookings[$uid])) {
                              foreach ($unitBookings[$uid] as $bk) {
                                $stOverlap = max_date($bk['start'], $range_start);
                                $enOverlap = min_date($bk['end'],   $range_end);
                                if ($stOverlap <= $enOverlap) {
                                  foreach (each_day_between($stOverlap,$enOverlap) as $d) {
                                    $occ[$d] = [
                                      'color' => $bk['color'],
                                      'tenant'=> $bk['tenant'],
                                      'start' => $bk['start'],
                                      'end'   => $bk['end'],
                                      'pay'   => $bk['pay']
                                    ];
                                  }
                                  $t = $bk['tenant'];
                                  if (!isset($tenantInfos[$t])) {
                                    $tenantInfos[$t] = [
                                      'color'    => $bk['color'],
                                      'startMin' => $bk['start'],
                                      'endMax'   => $bk['end'],
                                      'pay'      => $bk['pay']
                                    ];
                                  } else {
                                    if (strcmp($bk['start'], $tenantInfos[$t]['startMin']) < 0) $tenantInfos[$t]['startMin'] = $bk['start'];
                                    if (strcmp($bk['end'],   $tenantInfos[$t]['endMax'])   > 0) $tenantInfos[$t]['endMax']   = $bk['end'];
                                    if ($tenantInfos[$t]['endMax'] === $bk['end']) $tenantInfos[$t]['pay'] = $bk['pay'];
                                  }
                                  if (!isset($exitDates[$t]) || strcmp($bk['end'],$exitDates[$t]) < 0) {
                                    $exitDates[$t] = $bk['end'];
                                  }
                                }
                              }
                            }

                            echo '<tr>';
                            echo '<td class="tenant-col sticky-left">';
                            if (!empty($tenantInfos)) {
                              foreach ($tenantInfos as $tenantName => $ti) {
                                $ttTenant = htmlspecialchars($tenantName, ENT_QUOTES, 'UTF-8');
                                $ttUnit   = htmlspecialchars($uinfo['unit_no'], ENT_QUOTES, 'UTF-8');
                                $ttStart  = htmlspecialchars($ti['startMin'], ENT_QUOTES, 'UTF-8');
                                $ttEnd    = htmlspecialchars($ti['endMax'],   ENT_QUOTES, 'UTF-8');
                                $ttPayL   = htmlspecialchars($ti['pay']['label'] ?? '—', ENT_QUOTES, 'UTF-8');
                                $ttPayC   = htmlspecialchars($ti['pay']['class'] ?? 'unknown', ENT_QUOTES, 'UTF-8');
                                $dotColor = htmlspecialchars($ti['color'], ENT_QUOTES, 'UTF-8');

                                echo '<div class="tenant-chip js-grid-tt" '.
                                       'data-tenant="'.$ttTenant.'" '.
                                       'data-unit="'.$ttUnit.'" '.
                                       'data-start="'.$ttStart.'" '.
                                       'data-end="'.$ttEnd.'" '.
                                       'data-paylabel="'.$ttPayL.'" '.
                                       'data-payclass="'.$ttPayC.'">'.
                                      '<span class="tenant-dot" style="background:'.$dotColor.'"></span>'.
                                      htmlspecialchars($tenantName).' • '.htmlspecialchars($uinfo['unit_no']).
                                     '</div>';
                              }
                            } else {
                              echo '<em>No tenant in this period - '.htmlspecialchars($uinfo['unit_no']).'</em>';
                            }
                            echo '</td>';

                            foreach ($dates as $d) {
                              if (isset($occ[$d])) {
                                $od = $occ[$d];
                                $ttTenant = htmlspecialchars($od['tenant'], ENT_QUOTES, 'UTF-8');
                                $ttUnit   = htmlspecialchars($uinfo['unit_no'], ENT_QUOTES, 'UTF-8');
                                $ttStart  = htmlspecialchars($od['start'], ENT_QUOTES, 'UTF-8');
                                $ttEnd    = htmlspecialchars($od['end'],   ENT_QUOTES, 'UTF-8');
                                $ttPayL   = htmlspecialchars($od['pay']['label'] ?? '—', ENT_QUOTES, 'UTF-8');
                                $ttPayC   = htmlspecialchars($od['pay']['class'] ?? 'unknown', ENT_QUOTES, 'UTF-8');
                                $bg       = htmlspecialchars($od['color'], ENT_QUOTES, 'UTF-8');

                                echo '<td class="date-col">'.
                                       '<div class="occ js-grid-tt" '.
                                         'style="background:'.$bg.';" '.
                                         'data-tenant="'.$ttTenant.'" '.
                                         'data-unit="'.$ttUnit.'" '.
                                         'data-start="'.$ttStart.'" '.
                                         'data-end="'.$ttEnd.'" '.
                                         'data-paylabel="'.$ttPayL.'" '.
                                         'data-payclass="'.$ttPayC.'"></div>'.
                                     '</td>';
                              } else {
                                echo '<td class="date-col"></td>';
                              }
                            }

                            echo '<td class="exit-col sticky-right">';
                            if (!empty($exitDates)) {
                              foreach ($exitDates as $tenant=>$ed) {
                                $c = htmlspecialchars($tenantInfos[$tenant]['color'] ?? '#475569', ENT_QUOTES, 'UTF-8');
                                echo '<div style="display:flex;align-items:center;gap:6px;margin:4px 0;">'
                                  . '<span class="tenant-dot" style="background:'.$c.'"></span>'
                                  . '<span>'.htmlspecialchars(short_exit_date($ed)).'</span>'
                                  . '</div>';
                              }
                            } else {
                              echo '<span style="color:#94a3b8;">—</span>';
                            }
                            echo '</td>';

                            echo '</tr>';
                          }
                          ?>
                        </tbody>
                      </table>
                    </div>

                    <?php if (!empty($tenantColor)) { ?>
                      <hr>
                      <div class="legend">
                        <?php foreach ($tenantColor as $tenantName => $colorHex): ?>
                          <span class="legend-chip">
                            <span class="legend-swatch" style="background:<?= htmlspecialchars($colorHex) ?>"></span>
                            <small><?= htmlspecialchars($tenantName) ?></small>
                          </span>
                        <?php endforeach; ?>
                      </div>
                    <?php } ?>
                  </div>
                </div>
              <?php else: ?>
                <!-- Full month view -->
                <div id="booking-calendar"></div>
                <?php if (!empty($tenantColor)) { ?>
                  <hr>
                  <div class="legend">
                    <?php foreach ($tenantColor as $tenantName => $colorHex): ?>
                      <span class="legend-chip">
                        <span class="legend-swatch" style="background:<?= htmlspecialchars($colorHex) ?>"></span>
                        <small><?= htmlspecialchars($tenantName) ?></small>
                      </span>
                    <?php endforeach; ?>
                  </div>
                <?php } ?>
              <?php endif; ?>
            </div>

            <div class="col-md-5">
              <h4 style="font-weight:800; margin-top:0; color:#0f172a;">
                Units & Bookings (<?= htmlspecialchars(human_date($range_start)) ?> → <?= htmlspecialchars(human_date($range_end)) ?>)
              </h4>
              <div class="roster-wrap">
                <?php
                foreach ($units as $uid => $uinfo) {
                  $bookings = isset($unitBookings[$uid]) ? $unitBookings[$uid] : [];
                  echo '<div class="unit-card">';
                  echo '<div class="unit-title">'.htmlspecialchars($uinfo['b_name']).' • '.htmlspecialchars($uinfo['unit_no']).'</div>';
                  if (!empty($bookings)) {
                    echo '<div>';
                    foreach ($bookings as $b) {
                      $exit_words = format_words_date($b['end']);
                      echo '<span class="pill" title="Exit: '.htmlspecialchars($exit_words).'">';
                      echo '<span class="dot" style="background:'.htmlspecialchars($b['color']).'"></span>';
                      echo '<small>'.htmlspecialchars($b['tenant']).'</small>';
                      echo ' <span class="pay-badge '.htmlspecialchars($b['pay']['class']).'" title="'.htmlspecialchars($b['pay']['detail']).'">'.htmlspecialchars($b['pay']['label']).'</span>';
                      echo '<span class="exit"><strong>Exit:</strong> '.htmlspecialchars($exit_words).'</span>';
                      echo '</span>';
                    }
                    echo '</div>';
                  } else {
                    echo '<span class="pill" style="border-style:dashed;"><span class="dot" style="background:#94a3b8"></span><small>No bookings in selected period</small></span>';
                  }
                  echo '</div>';
                }
                ?>
              </div>
            </div>
          </div>

        </div>
      </div>
    </div>
  </div>

  <!-- Overview (All-time & Year) -->
  <div class="row home_dash_box">
    <div class="col-lg-6 ov-cards-1">
      <div class="box box-success">
        <div class="box-header with-border"><h2>&nbsp;&nbsp;<i class="fa fa-comments"></i> General Overview</h2></div>
        <div class="box-body">
          <style>
            .ov-cards-1 .small-box { border-radius:14px; box-shadow:0 4px 16px rgba(0,0,0,.06); overflow:hidden; transition:transform .15s ease, box-shadow .15s ease; }
            .ov-cards-1 .small-box:hover { transform:translateY(-2px); box-shadow:0 8px 24px rgba(0,0,0,.08); }
            .ov-cards-1 .small-box .inner { padding:16px 18px 12px; }
            .ov-cards-1 .small-box .icon { right:14px; top:12px; opacity:.15; font-size:56px; }
            .ov-cards-1 .small-box-footer { background:rgba(255,255,255,.18); border-top:none; display:block; padding:10px 14px; font-weight:600; color:#fff !important; }
            .sb2-rent{ background:linear-gradient(135deg,#3B82F6,#60A5FA); color:#fff; }
            .sb2-profit{ background:linear-gradient(135deg,#10B981,#34D399); color:#063324; }
            .sb2-maintenance{ background:linear-gradient(135deg,#F59E0B,#FBBF24); color:#2b1d02; }
            .sb2-units{ background:linear-gradient(135deg,#0EA5E9,#38BDF8); color:#052231; }
            .sb2-tenants{ background:linear-gradient(135deg,#FB7185,#FDA4AF); color:#3b0a12; }
          </style>
          <div class="row">
            <div class="col-xl-4 col-lg-6 col-md-6 col-xs-6">
              <div class="small-box sb2-rent">
                <div class="inner"><h4><?= money_print($total_rentt); ?></h4><p>Total Rent</p></div>
                <div class="icon"><i class="fa fa-money"></i></div>
                <a href="<?= WEB_URL; ?>rent/rentlist.php" class="small-box-footer"><?= $_data['dashboard_more_info']; ?> <i class="fa fa-arrow-circle-right"></i></a>
              </div>
            </div>
            <div class="col-xl-4 col-lg-6 col-md-6 col-xs-6">
              <div class="small-box sb2-profit">
                <div class="inner"><h4><?= money_print($total_rentt - $total_tmc); ?></h4><p>Total Profit</p></div>
                <div class="icon"><i class="fa fa-money"></i></div>
                <a href="<?= WEB_URL; ?>rent/rentlist.php" class="small-box-footer"><?= $_data['dashboard_more_info']; ?> <i class="fa fa-arrow-circle-right"></i></a>
              </div>
            </div>
            <div class="col-xl-4 col-lg-6 col-md-6 col-xs-6">
              <div class="small-box sb2-maintenance">
                <div class="inner"><h4><?= money_print($total_tmc); ?></h4><p><?= $_data['dashboard_total_maintenance']; ?></p></div>
                <div class="icon"><i class="fa fa-cogs"></i></div>
                <a href="<?= WEB_URL; ?>maintenance/maintenance_cost_list.php" class="small-box-footer"><?= $_data['dashboard_more_info']; ?> <i class="fa fa-arrow-circle-right"></i></a>
              </div>
            </div>
            <div class="col-xl-4 col-lg-6 col-md-6 col-xs-6">
              <div class="small-box sb2-units">
                <div class="inner"><h4><?= $total_units; ?></h4><p><?= $_data['dashboard_total_unit'] ?></p></div>
                <div class="icon"><i class="fa fa-building"></i></div>
                <a href="<?= WEB_URL; ?>unit/unitlist.php" class="small-box-footer"><?= $_data['dashboard_more_info'] ?> <i class="fa fa-arrow-circle-right"></i></a>
              </div>
            </div>
            <div class="col-xl-4 col-lg-6 col-md-6 col-xs-6">
              <div class="small-box sb2-tenants">
                <div class="inner"><h4><?= $total_tenants; ?></h4><p><?= $_data['dashboard_total_rented']; ?>s</p></div>
                <div class="icon"><i class="fa fa-users"></i></div>
                <a href="<?= WEB_URL; ?>tenant/tenantlist.php" class="small-box-footer"><?= $_data['dashboard_more_info']; ?> <i class="fa fa-arrow-circle-right"></i></a>
              </div>
            </div>
          </div>

        </div>
      </div>
    </div>

    <div class="col-lg-6">
      <div class="box box-success">
        <div class="box-header with-border"><h2>&nbsp;&nbsp;<i class="fa fa-comments"></i> Annual Overview For <?= date("Y") ?></h2></div>
        <div class="box-body">
          <style>
            .small-box{ border-radius:14px; box-shadow:0 4px 16px rgba(0,0,0,.06); overflow:hidden; transition:transform .15s ease, box-shadow .15s ease; }
            .small-box:hover{ transform:translateY(-2px); box-shadow:0 8px 24px rgba(0,0,0,.08); }
            .small-box .inner{ padding:16px 18px 12px; }
            .small-box .icon{ right:14px; top:12px; opacity:.15; font-size:56px; }
            .small-box-footer{ background:rgba(255,255,255,.18); border-top:none !important; display:block; padding:10px 14px; font-weight:600; color:#fff !important; }
            .sb-rent{ background:linear-gradient(135deg,#3B82F6,#60A5FA); color:#fff; }
            .sb-profit{ background:linear-gradient(135deg,#10B981,#34D399); color:#06281e; }
            .sb-maintenance{ background:linear-gradient(135deg,#F59E0B,#FBBF24); color:#2b1d02; }
            .sb-recv{ background:linear-gradient(135deg,#8B5CF6,#A78BFA); color:#180b33; }
            .sb-units{ background:linear-gradient(135deg,#0EA5E9,#38BDF8); color:#052231; }
            .sb-tenants{ background:linear-gradient(135deg,#FB7185,#FDA4AF); color:#3b0a12; }
          </style>
          <div class="row">
            <div class="col-xl-4 col-lg-6 col-md-6 col-xs-6">
              <div class="small-box sb-rent">
                <div class="inner"><h4><?= money_print($total_rent); ?></h4><p>Total Rent</p></div>
                <div class="icon"><i class="fa fa-money"></i></div>
                <a href="<?= WEB_URL; ?>rent/rentlist.php" class="small-box-footer"><?= $_data['dashboard_more_info']; ?> <i class="fa fa-arrow-circle-right"></i></a>
              </div>
            </div>
            <div class="col-xl-4 col-lg-6 col-md-6 col-xs-6">
              <div class="small-box sb-profit">
                <div class="inner"><h4><?= money_print($total_rent - $total_mc); ?></h4><p>Total Profit</p></div>
                <div class="icon"><i class="fa fa-money"></i></div>
                <a href="<?= WEB_URL; ?>rent/rentlist.php" class="small-box-footer"><?= $_data['dashboard_more_info']; ?> <i class="fa fa-arrow-circle-right"></i></a>
              </div>
            </div>
            <div class="col-xl-4 col-lg-6 col-md-6 col-xs-6">
              <div class="small-box sb-maintenance">
                <div class="inner"><h4><?= money_print($total_mc); ?></h4><p><?= $_data['dashboard_total_maintenance']; ?></p></div>
                <div class="icon"><i class="fa fa-cogs"></i></div>
                <a href="<?= WEB_URL; ?>maintenance/maintenance_cost_list.php" class="small-box-footer"><?= $_data['dashboard_more_info']; ?> <i class="fa fa-arrow-circle-right"></i></a>
              </div>
            </div>
            <div class="col-xl-4 col-lg-6 col-md-6 col-xs-6">
              <div class="small-box sb-recv">
                <div class="inner"><h4><?= money_print($total_payables); ?></h4><p>Total Receivables</p></div>
                <div class="icon"><i class="fa fa-money"></i></div>
                <a href="<?= WEB_URL; ?>rent/rentlist.php" class="small-box-footer"><?= $_data['dashboard_more_info']; ?> <i class="fa fa-arrow-circle-right"></i></a>
              </div>
            </div>
            <div class="col-xl-4 col-lg-6 col-md-6 col-xs-6">
              <div class="small-box sb-units">
                <div class="inner"><h4><?= $total_units; ?></h4><p><?= $_data['dashboard_total_unit'] ?></p></div>
                <div class="icon"><i class="fa fa-building"></i></div>
                <a href="<?= WEB_URL; ?>unit/unitlist.php" class="small-box-footer"><?= $_data['dashboard_more_info'] ?> <i class="fa fa-arrow-circle-right"></i></a>
              </div>
            </div>
            <div class="col-xl-4 col-lg-6 col-md-6 col-xs-6">
              <div class="small-box sb-tenants">
                <div class="inner"><h4><?= $total_tenants; ?></h4><p><?= $_data['dashboard_total_rented']; ?>s</p></div>
                <div class="icon"><i class="fa fa-users"></i></div>
                <a href="<?= WEB_URL; ?>tenant/tenantlist.php" class="small-box-footer"><?= $_data['dashboard_more_info']; ?> <i class="fa fa-arrow-circle-right"></i></a>
              </div>
            </div>
          </div>

        </div>
      </div>
    </div>
  </div>

  <!-- Units Available (next 6 months) -->
  <div class="row">
    <div class="col-xs-12">
      <div class="box box-success">
        <div class="box-header with-border">
          <h3><i class="fa fa-building"></i> Units & Their Available Dates (Next 6 Months)</h3>
        </div>
        <div class="box-body">

          <style>
            .avail-toolbar{
              display:flex; gap:12px; align-items:center; flex-wrap:wrap;
              background:linear-gradient(135deg,#f8fafc,#eef2ff); border:1px solid var(--line);
              border-radius:12px; padding:10px 12px; margin-bottom:12px;
            }
            .avail-toolbar .search{
              display:flex; align-items:center; gap:8px; background:#fff; border:1px solid var(--line);
              padding:8px 10px; border-radius:10px; min-width:240px;
            }
            .avail-toolbar .search input{ border:none; outline:none; width:180px; }
            .avail-toolbar .count{ margin-left:auto; font-weight:700; color:#0f172a; }
            .toggle{ display:inline-flex; align-items:center; gap:8px; font-weight:700; color:#334155; user-select:none; cursor:pointer; }
            .toggle input{ display:none; }
            .toggle .track{ width:42px; height:24px; background:#e5e7eb; border-radius:999px; position:relative; box-shadow:inset 0 0 0 1px rgba(15,23,42,.08); }
            .toggle .thumb{ position:absolute; top:3px; left:3px; width:18px; height:18px; background:#fff; border-radius:50%; box-shadow:0 1px 3px rgba(0,0,0,.12); transition:transform .18s ease, left .18s ease; }
            .toggle input:checked + .track{ background:#16a34a; }
            .toggle input:checked + .track .thumb{ left:21px; }

            .table-scroll{ overflow:auto; border:1px solid var(--line); border-radius:12px; box-shadow:0 2px 10px rgba(0,0,0,.04); background:#fff; }
            table.avail-table{ border-collapse:separate; border-spacing:0; min-width:900px; width:100%; }
            .avail-table thead th{ position:sticky; top:0; z-index:2; background:#fafafa; color:#0f172a; font-weight:800; border-bottom:1px solid var(--line) !important; }
            .avail-table th, .avail-table td{ border-bottom:1px solid #eef2f7; padding:10px 12px; vertical-align:middle; }
            .avail-table tbody tr:hover{ background:#f9fafb; }
            .avail-table .col-block{ position:sticky; left:0; z-index:1; background:#fff; min-width:140px; font-weight:700; }
            .avail-table .col-unit{ position:sticky; left:140px; z-index:1; background:#fff; min-width:100px; color:#0f172a; }
            .status-pill{ display:inline-flex; align-items:center; gap:6px; font-size:12px; font-weight:800; border-radius:999px; padding:4px 10px; border:1px solid; }
            .status-pill.available{ background:#ecfdf5; color:#065f46; border-color:#a7f3d0; }
            .status-pill.full{ background:#f1f5f9; color:#334155; border-color:#cbd5e1; }
            .availability-chips{ display:flex; flex-wrap:wrap; gap:6px; align-items:center; margin-top:6px; }
            .availability-chip{ display:inline-flex; align-items:center; gap:6px; background:#00a65a; color:#fff; border-radius:999px; padding:4px 10px; font-size:12px; line-height:1.2; white-space:nowrap; }
          </style>

          <div class="avail-toolbar">
            <div class="search">
              <i class="fa fa-search"></i>
              <input type="text" id="availSearch" placeholder="Search block or unit…">
            </div>
            <label class="toggle">
              <input type="checkbox" id="availOnly">
              <span class="track"><span class="thumb"></span></span> Show only available
            </label>
            <div class="count" id="availCount"></div>
          </div>

          <div class="table-scroll">
            <table id="availTable" class="table avail-table">
              <thead>
                <tr>
                  <th class="col-block">Block</th>
                  <th class="col-unit">Unit</th>
                  <th>Available Dates (next 6 months)</th>
                </tr>
              </thead>
              <tbody>
                <?php
                $first = date('Y-m-d');
                $last  = date('Y-m-d', strtotime('+6 months'));
                $uRs2 = $link->query("SELECT bid, uid, b_name, unit_no FROM unit_view ORDER BY b_name, unit_no");
                while ($u = mysqli_fetch_assoc($uRs2)) {
                  $uid_i = (int)$u['uid'];
                  $bRs = $link->query("
                    SELECT GREATEST(r.start_date, '$first') AS s, LEAST(r.end_date, '$last') AS e
                    FROM rent r
                    WHERE JSON_CONTAINS(r.uid, CAST($uid_i AS CHAR), '$')
                      AND NOT (r.end_date < '$first' OR r.start_date > '$last')
                    ORDER BY s
                  ");
                  $busy = [];
                  while ($b = mysqli_fetch_assoc($bRs)) { if($b['s'] && $b['e']) $busy[] = $b; }
                  usort($busy, function($a,$b){ return strcmp($a['s'],$b['s']); });

                  $merged = [];
                  foreach ($busy as $p) {
                    if (empty($merged)) { $merged[] = $p; }
                    else {
                      $i = count($merged)-1; $L = &$merged[$i];
                      $nextDay = date('Y-m-d', strtotime($L['e'].' +1 day'));
                      if ($p['s'] <= $nextDay) { if ($p['e'] > $L['e']) $L['e'] = $p['e']; }
                      else { $merged[] = $p; }
                    }
                  }

                  $free = []; $cur = $first;
                  foreach ($merged as $m) {
                    if ($cur < $m['s']) { $free[] = ['start'=>$cur, 'end'=>date('Y-m-d', strtotime($m['s'].' -1 day'))]; }
                    $cur = date('Y-m-d', strtotime($m['e'].' +1 day'));
                  }
                  if ($cur <= $last) { $free[] = ['start'=>$cur, 'end'=>$last]; }

                  $chips = '';
                  foreach ($free as $f) {
                    $chips .= '<span class="availability-chip" title="Available: '.htmlspecialchars($f['start']).' to '.htmlspecialchars($f['end']).'"><i class="fa fa-calendar-check-o"></i>'.htmlspecialchars(format_words_range($f['start'],$f['end'])).'</span>';
                  }
                  $hasAvail = !empty($free);
                  if ($hasAvail) {
                    $n = count($free);
                    $label = $n > 1 ? ($n.' windows') : 'Available';
                    $status = '<span class="status-pill available"><i class="fa fa-check-circle"></i>'.$label.'</span>';
                    $avail_html = '<div>'.$status.'<div class="availability-chips">'.$chips.'</div></div>';
                  } else {
                    $avail_html = '<span class="status-pill full"><i class="fa fa-ban"></i> Fully Occupied</span>';
                  }

                  $key = strtolower($u['b_name'].' '.$u['unit_no']);
                  echo '<tr data-key="'.htmlspecialchars($key,ENT_QUOTES).'" data-available="'.($hasAvail?1:0).'">';
                  echo '<td class="col-block">'.htmlspecialchars($u['b_name']).'</td>';
                  echo '<td class="col-unit">'.htmlspecialchars($u['unit_no']).'</td>';
                  echo '<td>'.$avail_html.'</td>';
                  echo '</tr>';
                }
                ?>
              </tbody>
            </table>
          </div>

          <script>
            (function(){
              var table = document.getElementById('availTable');
              var rows  = Array.prototype.slice.call(table.querySelectorAll('tbody tr'));
              var search = document.getElementById('availSearch');
              var only = document.getElementById('availOnly');
              var count = document.getElementById('availCount');

              function apply(){
                var q = (search.value || '').trim().toLowerCase();
                var onlyAvail = !!only.checked;
                var total = rows.length, shown = 0;

                rows.forEach(function(tr){
                  var ok = true;
                  if (q) ok = (tr.dataset.key||'').indexOf(q) > -1;
                  if (ok && onlyAvail) ok = tr.dataset.available === '1';
                  tr.style.display = ok ? '' : 'none';
                  if (ok) shown++;
                });
                count.textContent = 'Showing ' + shown + ' of ' + total + ' units';
              }
              search.addEventListener('input', apply);
              only.addEventListener('change', apply);
              apply();
            })();
          </script>

        </div>
      </div>
    </div>
  </div>

<style>
  .due-card .box-header { background: linear-gradient(180deg,#f8fafc,#ffffff); }
  .due-card .box-title { font-weight: 800; letter-spacing: .2px; color: #0f172a; }
  .due-card .box-body { padding-top: 0; }

  .klist-table { width: 100%; border-collapse: separate; border-spacing: 0 8px; }
  .klist-table thead th{ background:#f1f5f9; color:#0f172a; font-weight:800; border:none !important; text-transform: uppercase; font-size: 12px; letter-spacing: .6px; }
  .klist-table tbody tr{ background:#fff; border:1px solid #e5e7eb; border-radius:12px; overflow:hidden; box-shadow: 0 4px 12px rgba(2,6,23,.04); }
  .klist-table tbody tr:hover{ box-shadow: 0 8px 20px rgba(2,6,23,.08); }
  .klist-table td, .klist-table th { padding: 12px 14px !important; vertical-align: middle !important; border: none !important; }
  .klist-table .col-name{ font-weight:700; color:#0f172a; }
  .klist-table .col-unit{ color:#334155; font-weight:600; }

  .chip{ display:inline-flex; align-items:center; gap:6px; padding:6px 10px; border-radius:999px; font-size:12px; font-weight:700; letter-spacing:.2px; white-space:nowrap; }
  .chip i{ font-size:12px; }
  .chip.due-today{ background:#fee2e2; color:#7f1d1d; border:1px solid #fecaca; }
  .chip.due-1d   { background:#fff7ed; color:#9a3412; border:1px solid #fed7aa; }
  .chip.due-soon { background:#fef3c7; color:#78350f; border:1px solid #fde68a; }
  .chip.ok       { background:#ecfdf5; color:#065f46; border:1px solid #a7f3d0; }

  .pill-date{ display:inline-flex; align-items:center; gap:8px; padding:6px 10px; border-radius:10px; background:#eef2ff; color:#1e293b; font-weight:700; font-size:12px; border:1px solid #c7d2fe; }

  .empty-state{ padding:28px; text-align:center; color:#64748b; background:#f8fafc; border:1px dashed #e5e7eb; border-radius:12px; }
</style>

<div class="row">
  <!-- Tenants Closest to End of Rent -->
  <div class="col-lg-6">
    <div class="box box-success due-card" style="min-height:40vh;">
      <div class="box-header with-border">
        <h3 class="box-title">&nbsp;&nbsp;<i class="fa fa-hourglass-end"></i> Tenants Closest to End of Rent</h3>
      </div>
      <div class="box-body">
        <table class="table klist-table">
          <thead>
            <tr>
              <th>Name</th>
              <th>Unit/Shop</th>
              <th style="width:40%;">Checkout</th>
            </tr>
          </thead>
          <tbody>
            <?php
            date_default_timezone_set('Africa/Accra');

            $result = mysqli_query($link, "
              SELECT t.r_name, u.unit_no, r.end_date
              FROM rent r
              JOIN tenants t ON t.tid = r.tid
              JOIN unit_view u ON JSON_CONTAINS(r.uid, CAST(u.uid AS CHAR), '$')
              WHERE r.end_date >= CURDATE() AND r.end_date <= DATE_ADD(CURDATE(), INTERVAL 1 DAY)
              ORDER BY r.end_date ASC, t.r_name ASC, u.unit_no ASC
            ");

            $hadRows = false;

            $tz = new DateTimeZone('Africa/Accra');
            $today = new DateTime('today', $tz);

            while ($row = mysqli_fetch_assoc($result)) {
              $hadRows = true;

              $endObj = new DateTime($row['end_date'], $tz);
              $endMidnight = (clone $endObj)->setTime(0,0,0);
              $daysLeft = (int)$today->diff($endMidnight)->format('%r%a');

              if ($daysLeft === 0) { $chipClass = 'due-today'; $chipText  = 'Ends today'; }
              elseif ($daysLeft === 1) { $chipClass = 'due-1d'; $chipText  = 'In 1 day'; }
              elseif ($daysLeft > 1) { $chipClass = 'due-soon'; $chipText  = 'In ' . $daysLeft . ' days'; }
              else { $chipClass = 'ok'; $chipText  = 'Ended'; }

              $dateLabel = format_words_date($row['end_date']);

              echo '<tr>
                      <td class="col-name">'.htmlspecialchars($row["r_name"]).'</td>
                      <td class="col-unit">'.htmlspecialchars($row["unit_no"]).'</td>
                      <td>
                        <span class="pill-date"><i class="fa fa-calendar"></i>'.htmlspecialchars($dateLabel).'</span>
                        &nbsp;
                        <span class="chip '.$chipClass.'"><i class="fa fa-clock-o"></i>'.$chipText.'</span>
                      </td>
                    </tr>';
            }

            if (!$hadRows) {
              echo '<tr><td colspan="3"><div class="empty-state"><i class="fa fa-check-circle"></i> Nothing due within the next day.</div></td></tr>';
            }
            ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- Reminders Almost Due -->
  <div class="col-lg-6">
    <div class="box box-success due-card" style="min-height:40vh;">
      <div class="box-header with-border">
        <h3 class="box-title">&nbsp;&nbsp;<i class="fa fa-bell-o"></i> Reminders Almost Due</h3>
      </div>
      <div class="box-body">
        <table class="table klist-table">
          <thead>
            <tr>
              <th>Reminder</th>
              <th style="width:40%;">End Date</th>
              <th style="text-align:center; width:120px;">Days Left</th>
            </tr>
          </thead>
          <tbody>
            <?php
            $query = "
              SELECT * 
              FROM meetings 
              WHERE issue_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY)
              ORDER BY issue_date ASC
            ";
            $result = mysqli_query($link, $query);
            $hadRows2 = false;

            while ($row = mysqli_fetch_assoc($result)) {
              $hadRows2 = true;

              $issue_ts = strtotime($row["issue_date"]);
              $today_ts = strtotime(date('Y-m-d'));
              $days_until_due = (int)ceil(($issue_ts - $today_ts) / 86400);

              if ($days_until_due <= 0) { $c='due-today'; $t='Due today'; }
              elseif ($days_until_due == 1) { $c='due-1d'; $t='In 1 day'; }
              elseif ($days_until_due <= 3) { $c='due-soon'; $t='In '.$days_until_due.' days'; }
              else { $c='ok'; $t='In '.$days_until_due.' days'; }

              echo '<tr>
                      <td class="col-name">'.htmlspecialchars($row["meeting_title"]).'</td>
                      <td>
                        <span class="pill-date"><i class="fa fa-calendar"></i>'.htmlspecialchars(format_words_date($row["issue_date"])).'</span>
                        &nbsp;<span class="chip '.$c.'"><i class="fa fa-clock-o"></i>'.$t.'</span>
                      </td>
                      <td style="text-align:center; font-weight:800; color:#0f172a;">'.$days_until_due.'</td>
                    </tr>';
            }

            if (!$hadRows2) {
              echo '<tr><td colspan="3"><div class="empty-state"><i class="fa fa-smile-o"></i> No reminders in the next 7 days.</div></td></tr>';
            }
            ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

</section>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.11/main.min.css">
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.11/index.global.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/tippy.js@6.3.7/dist/tippy-bundle.umd.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tippy.js@6.3.7/dist/tippy.css"/>

<style>
  .tippy-box[data-theme~='light'] {
    background-color:#fff; color:#0f172a; border:1px solid #e5e7eb; box-shadow:0 10px 30px rgba(2,6,23,.12);
  }
</style>

<style>
.flatpickr-calendar{
  border-radius:12px !important;
  box-shadow:0 12px 28px rgba(2,6,23,.15) !important;
  border:1px solid #e5e7eb !important;
  font-family:'Inter', system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial !important;
}
.flatpickr-day.selected,
.flatpickr-day.startRange,
.flatpickr-day.endRange{
  background:#2563eb !important;
  border-color:#2563eb !important;
  color:#fff !important;
}
flatpickr-day.today{ border-color:#93c5fd !important; }
</style>

<script type="text/javascript">
(function(){
  function toYMD(d){ const z=n=>('0'+n).slice(-2); return d.getFullYear()+'-'+z(d.getMonth()+1)+'-'+z(d.getDate()); }
  function addDays(d, n){ const x=new Date(d); x.setDate(x.getDate()+n); return x; }

  const startEl = document.getElementById('range_start');
  const endEl   = document.getElementById('range_end');
  const selEl   = document.getElementById('sel');

  document.querySelectorAll('.quick-range .btn').forEach(btn=>{
    btn.addEventListener('click', function(e){
      e.preventDefault();
      const days = parseInt(this.getAttribute('data-qrange'),10)||7;
      const today = new Date();
      const until = addDays(today, days-1);
      startEl.value = toYMD(today);
      endEl.value   = toYMD(until);
      if (selEl) selEl.value = '1';
      this.closest('.filter-card').querySelector('form').submit();
    });
  });
})();

function ord(n){ n=parseInt(n,10); if([11,12,13].indexOf(n%100)>-1) return n+'th'; let m=n%10; return n+(m===1?'st':m===2?'nd':m===3?'rd':'th'); }
function fmt(ymd){
  var dt = new Date(ymd+'T00:00:00');
  var months=['January','February','March','April','May','June','July','August','September','October','November','December'];
  if (isNaN(dt.getTime())) return ymd;
  return ord(dt.getDate())+' '+months[dt.getMonth()]+', '+dt.getFullYear();
}

(function initGridTooltips(){
  var grid = document.querySelector('.schedule-grid');
  if (!grid) return;

  function ttHTML(tenant, unit, start, end, payLabel, payClass){
    var badge = payLabel ? ('<span class="pay-badge '+payClass+'">'+payLabel+'</span>') : '';
    var range = (start && end) ? (fmt(start)+' → '+fmt(end)) : '';
    return '<div style="min-width:220px;">'
      + '<div style="font-weight:800;color:#0f172a;margin-bottom:4px;">'+(tenant||'')+' • '+(unit||'')+'</div>'
      + (range?('<div style="color:#334155;margin-bottom:6px;">'+range+'</div>'):'')
      + (badge?('<div>'+badge+'</div>'):'')
      + '</div>';
  }

  document.querySelectorAll('.js-grid-tt').forEach(function(el){
    var d = el.dataset;
    tippy(el, {
      content: ttHTML(d.tenant, d.unit, d.start, d.end, d.paylabel, d.payclass),
      allowHTML: true,
      theme: 'light',
      placement: 'top',
      animation: 'scale',
      duration: [200,150]
    });
  });
})();

document.addEventListener('DOMContentLoaded', function () {
  var calEl = document.getElementById('booking-calendar');
  if (!calEl) return;

  var events = <?= $events_json ?: '[]' ?>;

  var calendar = new FullCalendar.Calendar(calEl, {
    initialView: 'dayGridMonth',
    height: 'auto',
    dayMaxEventRows: 3,
    selectable: true,
    selectMirror: true,
    headerToolbar: {
      left: 'prev,next today',
      center: 'title',
      right: 'dayGridMonth,timeGridWeek,listMonth'
    },
    views: {
      dayGridMonth:{ titleFormat:{ year:'numeric', month:'long'} },
      timeGridWeek:{ titleFormat:{ year:'numeric', month:'short', day:'numeric'} },
      listMonth:{ noEventsText: 'No bookings' }
    },
    nowIndicator: true,
    navLinks: true,
    events: events,
    displayEventTime: false,

    select: function(info){
      var start = info.startStr;
      var endExclusive = info.endStr;
      var end = new Date(endExclusive);
      end.setDate(end.getDate()-1);
      var z=n=>('0'+n).slice(-2);
      var endStr = end.getFullYear()+'-'+z(end.getMonth()+1)+'-'+z(end.getDate());
      window.location = '?range_start='+start+'&range_end='+endStr+'&sel=1';
    },

    dateClick: function(info){
      var day = info.dateStr;
      window.location = '?range_start='+day+'&range_end='+day+'&sel=1';
    },

    eventDidMount: function(info) {
      var p = info.event.extendedProps || {};
      var rangeWords = (p.enterDate && p.exitDate) ? (fmt(p.enterDate)+' → '+fmt(p.exitDate)) : '';
      var badge = p.payLabel ? ('<span class="pay-badge '+p.payClass+'">'+p.payLabel+'</span>') : '';
      var html = '<div style="min-width:220px;"><div style="font-weight:800;color:#0f172a;margin-bottom:4px;">'+(p.tenant||'')+' • '+(p.unit||'')+'</div>'
               + (rangeWords?('<div style="color:#334155;margin-bottom:6px;">'+rangeWords+'</div>'):'')
               + (badge?('<div>'+badge+'</div>'):'')
               + '</div>';
      tippy(info.el, { content: html, allowHTML: true, theme:'light', placement:'top', animation:'scale', duration:[200,150] });
      info.el.style.borderRadius = '8px';
    }
  });

  calendar.render();
});
</script>

<script>
(function ensureFlatpickrAndInit(){
  function initPickers(){
    if (!window.flatpickr) return;

    var opts = { dateFormat: 'Y-m-d', allowInput: true, clickOpens: true };

    var start = document.getElementById('range_start');
    var end   = document.getElementById('range_end');

    var fpStart = flatpickr(start, Object.assign({}, opts, {
      defaultDate: start.value || null,
      onChange: function(selectedDates){
        if (selectedDates && selectedDates[0]) fpEnd.set('minDate', selectedDates[0]);
      }
    }));

    var fpEnd = flatpickr(end, Object.assign({}, opts, {
      defaultDate: end.value || null,
      onChange: function(selectedDates){
        if (selectedDates && selectedDates[0]) fpStart.set('maxDate', selectedDates[0]);
      }
    }));

    if (start.value) fpEnd.set('minDate', start.value);
    if (end.value)   fpStart.set('maxDate', end.value);

    document.querySelectorAll('.quick-range .btn').forEach(function(btn){
      btn.addEventListener('click', function(){
        if (start.value) fpStart.setDate(start.value, true);
        if (end.value)   fpEnd.setDate(end.value, true);
      });
    });
  }

  if (window.flatpickr) { initPickers(); return; }

  var link1 = document.createElement('link');
  link1.rel  = 'stylesheet';
  link1.href = 'https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/flatpickr.min.css';
  document.head.appendChild(link1);

  var s = document.createElement('script');
  s.src = 'https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/flatpickr.min.js';
  s.onload = initPickers;
  document.head.appendChild(s);
})();
</script>

<?php include_once('footer.php'); ?>
