<?php
/* /edenrms/pages/dues.php */
declare(strict_types=1);

ini_set('display_errors', '1');
error_reporting(E_ALL);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/../includes/auth.php';

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

$tab = $_GET['tab'] ?? 'pending'; // pending | od_lines
if (!in_array($tab, ['pending', 'od_lines'], true)) {
    $tab = 'pending';
}

$export = isset($_GET['export']) && $_GET['export'] === 'csv';

$from = $_GET['from'] ?? date('Y-m-01');
$to   = $_GET['to']   ?? date('Y-m-t');
$mode = (($_GET['mode'] ?? '') === 'all') ? 'all' : 'range';

$m = (isset($_GET['m']) && preg_match('/^\d{4}-\d{2}$/', $_GET['m']))
    ? $_GET['m']
    : '';

$monthLabel = $m ? date('F Y', strtotime($m . '-01')) : '';

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

function table_exists(mysqli $db, string $tbl): bool {
    static $cache = [];
    if (isset($cache[$tbl])) return $cache[$tbl];

    $t = $db->real_escape_string($tbl);
    $rs = $db->query("SHOW TABLES LIKE '{$t}'");
    return $cache[$tbl] = ($rs && $rs->num_rows > 0);
}

function col_exists(mysqli $db, string $tbl, string $col): bool {
    static $cache = [];
    $key = $tbl . '.' . $col;
    if (isset($cache[$key])) return $cache[$key];

    $t = $db->real_escape_string($tbl);
    $c = $db->real_escape_string($col);
    $rs = $db->query("SHOW COLUMNS FROM `{$t}` LIKE '{$c}'");
    return $cache[$key] = ($rs && $rs->num_rows > 0);
}

function stmt_bind_all(mysqli_stmt $st, string $types, array $params): void {
    if ($types === '' || !$params) return;

    $args = [$types];
    foreach ($params as $k => $v) {
        $args[$k + 1] = &$params[$k];
    }
    call_user_func_array([$st, 'bind_param'], $args);
}

function money(float $n): float {
    return round($n, 2);
}

function url_swap(array $pairs): string {
    $q = $_GET;
    foreach ($pairs as $k => $v) {
        if ($v === null) unset($q[$k]);
        else $q[$k] = $v;
    }
    return '?' . http_build_query($q);
}

function student_name_expr(mysqli $db): string {
    if (col_exists($db, 'studentss', 'full_name')) return "s.full_name";
    if (col_exists($db, 'studentss', 'student_name')) return "s.student_name";
    if (col_exists($db, 'studentss', 'name')) return "s.name";
    if (col_exists($db, 'studentss', 'first_name') && col_exists($db, 'studentss', 'last_name')) {
        return "TRIM(CONCAT_WS(' ', s.first_name, s.last_name))";
    }
    return "CONCAT('Student #', s.id)";
}

function student_phone_expr(mysqli $db): string {
    foreach (['mobile', 'phone', 'contact_no', 'tel'] as $c) {
        if (col_exists($db, 'studentss', $c)) return "s.`$c`";
    }
    return "''";
}

function get_batch_name(mysqli $db, int $studentId, int $courseId): string {
    if (!table_exists($db, 'enrollments') || !table_exists($db, 'batches')) {
        return '-';
    }

    $batchNameCol = col_exists($db, 'batches', 'batch_code')
        ? 'batch_code'
        : (col_exists($db, 'batches', 'batch_name') ? 'batch_name' : 'id');

    $hasCourse = col_exists($db, 'batches', 'course_id');

    if ($hasCourse && $courseId > 0) {
        $sql = "
            SELECT b.`$batchNameCol` AS batch_name
            FROM enrollments e
            JOIN batches b ON b.id = e.batch_id
            WHERE e.student_id = ? AND b.course_id = ?
            ORDER BY e.id DESC
            LIMIT 1
        ";
        $st = $db->prepare($sql);
        if (!$st) return '-';
        $st->bind_param('ii', $studentId, $courseId);
    } else {
        $sql = "
            SELECT b.`$batchNameCol` AS batch_name
            FROM enrollments e
            JOIN batches b ON b.id = e.batch_id
            WHERE e.student_id = ?
            ORDER BY e.id DESC
            LIMIT 1
        ";
        $st = $db->prepare($sql);
        if (!$st) return '-';
        $st->bind_param('i', $studentId);
    }

    $st->execute();
    $rs = $st->get_result();
    $row = $rs ? $rs->fetch_assoc() : null;
    $st->close();

    $v = trim((string)($row['batch_name'] ?? ''));
    return $v !== '' ? $v : '-';
}

