<?php
// /edenrms/pages/dashboard.php
declare(strict_types=1);
ini_set('display_errors','1'); error_reporting(E_ALL);
if (session_status() !== PHP_SESSION_ACTIVE) session_start();

/* Make sure symbols render (≤) */
header('Content-Type: text/html; charset=UTF-8');

/* ---------- DB/Auth ---------- */
$auth = __DIR__ . '/../includes/auth.php';
if (!is_file($auth)) { http_response_code(500); exit('includes/auth.php not found'); }
require_once $auth;

$db = ec_db();
if (!$db instanceof mysqli) { http_response_code(500); exit('DB connection error'); }
$db->set_charset('utf8mb4');

/* ---------- helpers ---------- */
function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }

/** 1-value SELECT helper (safe, quiet) */
function qv(mysqli $db, string $sql, array $params = [], string $types = ''): float {
  $st = $db->prepare($sql); if(!$st) return 0.0;
  if ($params) { if ($types==='') $types=str_repeat('s',count($params)); @ $st->bind_param($types, ...$params); }
  if (!@ $st->execute()) { $st->close(); return 0.0; }
  $res = @ $st->get_result(); $v = 0.0;
  if ($res) { $row=$res->fetch_row(); if ($row) $v=(float)$row[0]; }
  else { @ $st->bind_result($x); if (@ $st->fetch()) $v=(float)$x; }
  $st->close(); return $v;
}

/** Row (assoc) helper for 2+ values */
function qrow(mysqli $db, string $sql, array $params = [], string $types = ''): array {
  $st = $db->prepare($sql); if(!$st) return [];
  if ($params) { if ($types==='') $types=str_repeat('s',count($params)); @ $st->bind_param($types, ...$params); }
  if (!@ $st->execute()) { $st->close(); return []; }
  $row = []; if (method_exists($st,'get_result')) { $res = $st->get_result(); if ($res) $row = (array)$res->fetch_assoc(); }
  $st->close(); return $row ?: [];
}

/* Simple column-exists (used for monthly card dynamic SQL) */
function c_exists(mysqli $db, string $t, string $c): bool {
  $t = $db->real_escape_string($t); $c = $db->real_escape_string($c);
  $rs = $db->query("SHOW COLUMNS FROM `$t` LIKE '$c'");
  return $rs && $rs->num_rows>0;
}
function first_col(mysqli $db,string $t,array $cands,string $fallback='NULL'):string{
  foreach($cands as $c) if(c_exists($db,$t,$c)) return "`$t`.`$c`";
  return $fallback;
}

/* ---------- filters ---------- */
$from   = $_GET['from']   ?? date('Y-m-01');
$to     = $_GET['to']     ?? date('Y-m-t');
$branch = isset($_GET['branch']) && $_GET['branch'] !== '' ? (int)$_GET['branch'] : null;

$canSeeFinanceCards = false;

if (function_exists('ec_can_any')) {
    $canSeeFinanceCards = ec_can_any([
        'users.manage',
        'roles.manage',
        'settings.manage'
    ]);
} else {
    $userRole = strtolower((string)($_SESSION['role'] ?? $_SESSION['user_role'] ?? ''));
    $normalizedRole = str_replace([' ', '_'], '', $userRole);
    $canSeeFinanceCards = in_array($normalizedRole, ['admin', 'superadmin'], true);
}

