<?php
// /admin/fees.php
require_once __DIR__ . '/_auth.php';
require_once __DIR__ . '/_layout.php';

// Create payment (ledger)
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['pay'])) {
  $registration_id = (int)($_POST['registration_id'] ?? 0);
  $amount = (int)($_POST['amount'] ?? 0);
  $method = trim($_POST['method'] ?? '');
  $note   = trim($_POST['note'] ?? '');
  if ($registration_id > 0 && $amount > 0) {
    $st = mysqli_prepare($conn, "INSERT INTO payments(registration_id,amount,method, note, paid_at) VALUES (?,?,?,?,NOW())");
    mysqli_stmt_bind_param($st, "iiss", $registration_id, $amount, $method, $note);
    mysqli_stmt_execute($st);
    mysqli_stmt_close($st);
    header('Location: fees.php?msg='.urlencode('Payment recorded'));
    exit;
  } else {
    header('Location: fees.php?msg='.urlencode('Select a registration and valid amount')); exit;
  }
}

// Filters
$q = trim($_GET['q'] ?? '');

// Core query: registrations + students + courses + sum(payments)
$sql = "
SELECT
  r.id AS reg_id, r.reg_no, r.approved_at, r.fee_status,
  s.full_name,
  c.name AS course_name, c.duration_months,
  c.fee_type, c.course_fee, c.monthly_fee,
  COALESCE(SUM(p.amount),0) AS paid_total
FROM registrations r
JOIN students s ON s.id = r.student_id
JOIN courses  c ON c.id = r.course_id
LEFT JOIN payments p ON p.registration_id = r.id
WHERE 1=1
";

$params = [];
$types  = '';
if ($q !== '') {
  $sql .= " AND (r.reg_no LIKE CONCAT('%',?,'%')
             OR s.full_name LIKE CONCAT('%',?,'%')
             OR c.name LIKE CONCAT('%',?,'%')) ";
  $params[] = $q; $params[] = $q; $params[] = $q;
  $types .= 'sss';
}

$sql .= "
GROUP BY r.id
ORDER BY r.approved_at DESC
LIMIT 300
";

$st = mysqli_prepare($conn, $sql);
if ($types !== '') {
  mysqli_stmt_bind_param($st, $types, ...$params);
}
mysqli_stmt_execute($st);
$res = mysqli_stmt_get_result($st);

admin_header('Fees / Hisab');
$msg = $_GET['msg'] ?? '';
?>
<h2 style="display:flex;align-items:center;gap:10px;margin:0 0 8px">
  Fees / Hisab
  <span style="font-size:12px;font-weight:600;color:#2563eb;background:#dbeafe;border:1px solid #bfdbfe;border-radius:999px;padding:2px 8px">
    Per-course & Per-month supported
  </span>
</h2>

<?php if($msg): ?>
  <div class="card mt-3" style="background:#eff6ff;border-color:#bfdbfe;color:#1e40af"><?= h($msg) ?></div>
<?php endif; ?>

<div class="card mt-3">
  <form method="get" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
    <input name="q" value="<?=h($q)?>" placeholder="Search: Reg No / Student / Course" style="min-width:240px">
    <button class="btn">Search</button>
    <a class="btn" href="fees.php">Reset</a>
  </form>
</div>

<div class="card mt-3">
  <div style="overflow:auto;border-radius:10px;border:1px solid var(--border)">
    <table style="min-width:1000px">
      <thead>
        <tr>
          <th style="background:#f1f5f9">Reg No</th>
          <th style="background:#f1f5f9;text-align:left">Student</th>
          <th style="background:#f1f5f9;text-align:left">Course</th>
          <th style="background:#f1f5f9">Model</th>
          <th style="background:#f1f5f9; text-align:right">Total (PKR)</th>
          <th style="background:#f1f5f9; text-align:right">Paid</th>
          <th style="background:#f1f5f9; text-align:right">Balance</th>
          <th style="background:#f1f5f9">Pay</th>
        </tr>
      </thead>
      <tbody>
        <?php
        $has = false;
        while($row = mysqli_fetch_assoc($res)):
          $has = true;
          $model = $row['fee_type'] === 'PER_MONTH' ? 'Per Month' : 'Per Course';

          if ($row['fee_type'] === 'PER_MONTH') {
            $total = (int)$row['monthly_fee'] * (int)$row['duration_months'];
          } else {
            $total = (int)$row['course_fee'];
          }
          $paid  = (int)$row['paid_total'];
          $bal   = max(0, $total - $paid);

          $badge = $bal>0
            ? '<span style="background:#fee2e2;color:#991b1b;border:1px solid #fecaca;padding:2px 8px;border-radius:999px;font-size:12px;font-weight:700">Due</span>'
            : '<span style="background:#dcfce7;color:#166534;border:1px solid #86efac;padding:2px 8px;border-radius:999px;font-size:12px;font-weight:700">Cleared</span>';
        ?>
        <tr>
          <td style="text-align:center;font-weight:700"><?=h($row['reg_no'])?></td>
          <td class="sname"><?=h($row['full_name'])?></td>
          <td class="cname"><?=h($row['course_name'])?></td>
          <td style="text-align:center"><?= $model ?></td>
          <td style="text-align:right"><?= number_format($total) ?></td>
          <td style="text-align:right"><?= number_format($paid) ?></td>
          <td style="text-align:right; font-weight:700"><?= number_format($bal) ?> <div style="display:inline-block;margin-left:6px"><?= $badge ?></div></td>
          <td style="min-width:260px">
            <form method="post" style="display:flex;gap:6px;align-items:center;flex-wrap:wrap">
              <input type="hidden" name="pay" value="1">
              <input type="hidden" name="registration_id" value="<?=$row['reg_id']?>">
              <input type="number" name="amount" min="1" placeholder="Amount" style="width:110px" required>
              <select name="method" style="width:110px">
                <option>Cash</option><option>Bank</option><option>Online</option>
              </select>
              <input name="note" placeholder="Note" style="width:160px">
              <button class="btn primary">Add</button>
            </form>
          </td>
        </tr>
        <?php endwhile; ?>

        <?php if(!$has): ?>
          <tr><td colspan="8" style="text-align:center;padding:20px;color:#64748b">No registrations found.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
  <div style="display:flex;justify-content:flex-end;font-size:12px;color:#64748b;margin-top:8px">
    Tip: Per-month total = monthly_fee × duration_months (from course).
  </div>
</div>

<?php admin_footer(); ?>