function load_due_summary_rows(mysqli $db): array {
    if (!table_exists($db, 'studentss') || !table_exists($db, 'student_fee_plans')) {
        return [];
    }

    $nameExpr  = student_name_expr($db);
    $phoneExpr = student_phone_expr($db);

    $extraCol = col_exists($db, 'student_fee_plans', 'extra_fee_lkr')
        ? 'extra_fee_lkr'
        : (col_exists($db, 'student_fee_plans', 'extra_fees_lkr') ? 'extra_fees_lkr' : null);

    $extraExpr = $extraCol ? "COALESCE(sfp.`$extraCol`,0)" : "0";

    $hasPayments = table_exists($db, 'payments');
    $hasSchedule = table_exists($db, 'payment_schedule');

    $paidLkrExpr = "0";
    if ($hasPayments) {
        $payCourse = col_exists($db, 'payments', 'course_id');
        $payPlan   = col_exists($db, 'payments', 'plan_id');

        $parts = [];
        if ($payCourse) $parts[] = "p.course_id = sfp.course_id";
        if ($payPlan)   $parts[] = "p.plan_id = sfp.id";

        $courseMatch = $parts ? '(' . implode(' OR ', $parts) . ')' : '1=1';

        $paidLkrExpr = "
            (
                SELECT COALESCE(SUM(COALESCE(p.amount,0)),0)
                FROM payments p
                WHERE p.student_id = sfp.student_id
                  AND $courseMatch
            )
        ";
    }

    $paidUsdExpr = "0";
    if ($hasPayments && col_exists($db, 'payments', 'usd_amount')) {
        $payCourse = col_exists($db, 'payments', 'course_id');
        $payPlan   = col_exists($db, 'payments', 'plan_id');

        $parts = [];
        if ($payCourse) $parts[] = "p.course_id = sfp.course_id";
        if ($payPlan)   $parts[] = "p.plan_id = sfp.id";

        $courseMatch = $parts ? '(' . implode(' OR ', $parts) . ')' : '1=1';

        $paidUsdExpr = "
            (
                SELECT COALESCE(SUM(COALESCE(p.usd_amount,0)),0)
                FROM payments p
                WHERE p.student_id = sfp.student_id
                  AND $courseMatch
            )
        ";
    }

    $oldestDueExpr = "NULL";
    if ($hasSchedule) {
        $oldestDueExpr = "
            (
                SELECT MIN(ps.due_date)
                FROM payment_schedule ps
                WHERE ps.student_id = sfp.student_id
                  AND ps.plan_id = sfp.id
            )
        ";
    }

    $sql = "
        SELECT
            sfp.id AS plan_row_id,
            sfp.student_id,
            sfp.course_id,
            COALESCE($nameExpr, CONCAT('Student #', s.id)) AS student_name,
            COALESCE($phoneExpr, '') AS student_phone,

            COALESCE(sfp.plan_type,'') AS plan_type,
            COALESCE(sfp.course_fee_lkr,0) AS course_fee_lkr,
            COALESCE(sfp.registration_fee_lkr,0) AS registration_fee_lkr,
            COALESCE(sfp.certificate_fee_usd,0) AS certificate_fee_usd,
            COALESCE(sfp.late_charges,0) AS late_charges,
            $extraExpr AS extra_fee_lkr,

            COALESCE(sfp.plan_discount_lkr,0) AS plan_discount_lkr,
            COALESCE(sfp.manual_discount_lkr,0) AS manual_discount_lkr,
            COALESCE(sfp.method_discount_lkr,0) AS method_discount_lkr,

            $paidLkrExpr AS paid_total_lkr,
            $paidUsdExpr AS paid_total_usd,
            $oldestDueExpr AS oldest_due_date

        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')
        ORDER BY sfp.id DESC
    ";

    $rs = $db->query($sql);
    if (!$rs) return [];

    $rows = [];

    while ($r = $rs->fetch_assoc()) {
        $courseFee = (float)$r['course_fee_lkr'];
        $regFee    = (float)$r['registration_fee_lkr'];
        $late      = (float)$r['late_charges'];
        $extra     = (float)$r['extra_fee_lkr'];

        $discount = (float)$r['plan_discount_lkr']
                  + (float)$r['manual_discount_lkr']
                  + (float)$r['method_discount_lkr'];

        $totalPayableLkr = max(0.0, ($courseFee + $regFee + $late + $extra) - max(0.0, $discount));
        $paidLkr         = (float)$r['paid_total_lkr'];

        $certUsd         = (float)$r['certificate_fee_usd'];
        $paidUsd         = (float)$r['paid_total_usd'];

        $outLkr = max(0.0, $totalPayableLkr - $paidLkr);
        $outUsd = max(0.0, $certUsd - $paidUsd);

        if ($outLkr <= 0.009 && $outUsd <= 0.009) {
            continue;
        }

        $rows[] = [
            'plan_row_id'       => (int)$r['plan_row_id'],
            'student_id'        => (int)$r['student_id'],
            'course_id'         => (int)$r['course_id'],
            'student_name'      => (string)$r['student_name'],
            'student_phone'     => (string)$r['student_phone'],
            'batch_name'        => get_batch_name($db, (int)$r['student_id'], (int)$r['course_id']),
            'plan_type'         => (string)$r['plan_type'],
            'total_payable_lkr' => money($totalPayableLkr),
            'paid_total_lkr'    => money($paidLkr),
            'outstanding_lkr'   => money($outLkr),
            'certificate_fee_usd' => money($certUsd),
            'paid_total_usd'      => money($paidUsd),
            'outstanding_usd'     => money($outUsd),
            'oldest_due_date'     => $r['oldest_due_date'] ?: null,
        ];
    }

    return $rows;
}

