<?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');

/* -------------------------------
   Helpers (date & validation)
--------------------------------*/
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_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 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; } // e.g., 20-Aug-25

/* -------------------------------
   Calendar range inputs
--------------------------------*/
$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'); // show compact grid when filtered or sel=1

/* -------------------------------
   Export calendar (CSV/Excel)
--------------------------------*/
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['export_calendar'])) {
  $exp_start = isset($_POST['range_start']) && is_valid_ymd($_POST['range_start']) ? $_POST['range_start'] : $range_start;
  $exp_end   = isset($_POST['range_end'])   && is_valid_ymd($_POST['range_end'])   ? $_POST['range_end']   : $range_end;

  $exp_start_sql = mysqli_real_escape_string($link, $exp_start);
  $exp_end_sql   = mysqli_real_escape_string($link, $exp_end);

  $rs = $link->query("
    SELECT r_name, unit_no, start_date, end_date
    FROM rent_tenant_unit_view
    WHERE NOT (end_date < '$exp_start_sql' OR start_date > '$exp_end_sql')
    ORDER BY start_date ASC, r_name ASC
  ");

  $filename = "bookings_{$exp_start}_to_{$exp_end}.csv";
  header('Content-Type: text/csv; charset=UTF-8');
  header('Content-Disposition: attachment; filename="'.$filename.'"');
  echo "\xEF\xBB\xBF";
  $out = fopen('php://output', 'w');
  fputcsv($out, ['Tenant','Unit','Start Date','End Date','Days']);
  while ($row = mysqli_fetch_assoc($rs)) {
    $sd = new DateTime($row['start_date']); $ed = new DateTime($row['end_date']);
    $days = max(0, $sd->diff($ed)->days + 1);
    fputcsv($out, [$row['r_name'],$row['unit_no'],$row['start_date'],$row['end_date'],$days]);
  }
  fclose($out);
  exit;
}

/* -------------------------------
   Dashboard counts & totals
--------------------------------*/
$total_units = 0; $total_rent = 0; $total_rentt = 0; $total_payables = 0; $total_maintenance = 0; $total_mc = 0;
$total_tenants = 0; $total_occupied_units = 0;

$current_year = date("Y");

/* Unit count (foreign currency view) */
$result_unit = $link->query("SELECT COUNT(uid) AS total_unit FROM unit_view");
if ($row = mysqli_fetch_array($result_unit)) { $total_units = (int)$row['total_unit']; }

$current_year = (int)date('Y');

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

// --- Current year (uses a range so MySQL can use indexes) ---
$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_foreign_currency_unit_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();
}

// --- All time ---
$result_all = $link->query("
    SELECT COALESCE(SUM(total_rent),0) AS total_all
    FROM rent_tenant_foreign_currency_unit_view
");
if ($result_all && ($row_all = $result_all->fetch_assoc())) {
    $total_rentt = (float)$row_all['total_all'];
}
/* Service fee (current year) & all time */
$result_service  = $link->query("SELECT SUM(amount) AS total_service FROM service_main_account WHERE fiscal_year = $current_year AND rent_id IS NOT NULL AND trans_type = 'debit'");
if ($row = mysqli_fetch_array($result_service)) { $total_service = (float)$row['total_service']; }
$result_service = $link->query("SELECT SUM(amount) AS total_service FROM service_main_account WHERE rent_id IS NOT NULL AND trans_type = 'debit'");
if ($row = mysqli_fetch_array($result_service)) { $total_servicee = (float)$row['total_service']; }

/* Receivables (current year) from foreign currency rent view */
$result_balance = $link->query("
  SELECT SUM(total_rent - amt_paid) AS total_balance
  FROM rent_tenant_foreign_currency_unit_view
  WHERE YEAR(issue_date) = '$current_year'
");
if ($row = mysqli_fetch_array($result_balance)) { $total_payables = (float)$row['total_balance']; }

/* Maintenance (all-time) */
$result_mc = $link->query("SELECT SUM(m_amount) AS total FROM maintenance");
if ($row = mysqli_fetch_array($result_mc)) { $total_mc = (float)$row['total']; }

/* Maintenance (current year) */
$result_mcy = $link->query("SELECT SUM(m_amount) AS total FROM maintenance WHERE xyear = $current_year");
if ($row = mysqli_fetch_array($result_mcy)) { $total_maintenance = (float)$row['total']; }

/* Service fee remaining (computed) */
$service_fee_remaining_year = ($total_service ?? 0) - ($total_maintenance ?? 0);
$service_fee_remaining_all  = ($total_servicee ?? 0) - ($total_mc ?? 0);

/* Tenants count */
$result_tenants = $link->query("SELECT COUNT(tid) AS total_tenants FROM tenants");
if ($row = mysqli_fetch_array($result_tenants)) { $total_tenants = (int)$row['total_tenants']; }

/* Occupied units (foreign currency view) */
$result_occupied = $link->query("SELECT COUNT(uid) AS occupied_count FROM foreign_currency_occupied_unit_view");
if ($row = mysqli_fetch_array($result_occupied)) { $total_occupied_units = (int)$row['occupied_count']; }

/* -------------------------------
   Calendar data (events + grid)
--------------------------------*/
$range_start_sql = mysqli_real_escape_string($link, $range_start);
$range_end_sql   = mysqli_real_escape_string($link,   $range_end);

/* All units (for left column list) */
$units = []; $unitNoIndex = [];
$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)) {
  $uid = (int)$u['uid'];
  $units[$uid] = ['uid'=>$uid, 'b_name'=>$u['b_name'], 'unit_no'=>$u['unit_no']];
  $unitNoIndex[strtolower($u['b_name'].'|'.$u['unit_no'])] = $uid;
}