$pendingDues = qv($db, "
  SELECT COALESCE(SUM(x.outstanding_lkr),0)
  FROM (
    SELECT
      sfp.student_id,
      GREATEST(
        (
          COALESCE(sfp.course_fee_lkr,0)
          + COALESCE(sfp.registration_fee_lkr,0)
          + COALESCE(sfp.late_charges,0)
          + COALESCE(sfp.extra_fee_lkr,0)
          - COALESCE(sfp.plan_discount_lkr,0)
          - COALESCE(sfp.manual_discount_lkr,0)
          - COALESCE(sfp.method_discount_lkr,0)
        )
        - COALESCE((
            SELECT SUM(COALESCE(p.amount,0))
            FROM payments p
            WHERE p.student_id = sfp.student_id
              AND (
                p.plan_id = sfp.id
                OR p.course_id = sfp.course_id
              )
          ),0),
        0
      ) AS outstanding_lkr
    FROM student_fee_plans sfp
    JOIN studentss s ON s.id = sfp.student_id
    WHERE LOWER(COALESCE(s.lms_status,'active')) NOT IN ('inactive','suspended')
      AND EXISTS (
        SELECT 1
        FROM payment_schedule ps
        WHERE ps.plan_id = sfp.id
          AND ps.due_date = CURDATE()
      )
  ) x
  WHERE x.outstanding_lkr > 0.009
");

/* ---------- Overdue students count: real outstanding, due before today ---------- */
$overdueStudents = (int) qv($db, "
  SELECT COUNT(DISTINCT x.student_id)
  FROM (
    SELECT
      sfp.student_id,
      GREATEST(
        (
          COALESCE(sfp.course_fee_lkr,0)
          + COALESCE(sfp.registration_fee_lkr,0)
          + COALESCE(sfp.late_charges,0)
          + COALESCE(sfp.extra_fee_lkr,0)
          - COALESCE(sfp.plan_discount_lkr,0)
          - COALESCE(sfp.manual_discount_lkr,0)
          - COALESCE(sfp.method_discount_lkr,0)
        )
        - COALESCE((
            SELECT SUM(COALESCE(p.amount,0))
            FROM payments p
            WHERE p.student_id = sfp.student_id
              AND (
                p.plan_id = sfp.id
                OR p.course_id = sfp.course_id
              )
          ),0),
        0
      ) AS outstanding_lkr
    FROM student_fee_plans sfp
    JOIN studentss s ON s.id = sfp.student_id
    WHERE LOWER(COALESCE(s.lms_status,'active')) NOT IN ('inactive','suspended')
      AND EXISTS (
        SELECT 1
        FROM payment_schedule ps
        WHERE ps.plan_id = sfp.id
          AND ps.due_date < CURDATE()
      )
  ) x
  WHERE x.outstanding_lkr > 0.009
");

/* ---------- Income (Selected Period) ---------- */
$sqlInc = "SELECT IFNULL(SUM(p.amount),0) FROM payments p WHERE DATE(p.date_paid) >= ? AND DATE(p.date_paid) <= ?";
$iParams = [$from,$to]; $iTypes='ss';
if ($branch !== null) {
  $sqlInc .= " AND EXISTS (SELECT 1 FROM enrollments e JOIN batches b ON b.id=e.batch_id
                           WHERE e.student_id=p.student_id AND b.branch_id=?)";
  $iParams[]=$branch; $iTypes.='i';
}
$incomePeriod = qv($db,$sqlInc,$iParams,$iTypes);

/* ---------- Today minis ---------- */
$registrationsToday = (int) qv($db,"SELECT COUNT(*) FROM studentss WHERE DATE(created_at)=CURDATE()");
$paymentsToday      = qv($db,"SELECT IFNULL(SUM(amount),0) FROM payments WHERE DATE(date_paid)=CURDATE()");

/* =========================================================
   Month card — make it MATCH the monthly page (discount-aware).
   Default: include whole month (future + past due).
   Set to false if you only want past-due lines.
   ========================================================= */
$MONTH_CARD_INCLUDE_FUTURE = true;

$y = (int)date('Y', strtotime($to));
$m = (int)date('n', strtotime($to));

/* dynamic cols used in the monthly computation */
$ps_student = first_col($db,'payment_schedule',['student_id','sid','stu_id'],'`payment_schedule`.`student_id`');
$ps_due     = first_col($db,'payment_schedule',['due_date','installment_due','due_on','pay_on'],'`payment_schedule`.`due_date`');
$ps_inst    = first_col($db,'payment_schedule',['installment_no','installment','inst_no','seq'],'`payment_schedule`.`installment_no`');
$ps_fee_a   = first_col($db,'payment_schedule',['course_fee_lkr','course_fee','fee_lkr','fee','amount','amount_lkr'],'0');
$ps_fee_b   = first_col($db,'payment_schedule',['registration_fee_lkr','registration_fee','reg_fee_lkr','reg_fee','admission_fee','admission_fee_lkr'],'0');

$p_student  = first_col($db,'payments',['student_id','sid','stu_id'],'`payments`.`student_id`');
$p_amount   = first_col($db,'payments',['amount','paid_amount','amount_lkr','value'],'`payments`.`amount`');
$p_date     = first_col($db,'payments',['date_paid','payment_date','paid_at','date','created_at'],'`payments`.`date_paid`');
$p_status   = first_col($db,'payments',['status','state'],'NULL');
$status_select = ($p_status==='NULL') ? 'NULL AS p2status' : "$p_status AS p2status";
$status_ok     = ($p_status==='NULL') ? 'TRUE' : "LOWER(COALESCE(p2status,'')) IN ('paid','success','completed') OR p2status IS NULL";

/* discount / payments helpers */
$plansSub = "SELECT sfp.student_id AS pid,
                    SUM(COALESCE(sfp.course_fee_lkr,0)+COALESCE(sfp.registration_fee_lkr,0)) AS nominal_total,
                    SUM(COALESCE(sfp.plan_discount_lkr,0)+COALESCE(sfp.manual_discount_lkr,0)+COALESCE(sfp.method_discount_lkr,0)) AS discount_total
             FROM student_fee_plans sfp GROUP BY sfp.student_id";
$paymentsSub = "SELECT $p_student AS p_student, $p_amount AS p_amount, $p_date AS p_date, $status_select FROM payments";

/* Build inner monthly rows exactly like montly_due.php (per installment) */
$inner = "
  SELECT
    ps.student_id,
    ((COALESCE(ps.fee_a,0)+COALESCE(ps.fee_b,0)) *
      CASE WHEN COALESCE(pl.nominal_total,0) > 0
           THEN (COALESCE(pl.nominal_total,0) - COALESCE(pl.discount_total,0)) / COALESCE(pl.nominal_total,1)
           ELSE 1 END) AS due_lkr,
    COALESCE((
      SELECT SUM(p2.p_amount)
      FROM ( $paymentsSub ) p2
      WHERE p2.p_student = ps.student_id
        AND DATE(p2.p_date) <= DATE(ps.due_date)
        AND ($status_ok)
    ),0) AS paid_upto_due_lkr
  FROM (
    SELECT $ps_student AS student_id, $ps_inst AS installment_no, $ps_due AS due_date, $ps_fee_a AS fee_a, $ps_fee_b AS fee_b
    FROM payment_schedule
    WHERE YEAR($ps_due)=? 
      AND MONTH($ps_due)=?
      AND $ps_student NOT IN (
        SELECT id
        FROM studentss
        WHERE LOWER(COALESCE(lms_status,'active')) IN ('inactive','suspended')
      )
) ps
  LEFT JOIN ( $plansSub ) pl ON pl.pid = ps.student_id
";

/* Branch scope for month card (student-based) */
$branchFilter = '';
$bind = [$y,$m]; $types = 'ii';
if ($branch !== null) {
  $branchFilter = " WHERE EXISTS (
                      SELECT 1
                      FROM enrollments e
                      JOIN batches b ON b.id = e.batch_id
                      WHERE e.student_id = t.student_id AND b.branch_id = ?
                    )";
  $types .= 'i'; $bind[] = $branch;
}