function load_installment_rows(mysqli $db, array $summaryRows): array {
    if (!table_exists($db, 'payment_schedule')) {
        return [];
    }

    $byPlan = [];
    foreach ($summaryRows as $r) {
        $byPlan[(int)$r['plan_row_id']] = $r;
    }

    if (!$byPlan) return [];

    $ids = array_keys($byPlan);
    $in  = implode(',', array_fill(0, count($ids), '?'));
    $types = str_repeat('i', count($ids));

    $sql = "
        SELECT
            id,
            plan_id,
            student_id,
            installment_no,
            due_date,
            COALESCE(course_fee_lkr,0) AS course_fee_lkr,
            COALESCE(registration_fee_lkr,0) AS registration_fee_lkr,
            COALESCE(certificate_fee_usd,0) AS certificate_fee_usd
        FROM payment_schedule
        WHERE plan_id IN ($in)
        ORDER BY due_date ASC, installment_no ASC, id ASC
    ";

    $st = $db->prepare($sql);
    if (!$st) return [];
    stmt_bind_all($st, $types, $ids);
    $st->execute();
    $rs = $st->get_result();

    $schedule = [];
    while ($r = $rs->fetch_assoc()) {
        $pid = (int)$r['plan_id'];
        $schedule[$pid][] = $r;
    }
    $st->close();

    $out = [];

    foreach ($byPlan as $pid => $plan) {
        $paidTotal = (float)$plan['paid_total_lkr'];
        $payable   = (float)$plan['total_payable_lkr'];
        $outstandingTotal = (float)$plan['outstanding_lkr'];

        if ($outstandingTotal <= 0.009) continue;

        $lines = $schedule[$pid] ?? [];

        if (!$lines) {
            $out[] = [
    'plan_row_id'       => $pid,
    'student_id'        => $plan['student_id'],
    'student_name'      => $plan['student_name'],
    'student_phone'     => $plan['student_phone'],
    'installment_no'    => $line['installment_no'],
    'due_date'          => $line['due_date'],
    'due_lkr'           => money($due),
    'paid_upto_due_lkr' => money($paidForLine),
    'outstanding_lkr'   => money($lineOut),
];
            continue;
        }

        $scheduleNominalTotal = 0.0;
        foreach ($lines as $line) {
            $scheduleNominalTotal += (float)$line['course_fee_lkr'] + (float)$line['registration_fee_lkr'];
        }

        $scale = ($scheduleNominalTotal > 0.009)
            ? min(1.0, $payable / $scheduleNominalTotal)
            : 1.0;

        $allocatedPaid = 0.0;

        foreach ($lines as $line) {
            $nominal = (float)$line['course_fee_lkr'] + (float)$line['registration_fee_lkr'];
            $due = money($nominal * $scale);

            $available = max(0.0, $paidTotal - $allocatedPaid);
            $paidForLine = min($due, $available);
            $lineOut = max(0.0, $due - $paidForLine);

            $allocatedPaid += $paidForLine;

            if ($lineOut <= 0.009) continue;

            $out[] = [
                'student_id'        => $plan['student_id'],
                'student_name'      => $plan['student_name'],
                'student_phone'     => $plan['student_phone'],
                'installment_no'    => $line['installment_no'],
                'due_date'          => $line['due_date'],
                'due_lkr'           => money($due),
                'paid_upto_due_lkr' => money($paidForLine),
                'outstanding_lkr'   => money($lineOut),
            ];
        }
    }

    return $out;
}