/* Distinct colors per tenant */
$palette = [
  '#3B82F6','#10B981','#F59E0B','#8B5CF6','#EF4444',
  '#06B6D4','#F97316','#84CC16','#EC4899','#22C55E',
  '#EAB308','#A78BFA','#F43F5E','#14B8A6','#60A5FA',
  '#34D399','#FDBA74','#A3E635','#FB7185','#C084FC',
  '#0EA5E9','#F472B6','#93C5FD','#4ADE80','#FDE047'
];
$tenantColor = []; $paletteIdx = 0;

/* Get bookings overlapping selected range */
$calendar_rs = $link->query("
  SELECT uid, b_name, r_name, unit_no, start_date, end_date
  FROM rent_tenant_unit_view
  WHERE NOT (end_date < '$range_start_sql' OR start_date > '$range_end_sql')
  ORDER BY start_date ASC, r_name ASC
");

$events = [];
$unitBookings = []; // uid => [ {tenant,start,end,color} ... ]
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];

  // For FullCalendar (month view)
  $events[] = [
    'title' => $name.' • '.$bk['unit_no'],
    'start' => $bk['start_date'],
    'end'   => plus_one_day($bk['end_date']),
    'backgroundColor' => $color,
    'borderColor'     => $color,
    'textColor'       => '#fff',
    'extendedProps'   => [
      'tenant'    => $name,
      'unit'      => $bk['unit_no'],
      'enterDate' => $bk['start_date'],
      'exitDate'  => $bk['end_date']
    ]
  ];

  // For custom grid (map by uid when possible; fallback by b_name|unit_no)
  $uid = isset($bk['uid']) && $bk['uid'] !== '' ? (int)$bk['uid'] : null;
  if ($uid === null) {
    $key = strtolower(($bk['b_name'] ?? '').'|'.$bk['unit_no']);
    if (isset($unitNoIndex[$key])) $uid = $unitNoIndex[$key];
  }
  if ($uid !== null) {
    if (!isset($unitBookings[$uid])) $unitBookings[$uid] = [];
    $unitBookings[$uid][] = [
      'tenant' => $name,
      'start'  => $bk['start_date'],
      'end'    => $bk['end_date'],
      'color'  => $color
    ];
  }
}
$events_json = json_encode($events);
$all_dates_in_range = each_day_between($range_start, $range_end);
?>
<!-- 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>