/* full month outstanding = sum over rows where outstanding>0
   by default include future rows of the month; if not, keep only past-due rows */
$SUSPENDED_NOT_IN =
    "AND t.student_id NOT IN
     (
       SELECT id
       FROM studentss
       WHERE LOWER(COALESCE(lms_status,'active')) IN ('inactive','suspended')
     )";
 
$having = $MONTH_CARD_INCLUDE_FUTURE
    ? " WHERE t.outstanding_lkr > 0 $SUSPENDED_NOT_IN "
    : " WHERE t.is_past_due = 1 AND t.outstanding_lkr > 0 $SUSPENDED_NOT_IN ";

$sqlMonthAgg = "
  SELECT
    IFNULL(SUM(t.outstanding_lkr),0) AS amt,
    COUNT(DISTINCT t.student_id)     AS cnt
  FROM (
    SELECT i.student_id,
           GREATEST(i.due_lkr - i.paid_upto_due_lkr, 0) AS outstanding_lkr,
           (DATE_FORMAT((SELECT $ps_due FROM payment_schedule WHERE $ps_student=i.student_id ORDER BY $ps_due DESC LIMIT 1), '%Y-%m') IS NOT NULL) AS dummy,
           CASE WHEN (SELECT 1) THEN (CASE WHEN DATE((SELECT $ps_due FROM payment_schedule WHERE $ps_student=i.student_id ORDER BY $ps_due DESC LIMIT 1)) <= CURDATE() THEN 1 ELSE 0 END) END AS tmp, /* not used, but keeps MySQL happy in some modes */
           CASE WHEN 1=1 THEN (0) END AS z, /* no-op */
           (SELECT 1) AS one, /* no-op */
           (SELECT CASE WHEN DATE(MAX(ps2.due_date)) <= CURDATE() THEN 1 ELSE 0 END
              FROM payment_schedule ps2
             WHERE ps2.student_id = i.student_id
               AND YEAR(ps2.due_date)=? AND MONTH(ps2.due_date)=?) AS is_past_due
    FROM ( $inner ) i
  ) t
  $having
  $branchFilter