/* ---------- build page rows ---------- */

$summaryRows = load_due_summary_rows($db);
$rows = [];

$allInstallmentRows = load_installment_rows($db, $summaryRows);

if ($tab === 'pending') {
    foreach ($allInstallmentRows as $r) {
        if ($mode !== 'all') {
            $d = $r['due_date'] ?: date('Y-m-d');
            if ($d < $from || $d > $to) {
                continue;
            }
        }

        $rows[] = [
            'student_id'        => $r['student_id'],
            'student_name'      => $r['student_name'],
            'student_phone'     => $r['student_phone'] ?? '',
            'installment_no'    => $r['installment_no'],
            'due_date'          => $r['due_date'],
            'due_lkr'           => $r['due_lkr'],
            'paid_upto_due_lkr' => $r['paid_upto_due_lkr'],
            'outstanding_lkr'   => $r['outstanding_lkr'],
        ];
    }
} else {
    $rows = load_installment_rows($db, $summaryRows);

    if ($m !== '') {
        $rows = array_values(array_filter($rows, function($r) use ($m) {
            return !empty($r['due_date']) && substr((string)$r['due_date'], 0, 7) === $m;
        }));
    } else {
        $rows = array_values(array_filter($rows, function($r) {
            return !empty($r['due_date']) && $r['due_date'] <= date('Y-m-d');
        }));
    }
}

$t_due = $t_paid = $t_out = 0.0;

foreach ($rows as $r) {
    $t_due  += (float)($r['due_lkr'] ?? 0);
    $t_paid += (float)($r['paid_upto_due_lkr'] ?? 0);
    $t_out  += (float)($r['outstanding_lkr'] ?? 0);
}

$t_due  = money($t_due);
$t_paid = money($t_paid);
$t_out  = money($t_out);

if ($export) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="dues_' . $tab . '.csv"');
    $f = fopen('php://output', 'w');

    fputcsv($f, ['Student ID', 'Name', 'Batch/Phone', 'Installment', 'Due Date', 'Due', 'Paid', 'Outstanding']);
    foreach ($rows as $r) {
        fputcsv($f, [
            $r['student_id'],
            $r['student_name'],
            $r['batch_name'] ?? ($r['student_phone'] ?? ''),
            $r['installment_no'],
            $r['due_date'],
            $r['due_lkr'],
            $r['paid_upto_due_lkr'],
            $r['outstanding_lkr'],
        ]);
    }
    exit;
}