<!-- Main content -->
<section class="content">

  <!-- ===== Calendar (with filters) FIRST ===== -->
  <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;font-weight:800;color:#0f172a;">
              Period: <?= htmlspecialchars(human_range($range_start,$range_end)) ?>
            </div>
          <?php endif; ?>
        </div>
        <div class="box-body">

          <div class="filter-card" style="display:flex; flex-wrap:wrap; align-items:center; gap:12px; background:linear-gradient(135deg,#f8fafc,#eef2ff); border:1px solid #e5e7eb; border-radius:12px; padding:10px 12px; margin-bottom:10px;">
            <form method="get" class="form-inline" style="display:flex; gap:10px; flex-wrap:wrap;">
              <div class="form-group">
                <label for="range_start" style="margin-right:6px; font-weight:700;">From</label>
                <!-- Modern date picker (Flatpickr) -->
                <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" style="margin:0 6px 0 10px; font-weight:700;">To</label>
                <!-- Modern date picker (Flatpickr) -->
                <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="?range_start=<?= urlencode($default_start); ?>&range_end=<?= urlencode($default_end); ?>&sel=0"><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:8px;">
            <div class="col-md-12">
              <?php if ($selected_mode): ?>
                <!-- CUSTOM THIN-LINE GRID: Tenant & Unit on the left, Exit date on the right -->
                <style>
                  .schedule-wrap{ overflow-x:auto; border:1px solid #e5e7eb; 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:300px; max-width:300px; }
                  .schedule-grid .date-col{ min-width:72px; text-align:center; }
                  .schedule-grid .exit-col{ width:170px; text-align:left; }

                  .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; }
                  .occ{ height:26px; border-radius:4px; box-shadow: inset 0 0 0 1px rgba(0,0,0,.06); }
                </style>

                <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(s) • 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_suffix($day).'</th>';
                              }
                            ?>
                            <th class="exit-col sticky-right"></th>
                          </tr>
                        </thead>
                        <tbody>
                          <?php
                          foreach ($units as $uid => $uinfo) {
                            // collect tenants & occupancy just for the selected window
                            $occ = []; // date => color
                            $tenantNames = []; // tenant => color
                            $exitDates = [];   // tenant => latest exit

                            if (isset($unitBookings[$uid])) {
                              foreach ($unitBookings[$uid] as $bk) {
                                $st = max_date($bk['start'], $range_start);
                                $en = min_date($bk['end'],   $range_end);
                                if ($st <= $en) {
                                  foreach (each_day_between($st,$en) as $d) { $occ[$d] = $bk['color']; }
                                  $tenantNames[$bk['tenant']] = $bk['color'];
                                  if (!isset($exitDates[$bk['tenant']]) || strcmp($bk['end'],$exitDates[$bk['tenant']]) < 0) {
                                    $exitDates[$bk['tenant']] = $bk['end'];
                                  }
                                }
                              }
                            }

                            echo '<tr>';
                            // left: tenants + unit
                            echo '<td class="tenant-col sticky-left">';
                            if (!empty($tenantNames)) {
                              foreach ($tenantNames as $n=>$c) {
                                echo '<div><span class="tenant-dot" style="background:'.htmlspecialchars($c).'"></span>'
                                    .htmlspecialchars($n).' • '.htmlspecialchars($uinfo['unit_no']).'</div>';
                              }
                            } else {
                              echo '<em>No tenant in this period</em> • '.htmlspecialchars($uinfo['unit_no']);
                            }
                            echo '</td>';

                            // middle: per-day thin cells
                            foreach ($dates as $d) {
                              if (isset($occ[$d])) {
                                echo '<td class="date-col"><div class="occ" style="background:'.htmlspecialchars($occ[$d]).';"></div></td>';
                              } else {
                                echo '<td class="date-col"></td>';
                              }
                            }

                            // right: exit dates per tenant
                            echo '<td class="exit-col sticky-right">';
                            if (!empty($exitDates)) {
                              foreach ($exitDates as $tn=>$ed) {
                                $c = $tenantNames[$tn] ?? '#475569';
                                echo '<div style="display:flex;align-items:center;gap:6px;margin:4px 0;">'
                                    .'<span class="tenant-dot" style="background:'.htmlspecialchars($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 style="display:flex; flex-wrap:wrap; gap:10px;">
                        <?php foreach ($tenantColor as $tenantName => $colorHex): ?>
                          <span style="display:inline-flex;align-items:center;gap:8px;padding:6px 10px;border-radius:999px;background:#f8fafc;border:1px solid #e5e7eb;">
                            <span style="width:14px;height:14px;border-radius:3px;background:<?= htmlspecialchars($colorHex) ?>"></span>
                            <small><?= htmlspecialchars($tenantName) ?></small>
                          </span>
                        <?php endforeach; ?>
                      </div>
                    <?php } ?>
                  </div>
                </div>
              <?php else: ?>
                <!-- FullCalendar month/week/list (thin lines, NO vacant indicators) -->
                <div id="booking-calendar"></div>
                <?php if (!empty($tenantColor)) { ?>
                  <hr>
                  <div style="display:flex; flex-wrap:wrap; gap:10px;">
                    <?php foreach ($tenantColor as $tenantName => $colorHex): ?>
                      <span style="display:inline-flex;align-items:center;gap:8px;padding:6px 10px;border-radius:999px;background:#f8fafc;border:1px solid #e5e7eb;">
                        <span style="width:14px;height:14px;border-radius:3px;background:<?= htmlspecialchars($colorHex) ?>"></span>
                        <small><?= htmlspecialchars($tenantName) ?></small>
                      </span>
                    <?php endforeach; ?>
                  </div>
                <?php } ?>
              <?php endif; ?>
            </div>
          </div>

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

  <!-- ===== Overview cards ===== -->
  <style>
    .small-box{ border-radius:14px; overflow:hidden; box-shadow:0 4px 16px rgba(0,0,0,.06); 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 .inner h4{ margin:0 0 4px; font-weight:700; letter-spacing:.2px; }
    .small-box .inner p{ margin:0; opacity:.95; font-weight:500; }
    .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; }
    .small-box-footer:hover{ background:rgba(255,255,255,.24); }

    .sb-rent   { background:linear-gradient(135deg,#3B82F6,#60A5FA); color:#fff; }
    .sb-recv   { background:linear-gradient(135deg,#8B5CF6,#A78BFA); color:#10072a; }
    .sb-units  { background:linear-gradient(135deg,#0EA5E9,#38BDF8); color:#062231; }
    .sb-tenants{ background:linear-gradient(135deg,#FB7185,#FDA4AF); color:#3b0a12; }

    /* Added service fee styles */
    .sb-service{ background:linear-gradient(135deg,#7C3AED,#C4B5FD); color:#1c1033; }
    .sb-service-remaining{ background:linear-gradient(135deg,#0891B2,#67E8F9); color:#06262b; }
  </style>

  <div class="row home_dash_box">
    <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> General Overview</h2>
        </div>
        <div class="box-body">
          <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_sym($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>

            <!-- All-time Service Fee -->
            <div class="col-xl-4 col-lg-6 col-md-6 col-xs-6">
              <div class="small-box sb-service">
                <div class="inner">
                  <h4><?= money_sym($total_servicee ?? 0); ?></h4>
                  <p>Service Fee</p>
                </div>
                <div class="icon"><i class="fa fa-wrench"></i></div>
                <a href="<?= WEB_URL; ?>service_fee/servicelist.php" class="small-box-footer"><?= $_data['dashboard_more_info']; ?> <i class="fa fa-arrow-circle-right"></i></a>
              </div>
            </div>

            <!-- All-time Service Fee Remaining -->
            <div class="col-xl-4 col-lg-6 col-md-6 col-xs-6">
              <div class="small-box sb-service-remaining">
                <div class="inner">
                  <h4><?= money_sym($service_fee_remaining_all); ?></h4>
                  <p>Service Fee Remaining</p>
                </div>
                <div class="icon"><i class="fa fa-balance-scale"></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-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 class="col-lg-6">
      <div class="box box-success">
        <div class="box-header with-border">
          <h2>&nbsp;&nbsp;<i class="fa fa-comments"></i> General Overview For <?= date("Y") ?></h2>
        </div>
        <div class="box-body">
          <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_sym($total_rent); ?></h4>
                  <p>Total Rent (<?= date('Y');?>)</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-recv">
                <div class="inner">
                  <h4><?= money_sym($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>

            <!-- Current Year Service Fee -->
            <div class="col-xl-4 col-lg-6 col-md-6 col-xs-6">
              <div class="small-box sb-service">
                <div class="inner">
                  <h4><?= money_sym($total_service ?? 0); ?></h4>
                  <p>Service Fee (<?= date('Y');?>)</p>
                </div>
                <div class="icon"><i class="fa fa-wrench"></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>

            <!-- Current Year Service Fee Remaining -->
            <div class="col-xl-4 col-lg-6 col-md-6 col-xs-6">
              <div class="small-box sb-service-remaining">
                <div class="inner">
                  <h4><?= money_sym($service_fee_remaining_year); ?></h4>
                  <p>Service Fee Remaining (<?= date('Y');?>)</p>
                </div>
                <div class="icon"><i class="fa fa-balance-scale"></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-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>

  <!-- ===== Tenants ending soon & Reminders ===== -->
 

</section>

<!-- FullCalendar (CDN v5) -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar@5.11.3/main.min.css">
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@5.11.3/main.min.js"></script>

<style>
  /* FullCalendar: make grid lines thinner */
  #booking-calendar .fc-theme-standard td, 
  #booking-calendar .fc-theme-standard th { border-color:#e6eaf0; border-width:1px; }
  #booking-calendar .fc .fc-button { border:1px solid #e5e7eb; border-radius:10px; background:#fff; color:#0f172a; font-weight:700; }
  #booking-calendar .fc .fc-toolbar-title { font-weight:800; color:#0f172a; }
  #booking-calendar .fc-event, #booking-calendar .fc-event-title{ white-space: normal; line-height: 1.15; font-size: 12px; padding: 2px 4px; }
</style>

<!-- ===== Modern datepicker (Flatpickr) assets ===== -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/flatpickr.min.css">
<style>
/* Flatpickr (modern look to match UI) */
.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 src="https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/flatpickr.min.js"></script>

<script type="text/javascript">
/* Charts (Chart.js is assumed available in your layout) */
var ctx = document.getElementById('pie-chart');
if (ctx && typeof Chart !== 'undefined') {
  new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: ["Income", "Maintenance"],
      datasets: [{
        data: [<?= max(0, ($total_rent - $total_mc)); ?>, <?= $total_mc ?: 0; ?>],
        backgroundColor: ['rgba(54, 162, 235)','rgba(255, 99, 132)'],
        borderColor: ['rgba(20,20,20,.2)','rgba(20,20,20,.2)'],
        borderWidth:1
      }]
    },
    options: { cutout:'60%', plugins:{ legend:{ position:'bottom' } } }
  });
}

var ctx2 = document.getElementById('bar-graph');
if (ctx2 && typeof Chart !== 'undefined') {
  new Chart(ctx2, {
    type: 'doughnut',
    data: {
      labels: ['Vacant', 'Occupied'],
      datasets: [{
        data: [<?= max(0, $total_units - (int)$total_occupied_units) ?>, <?= (int)$total_occupied_units ?>],
        backgroundColor: ['rgba(0,115,183)','rgba(255,99,132)'],
        borderWidth:1
      }]
    },
    options: { cutout:'60%', plugins:{ legend:{ position:'bottom' } } }
  });
}

/* Quick range buttons: always submit to grid (sel=1) */
(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();
    });
  });
})();

/* FullCalendar month/week/list (used when not filtered) */
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',
    headerToolbar: { left: 'title', center: '', right: 'today prev,next' },
    events: events,
    displayEventEnd: true,
    dateClick: function(info){
      // clicking a day switches to grid for that single day
      var day = info.dateStr;
      window.location = '?range_start='+day+'&range_end='+day+'&sel=1';
    },
    select: function(info){
      // range selection -> grid view for that range
      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';
    },
    eventDidMount: function(info){
      var p = info.event.extendedProps || {};
      var tip = (p.tenant || info.event.title)
              + "\nUnit: "   + (p.unit || "")
              + "\nEnter: "  + (p.enterDate || info.event.startStr)
              + "\nExit: "   + (p.exitDate  || (info.event.endStr || ''));
      info.el.setAttribute('title', tip);
    }
  });
  calendar.render();
});

/* ===== Initialize Flatpickr on the two inputs ===== */
document.addEventListener('DOMContentLoaded', function(){
  if (!window.flatpickr) return;

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

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

  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]);
    }
  }));

  // Apply initial min/max constraints based on current values
  if (start.value) fpEnd.set('minDate', start.value);
  if (end.value)   fpStart.set('maxDate', end.value);
});
</script>

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