";

/* Bind: inner needs (y,m); outer CASE(is_past_due) also needs (y,m) */
$bindAgg = [$y,$m, $y,$m];
$typesAgg = 'iiii';
if ($branch !== null) { $bindAgg[] = $branch; $typesAgg .= 'i'; }

$monthRow = qrow($db, $sqlMonthAgg, $bindAgg, $typesAgg);
$monthOverAmt = (float)($monthRow['amt'] ?? 0);
$monthOverCnt = (int)($monthRow['cnt'] ?? 0);
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Dashboard Overview</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">

  <style>
    :root{
      --bg:#f6f7fb;
      --surface:#ffffff;
      --surface-2:#fbfcff;
      --text:#0f172a;
      --muted:#64748b;
      --border:#e5e7eb;

      --primary:#2563eb;
      --primary-dark:#1d4ed8;
      --danger:#ef4444;
      --success:#16a34a;
      --warning:#f59e0b;
      --purple:#7c3aed;

      --shadow:0 10px 30px rgba(15,23,42,.06);
      --shadow-sm:0 6px 18px rgba(15,23,42,.05);
      --shadow-hover:0 16px 34px rgba(15,23,42,.09);

      --radius:18px;
      --radius-sm:14px;

      --kpi-primary:linear-gradient(135deg, rgba(37,99,235,.08), rgba(37,99,235,.02));
      --kpi-danger:linear-gradient(135deg, rgba(239,68,68,.08), rgba(239,68,68,.02));
      --kpi-success:linear-gradient(135deg, rgba(22,163,74,.08), rgba(22,163,74,.02));
      --kpi-warning:linear-gradient(135deg, rgba(245,158,11,.10), rgba(245,158,11,.02));
      --kpi-purple:linear-gradient(135deg, rgba(124,58,237,.08), rgba(124,58,237,.02));
    }

    body.ec-dashboard-body{
      background:var(--bg);
      min-height:100vh;
      margin:0;
      color:var(--text);
      font-size:.94rem;
      line-height:1.45;
    }

    .ec-main{
      min-height:100vh;
      padding:.55rem 0 1.5rem;
      position:relative;
      z-index:1;
    }

    .ec-main-inner{
      max-width:1480px;
      margin:0 auto;
      padding-inline:.85rem;
    }

    .ec-header-wrap{
      background:linear-gradient(180deg, rgba(255,255,255,.85), rgba(255,255,255,.55));
      border:1px solid rgba(229,231,235,.85);
      border-radius:22px;
      box-shadow:var(--shadow);
      padding:1rem 1.1rem;
      margin-bottom:1rem;
      backdrop-filter:blur(10px);
    }

    .ec-page-title{
      font-size:1.55rem;
      font-weight:900;
      color:var(--text);
      margin-bottom:.18rem;
      letter-spacing:-.02em;
    }

    .ec-page-sub{
      font-size:.9rem;
      color:var(--muted);
      margin-bottom:0;
    }

    .ec-chip{
      display:inline-flex;
      align-items:center;
      gap:.5rem;
      min-height:34px;
      padding:.38rem .82rem;
      border-radius:999px;
      border:1px solid var(--border);
      background:rgba(255,255,255,.92);
      font-size:.78rem;
      color:var(--muted);
      box-shadow:var(--shadow-sm);
      margin-left:.45rem;
      transition:all .18s ease;
      white-space:nowrap;
    }

    .ec-chip:hover{
      transform:translateY(-1px);
      box-shadow:var(--shadow-hover);
      border-color:#dbe3ee;
    }

    .ec-chip i{
      font-size:.95rem;
      color:var(--primary);
    }

    .ec-filter-card{
      background:var(--surface);
      border-radius:var(--radius);
      border:1px solid var(--border);
      box-shadow:var(--shadow);
      color:var(--text);
      overflow:hidden;
    }

    .ec-filter-card .card-body{
      padding:1rem 1.1rem;
    }

    .ec-filter-top{
      display:flex;
      justify-content:space-between;
      align-items:flex-start;
      gap:1rem;
      margin-bottom:.9rem;
      flex-wrap:wrap;
    }

    .ec-filter-title{
      font-size:1rem;
      font-weight:900;
      margin-bottom:.08rem;
      color:var(--text);
      letter-spacing:-.01em;
    }

    .ec-filter-sub{
      font-size:.82rem;
      color:var(--muted);
      margin:0;
    }

    .ec-filter-label{
      font-size:.76rem;
      font-weight:800;
      color:var(--muted);
      margin-bottom:.28rem;
      text-transform:uppercase;
      letter-spacing:.08em;
    }

    .ec-filter-card .form-control,
    .ec-filter-card .form-select{
      background:var(--surface-2);
      border-radius:13px;
      border:1px solid var(--border);
      color:var(--text);
      font-size:.9rem;
      padding:.62rem .78rem;
      transition:border-color .18s ease, box-shadow .18s ease, background .18s ease;
    }

    .ec-filter-card .form-control:focus,
    .ec-filter-card .form-select:focus{
      border-color:rgba(37,99,235,.45);
      box-shadow:0 0 0 .18rem rgba(37,99,235,.12);
      background:#fff;
      color:var(--text);
    }

    .btn-ec-primary{
      border-radius:999px;
      border:1px solid var(--primary);
      background:linear-gradient(135deg,var(--primary),var(--primary-dark));
      color:#fff;
      font-size:.86rem;
      font-weight:700;
      padding:.62rem 1.15rem;
      box-shadow:0 10px 22px rgba(37,99,235,.18);
      transition:all .18s ease;
    }

    .btn-ec-primary:hover{
      background:linear-gradient(135deg,var(--primary-dark),var(--primary-dark));
      border-color:var(--primary-dark);
      color:#fff;
      transform:translateY(-1px);
      box-shadow:0 14px 30px rgba(37,99,235,.26);
    }

    .btn-ec-ghost{
      border-radius:999px;
      border:1px solid var(--border);
      font-size:.85rem;
      font-weight:600;
      padding:.6rem 1.05rem;
      color:var(--text);
      background:#fff;
      box-shadow:var(--shadow-sm);
      transition:all .18s ease;
    }

    .btn-ec-ghost:hover{
      background:#fff;
      border-color:#d1d5db;
      transform:translateY(-1px);
      box-shadow:var(--shadow-hover);
      color:var(--text);
    }

    .ec-kpi-link{
      text-decoration:none;
      color:inherit;
      display:block;
      height:100%;
    }

    .ec-kpi-link:hover{
      color:inherit;
    }

    .ec-kpi-card{
      border:1px solid var(--border);
      border-radius:var(--radius);
      box-shadow:var(--shadow);
      background:var(--surface);
      overflow:hidden;
      height:100%;
      position:relative;
      transition:transform .18s ease, box-shadow .18s ease, border-color .18s ease;
    }

    .ec-kpi-card:hover{
      transform:translateY(-2px);
      box-shadow:var(--shadow-hover);
      border-color:#dbe3ee;
    }

    .ec-kpi-card::before{
      content:"";
      position:absolute;
      inset:0 0 auto 0;
      height:4px;
      background:transparent;
    }

    .ec-kpi-card.primary{ background:var(--kpi-primary); }
    .ec-kpi-card.primary::before{ background:var(--primary); }

    .ec-kpi-card.danger{ background:var(--kpi-danger); }
    .ec-kpi-card.danger::before{ background:var(--danger); }

    .ec-kpi-card.success{ background:var(--kpi-success); }
    .ec-kpi-card.success::before{ background:var(--success); }

    .ec-kpi-card.warning{ background:var(--kpi-warning); }
    .ec-kpi-card.warning::before{ background:var(--warning); }

    .ec-kpi-card.purple{ background:var(--kpi-purple); }
    .ec-kpi-card.purple::before{ background:var(--purple); }

    .ec-kpi-card-body{
      position:relative;
      padding:1rem 1rem .95rem;
    }

    .ec-kpi-label{
      font-size:.69rem;
      text-transform:uppercase;
      letter-spacing:.12em;
      color:var(--muted);
      margin-bottom:.38rem;
      font-weight:800;
    }

    .ec-kpi-value{
      font-size:1.55rem;
      font-weight:900;
      color:var(--text);
      line-height:1.08;
      letter-spacing:-.02em;
    }

    .ec-kpi-sub{
      font-size:.82rem;
      color:var(--muted);
      margin-top:.28rem;
    }

    .ec-kpi-icon{
      width:46px;
      height:46px;
      border-radius:14px;
      display:flex;
      align-items:center;
      justify-content:center;
      font-size:1.18rem;
      flex-shrink:0;
      box-shadow:inset 0 0 0 1px rgba(255,255,255,.35);
    }

    .ec-kpi-card.primary .ec-kpi-icon{
      background:rgba(37,99,235,.12);
      color:var(--primary);
    }

    .ec-kpi-card.danger .ec-kpi-icon{
      background:rgba(239,68,68,.12);
      color:var(--danger);
    }

    .ec-kpi-card.success .ec-kpi-icon{
      background:rgba(22,163,74,.12);
      color:var(--success);
    }

    .ec-kpi-card.warning .ec-kpi-icon{
      background:rgba(245,158,11,.15);
      color:#b45309;
    }

    .ec-kpi-card.purple .ec-kpi-icon{
      background:rgba(124,58,237,.12);
      color:var(--purple);
    }

    .ec-kpi-value-danger{ color:var(--danger); }
    .ec-kpi-value-success{ color:var(--success); }
    .ec-kpi-value-warning{ color:#b45309; }
    .ec-kpi-value-purple{ color:var(--purple); }

    .ec-section-head{
      margin:.35rem 0 .8rem;
    }

    .ec-section-title{
      font-size:1rem;
      font-weight:900;
      color:var(--text);
      margin-bottom:.2rem;
      letter-spacing:-.01em;
    }

    .ec-section-sub{
      font-size:.82rem;
      color:var(--muted);
      margin-bottom:0;
    }

    .ec-today-card{
      background:var(--surface);
      border-radius:var(--radius);
      border:1px solid var(--border);
      box-shadow:var(--shadow);
      color:var(--text);
      height:100%;
      transition:transform .18s ease, box-shadow .18s ease, border-color .18s ease;
      overflow:hidden;
      position:relative;
    }

    .ec-today-card::before{
      content:"";
      position:absolute;
      left:0; top:0; bottom:0;
      width:4px;
      background:#e5e7eb;
      transition:background .18s ease;
    }

    .ec-today-card:hover{
      transform:translateY(-2px);
      box-shadow:var(--shadow-hover);
      border-color:#dbe3ee;
    }

    .ec-today-card:hover::before{
      background:var(--primary);
    }

    .ec-today-card .card-body{
      padding:1rem 1rem .95rem;
    }

    .ec-today-label{
      font-size:.8rem;
      color:var(--muted);
      font-weight:800;
      text-transform:uppercase;
      letter-spacing:.08em;
    }

    .ec-today-value{
      font-size:1.22rem;
      font-weight:900;
      color:var(--text);
      line-height:1.15;
      margin:.22rem 0 .35rem;
    }

    .ec-badge-soft{
      display:inline-flex;
      align-items:center;
      gap:.35rem;
      padding:.24rem .62rem;
      border-radius:999px;
      font-size:.74rem;
      border:1px solid var(--border);
      background:var(--surface-2);
      color:var(--muted);
      line-height:1.2;
    }

    .ec-badge-soft i{
      font-size:.88rem;
      color:var(--primary);
    }

    .text-success-soft{ color:var(--success)!important; }
    .text-danger-soft{ color:var(--danger)!important; }
    .text-warning-soft{ color:#b45309!important; }

    @media (max-width:991.98px){
      .ec-main{
        padding-top:.45rem;
        padding-bottom:1rem;
      }

      .ec-main-inner{
        padding-inline:.7rem;
      }

      .ec-header-wrap{
        padding:.95rem .95rem;
      }
    }

    @media (max-width:767.98px){
      .ec-main-inner{
        padding-inline:.5rem;
      }

      .ec-page-title{
        font-size:1.25rem;
      }

      .ec-page-sub{
        font-size:.84rem;
      }

      .ec-chip{
        margin-left:0;
        margin-right:.35rem;
        margin-top:.35rem;
      }

      .ec-kpi-value{
        font-size:1.28rem;
      }

      .ec-today-value{
        font-size:1.08rem;
      }

      .btn-ec-ghost,
      .btn-ec-primary{
        width:100%;
        justify-content:center;
      }
    }
  </style>

</head>
<body class="ec-dashboard-body">
<?php
$ACTIVE = 'dashboard';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<main class="ec-main">
  <div class="ec-main-inner">
    <div class="container-fluid">

      <!-- Page header -->
      <div class="ec-header-wrap">
        <div class="row align-items-center g-3">
          <div class="col-md-6">
            <div class="ec-page-title">Dashboard Overview</div>
            <p class="ec-page-sub">Quick view of dues, income &amp; today’s activity for Eden Campus.</p>
          </div>
          <div class="col-md-6 text-md-end">
            <span class="ec-chip">
              <i class="bi bi-calendar3"></i>
              Today: <?= date('d M Y') ?>
            </span>
            <span class="ec-chip">
              <i class="bi bi-arrow-left-right"></i>
              Period: <?= esc($from) ?> → <?= esc($to) ?>
            </span>
          </div>
        </div>
      </div>

      <!-- Filters -->
      <div class="card ec-filter-card mb-4">
        <div class="card-body">
          <div class="ec-filter-top">
            <div>
              <div class="ec-filter-title">Filter View</div>
              <div class="ec-filter-sub">Change date range and branch to update income and dues.</div>
            </div>
            <div class="d-none d-md-block">
              <span class="ec-badge-soft">
                <i class="bi bi-info-circle"></i>
                Payments use posted date; dues use schedule due dates
              </span>
            </div>
          </div>

          <form class="row g-3 align-items-end">
            <div class="col-sm-6 col-lg-3">
              <label class="ec-filter-label">From Date</label>
              <input type="date" name="from" value="<?= esc($from) ?>" class="form-control">
            </div>

            <div class="col-sm-6 col-lg-3">
              <label class="ec-filter-label">To Date</label>
              <input type="date" name="to" value="<?= esc($to) ?>" class="form-control">
            </div>

            <div class="col-sm-8 col-lg-3">
              <label class="ec-filter-label">Branch</label>
              <select name="branch" class="form-select">
                <option value="">All Branches</option>
                <?php
                try {
                  $rs = $db->query("SELECT id,COALESCE(name,CONCAT('Branch #',id)) AS name FROM branches ORDER BY name");
                  if ($rs) foreach($rs as $br) {
                    $id=(int)$br['id'];
                    $sel = ($branch === $id) ? 'selected' : '';
                    echo '<option value="'.$id.'" '.$sel.'>'.esc($br['name']).'</option>';
                  }
                } catch (Throwable $e) { /* ignore */ }
                ?>
              </select>
            </div>

            <div class="col-sm-4 col-lg-3 d-flex gap-2">
              <button class="btn btn-ec-primary w-100" type="submit">
                <i class="bi bi-funnel me-1"></i> Apply Filters
              </button>
              <a href="dashboard.php" class="btn btn-ec-ghost">
                <i class="bi bi-arrow-counterclockwise"></i>
              </a>
            </div>
          </form>
        </div>
      </div>

      <!-- KPI Row -->
      <div class="row g-3 mb-4">
<?php if ($canSeeFinanceCards): ?>
        <div class="col-md-6 col-xl-3">
          <a class="ec-kpi-link" href="dues.php?tab=od_lines">
            <div class="ec-kpi-card danger">
              <div class="ec-kpi-card-body">
                <div class="d-flex justify-content-between align-items-start mb-2">
                  <div>
                    <div class="ec-kpi-label">Pending Dues</div>
                    <div class="ec-kpi-value ec-kpi-value-danger">
                      Rs. <?= number_format($pendingDues,0) ?>
                    </div>
                    <div class="ec-kpi-sub">Due ≤ Today · Click for student list</div>
                  </div>
                  <div class="ec-kpi-icon">
                    <i class="bi bi-cash-coin"></i>
                  </div>
                </div>
              </div>
            </div>
          </a>
        </div>
        <?php endif; ?>

<?php if ($canSeeFinanceCards): ?>
<div class="col-md-6 col-xl-3">
  <div class="ec-kpi-card primary">
    <div class="ec-kpi-card-body">
      <div class="d-flex justify-content-between align-items-start mb-2">
        <div>
          <div class="ec-kpi-label">Income (Selected Period)</div>
          <div class="ec-kpi-value">
            Rs. <?= number_format($incomePeriod,0) ?>
          </div>
          <div class="ec-kpi-sub">All posted payments within chosen dates</div>
        </div>
        <div class="ec-kpi-icon">
          <i class="bi bi-graph-up-arrow"></i>
        </div>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>

<?php if ($canSeeFinanceCards): ?>
        <div class="col-md-6 col-xl-3">
          <a class="ec-kpi-link" href="dues.php?tab=pending&mode=range&from=<?= date('Y-m-d') ?>&to=<?= date('Y-m-d') ?>">
            <div class="ec-kpi-card warning">
              <div class="ec-kpi-card-body">
                <div class="d-flex justify-content-between align-items-start mb-2">
                  <div>
                    <div class="ec-kpi-label">Overdue Students</div>
                    <div class="ec-kpi-value ec-kpi-value-warning">
                      <?= number_format($overdueStudents) ?>
                    </div>
                    <div class="ec-kpi-sub">Students with outstanding balance</div>
                  </div>
                  <div class="ec-kpi-icon">
                    <i class="bi bi-people-fill"></i>
                  </div>
                </div>
              </div>
            </div>
          </a>
        </div>
<?php endif; ?>
        <div class="col-md-6 col-xl-3">
          <a class="ec-kpi-link" href="montly_due.php?y=<?= (int)$y ?>&m=<?= (int)$m ?>">
            <div class="ec-kpi-card purple">
              <div class="ec-kpi-card-body">
                <div class="d-flex justify-content-between align-items-start mb-2">
                  <div>
                    <div class="ec-kpi-label">Month Overdue (<?= date('M Y', strtotime("$y-$m-01")) ?>)</div>
                    <div class="ec-kpi-value ec-kpi-value-purple">
                      Rs. <?= number_format($monthOverAmt,0) ?>
                    </div>
                    <div class="ec-kpi-sub"><?= (int)$monthOverCnt ?> students · Full month view</div>
                  </div>
                  <div class="ec-kpi-icon">
                    <i class="bi bi-exclamation-octagon-fill"></i>
                  </div>
                </div>
              </div>
            </div>
          </a>
        </div>

      </div>

      <!-- Today section -->
      <div class="ec-section-head">
        <div class="ec-section-title">Today at a Glance</div>
        <div class="ec-section-sub">Snapshot for <?= date('d M Y') ?> across all branches or selected branch.</div>
      </div>

      <div class="row g-3">
        <div class="col-md-6">
          <div class="card ec-today-card">
            <div class="card-body d-flex justify-content-between align-items-center">
              <div>
                <div class="ec-today-label">Registrations Today</div>
                <div class="ec-today-value">
                  <?= number_format($registrationsToday) ?>
                </div>
                <span class="ec-badge-soft">
                  <i class="bi bi-person-plus-fill"></i>
                  New student profiles created
                </span>
              </div>
              <i class="bi bi-postcard-heart fs-2 text-primary"></i>
            </div>
          </div>
        </div>

        <div class="col-md-6">
          <div class="card ec-today-card">
            <div class="card-body d-flex justify-content-between align-items-center">
              <div>
                <div class="ec-today-label">Payments Today</div>
                <div class="ec-today-value text-success-soft">
                  Rs. <?= number_format($paymentsToday,0) ?>
                </div>
                <span class="ec-badge-soft">
                  <i class="bi bi-receipt"></i>
                  Total receipts posted today
                </span>
              </div>
              <i class="bi bi-wallet2 fs-2 text-success"></i>
            </div>
          </div>
        </div>
      </div>

    </div><!-- /.container-fluid -->
  </div><!-- /.ec-main-inner -->
</main>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
</body>
</html>