$ACTIVE = 'dues';
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Dues & Overdue</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>
    body{background:#f4f7fb;}
    .dues-wrap{padding:24px;}
    .dues-hero{
      background:linear-gradient(135deg,#0f2548 0%,#1d4ed8 58%,#38bdf8 100%);
      color:#fff;border-radius:24px;padding:24px;
      box-shadow:0 18px 45px rgba(15,23,42,.16);
      margin-bottom:18px;
    }
    .dues-title{font-weight:900;margin:0;letter-spacing:-.03em;}
    .dues-sub{opacity:.86;margin:.35rem 0 0;font-size:.9rem;}
    .nav-pills-clean{display:flex;gap:8px;flex-wrap:wrap;}
    .nav-pills-clean a{
      text-decoration:none;border-radius:14px;padding:9px 14px;
      font-weight:800;font-size:.86rem;border:1px solid rgba(255,255,255,.4);
      color:#fff;background:rgba(255,255,255,.12);
    }
    .nav-pills-clean a.active{background:#fff;color:#1d4ed8;border-color:#fff;}
    .filter-card,.summary-card,.table-card{
      border:0;border-radius:22px;background:#fff;
      box-shadow:0 10px 30px rgba(15,23,42,.07);
    }
    .summary-card{padding:18px;}
    .summary-label{
      color:#64748b;font-size:.75rem;font-weight:900;
      text-transform:uppercase;letter-spacing:.07em;
    }
    .summary-value{font-size:1.32rem;font-weight:900;color:#0f172a;margin-top:4px;}
    .summary-icon{
      width:42px;height:42px;border-radius:14px;background:#eff6ff;color:#2563eb;
      display:flex;align-items:center;justify-content:center;font-size:1.12rem;
    }
    .table-card{overflow:hidden;}
    .dues-table{margin-bottom:0;}
    .dues-table thead th{
      background:#f8fafc;color:#334155;font-size:.75rem;
      text-transform:uppercase;letter-spacing:.07em;font-weight:900;
      padding:14px;border-bottom:1px solid #e5e7eb;white-space:nowrap;
    }
    .dues-table tbody td{
      padding:13px 14px;vertical-align:middle;border-color:#edf2f7;font-size:.91rem;
    }
    .dues-table tbody tr:hover{background:#fbfdff;}
    .student-name{font-weight:850;color:#0f172a;line-height:1.15;}
    .student-id{font-size:.78rem;color:#64748b;margin-top:2px;}
    .soft-pill{
      display:inline-block;border-radius:999px;padding:6px 10px;
      background:#eef4ff;color:#1d4ed8;font-weight:800;font-size:.8rem;
      max-width:260px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;
    }
    .inst-badge{
      min-width:34px;display:inline-flex;justify-content:center;
      padding:5px 9px;border-radius:10px;background:#f1f5f9;color:#334155;font-weight:850;
    }
    .amount-due{font-weight:850;color:#0f172a;}
    .amount-paid{font-weight:850;color:#15803d;}
    .amount-out{font-weight:900;color:#dc2626;}
    .empty-state{padding:52px 20px;text-align:center;color:#64748b;}
    .empty-state i{font-size:2.4rem;color:#22c55e;margin-bottom:10px;}
    .btn,.form-control{border-radius:14px;}
    .btn-soft{font-weight:800;padding:9px 14px;}
    @media(max-width:768px){
      .dues-wrap{padding:12px;}
      .dues-hero{border-radius:18px;padding:20px;}
    }
  </style>
</head>
<body>
<?php
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>

<main class="ec-main">
<div class="container-fluid dues-wrap">

  <div class="dues-hero">
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
      <div>
        <h4 class="dues-title">
          <?= $tab === 'pending'
              ? 'Pending Dues'
              : ($m ? 'Per Installment — ' . esc($monthLabel) : 'Per Installment — Due Today') ?>
        </h4>
        <p class="dues-sub">Full paid students are removed automatically. Inactive and Suspended students are excluded.</p>
      </div>

      <div class="d-flex flex-wrap gap-2 align-items-center">
        <div class="nav-pills-clean">
          <a class="<?= $tab === 'pending' ? 'active' : '' ?>"
             href="<?= esc(url_swap(['tab'=>'pending','m'=>null])) ?>">
             Pending Dues
          </a>
          <a class="<?= $tab === 'od_lines' ? 'active' : '' ?>"
             href="<?= esc(url_swap(['tab'=>'od_lines','mode'=>null,'from'=>null,'to'=>null])) ?>">
             Per Installment
          </a>
        </div>

        <a class="btn btn-light btn-sm btn-soft"
           href="?<?= esc(http_build_query(array_merge($_GET, ['export'=>'csv']))) ?>">
          <i class="bi bi-download me-1"></i> Export CSV
        </a>
      </div>
    </div>
  </div>

  <?php if ($tab === 'pending'): ?>
    <form class="card filter-card mb-3">
      <div class="card-body">
        <input type="hidden" name="tab" value="pending">
        <input type="hidden" name="mode" value="range">

        <div class="row g-2 align-items-end">
          <div class="col-md-2 col-sm-4">
            <label class="form-label small fw-bold text-muted">From</label>
            <input type="date" name="from" value="<?= esc($from) ?>" class="form-control">
          </div>

          <div class="col-md-2 col-sm-4">
            <label class="form-label small fw-bold text-muted">To</label>
            <input type="date" name="to" value="<?= esc($to) ?>" class="form-control">
          </div>

          <div class="col-md-auto col-sm-4">
            <button class="btn btn-primary px-4"><i class="bi bi-funnel me-1"></i> Apply</button>
          </div>

          <div class="col-md-auto col-sm-4">
            <a class="btn btn-outline-secondary px-4" href="?tab=pending&mode=range">Clear</a>
          </div>

          <div class="col-md-auto ms-auto">
            <div class="btn-group">
              <a class="btn btn-<?= $mode === 'range' ? 'primary' : 'outline-primary' ?>"
                 href="?tab=pending&mode=range">Range</a>
              <a class="btn btn-<?= $mode === 'all' ? 'primary' : 'outline-primary' ?>"
                 href="?tab=pending&mode=all">All-time</a>
            </div>
          </div>
        </div>
      </div>
    </form>
  <?php else: ?>
    <form method="get" class="card filter-card mb-3">
      <div class="card-body">
        <input type="hidden" name="tab" value="od_lines">

        <div class="row g-2 align-items-end">
          <div class="col-md-3 col-sm-5">
            <label class="form-label small fw-bold text-muted">Month</label>
            <input type="month" name="m" value="<?= esc($m) ?>" class="form-control">
          </div>

          <div class="col-md-auto col-sm-4">
            <button class="btn btn-primary px-4"><i class="bi bi-funnel me-1"></i> Apply</button>
          </div>

          <div class="col-md-auto col-sm-4">
            <a class="btn btn-outline-secondary px-4" href="?tab=od_lines">Clear</a>
          </div>
        </div>
      </div>
    </form>
  <?php endif; ?>

  <div class="row g-3 mb-3">
    <div class="col-md-3 col-sm-6">
      <div class="summary-card">
        <div class="d-flex justify-content-between align-items-center">
          <div>
            <div class="summary-label">Rows</div>
            <div class="summary-value"><?= count($rows) ?></div>
          </div>
          <div class="summary-icon"><i class="bi bi-list-check"></i></div>
        </div>
      </div>
    </div>

    <div class="col-md-3 col-sm-6">
      <div class="summary-card">
        <div class="d-flex justify-content-between align-items-center">
          <div>
            <div class="summary-label">Total Due</div>
            <div class="summary-value"><?= number_format($t_due, 2) ?></div>
          </div>
          <div class="summary-icon"><i class="bi bi-cash-stack"></i></div>
        </div>
      </div>
    </div>

    <div class="col-md-3 col-sm-6">
      <div class="summary-card">
        <div class="d-flex justify-content-between align-items-center">
          <div>
            <div class="summary-label">Paid</div>
            <div class="summary-value"><?= number_format($t_paid, 2) ?></div>
          </div>
          <div class="summary-icon"><i class="bi bi-check2-circle"></i></div>
        </div>
      </div>
    </div>

    <div class="col-md-3 col-sm-6">
      <div class="summary-card">
        <div class="d-flex justify-content-between align-items-center">
          <div>
            <div class="summary-label">Outstanding</div>
            <div class="summary-value"><?= number_format($t_out, 2) ?></div>
          </div>
          <div class="summary-icon"><i class="bi bi-exclamation-circle"></i></div>
        </div>
      </div>
    </div>
  </div>

  <div class="table-card">
    <div class="table-responsive">
      <table class="table dues-table align-middle">
        <thead>
          <tr>
            <?php if ($tab === 'od_lines'): ?><th style="width:60px">#</th><?php endif; ?>
            <th>Student</th>
            <th>Phone</th>
            <th>Inst#</th>
            <th>Due Date</th>
            <th class="text-end">Due</th>
            <th class="text-end">Paid</th>
            <th class="text-end">Outstanding</th>
          </tr>
        </thead>

        <tbody>
        <?php if (!$rows): ?>
          <tr>
            <td colspan="<?= $tab === 'od_lines' ? 8 : 7 ?>">
              <div class="empty-state">
                <i class="bi bi-check-circle-fill d-block"></i>
                <strong>No due records found.</strong>
                <div class="small mt-1">All dues are clear for this view.</div>
              </div>
            </td>
          </tr>
        <?php else: ?>
          <?php $i=1; foreach ($rows as $r): ?>
            <tr>
              <?php if ($tab === 'od_lines'): ?><td><?= $i++ ?></td><?php endif; ?>
              <td>
                <div class="student-name"><?= esc($r['student_name']) ?></div>
                <div class="student-id">#<?= (int)$r['student_id'] ?></div>
              </td>
              <td><?= esc($r['student_phone'] ?? '-') ?></td>
              <td><span class="inst-badge"><?= esc($r['installment_no']) ?></span></td>
              <td><?= esc($r['due_date']) ?></td>
              <td class="text-end amount-due"><?= number_format((float)$r['due_lkr'], 2) ?></td>
              <td class="text-end amount-paid"><?= number_format((float)$r['paid_upto_due_lkr'], 2) ?></td>
              <td class="text-end amount-out"><?= number_format((float)$r['outstanding_lkr'], 2) ?></td>
            </tr>
          <?php endforeach; ?>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

</div>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>