<?php
require_once __DIR__ . '/_auth.php';


/* ===========================================
   AJAX SECTION
=========================================== */
if (isset($_GET['ajax']) && $_GET['ajax'] === 'student' && isset($_GET['id'])) {
  header('Content-Type: application/json');
  $sid = (int)$_GET['id'];
  $q = mysqli_query($conn, "
    SELECT 
      s.id, s.full_name, c.name AS course_name,
      c.fee_type, c.course_fee, c.monthly_fee, c.duration_months,
      IFNULL(f.paid_amount,0) AS paid_amount,
      IFNULL(f.discount,0) AS discount,
      IFNULL(f.extra_charges,0) AS extra_charges,
      CASE WHEN c.fee_type='PER_MONTH' THEN (c.monthly_fee * c.duration_months)
           ELSE c.course_fee END AS total_fee
    FROM registrations r
    JOIN students s ON s.id=r.student_id
    JOIN courses c ON c.id=r.course_id
    LEFT JOIN fee_payments f ON f.student_id=s.id AND f.course_id=c.id
    WHERE s.id=$sid
    LIMIT 1
  ");
  echo json_encode(mysqli_fetch_assoc($q) ?: []);
  exit;
}

// Payment History
if (isset($_GET['ajax']) && $_GET['ajax'] === 'history' && isset($_GET['id'])) {
  header('Content-Type: text/html');
  $sid = (int)$_GET['id'];
  $q = mysqli_query($conn, "SELECT paid_date, paid_now, discount, extra_charges, received_by FROM fee_history WHERE student_id=$sid ORDER BY paid_date DESC");
  if (mysqli_num_rows($q) === 0) {
    echo '<p style="color:#64748b;text-align:center;margin:10px 0">No payments yet.</p>';
  } else {
    echo '<table style="width:100%;border-collapse:collapse">';
    echo '<tr><th>Date</th><th>Paid</th><th>Discount</th><th>Extra</th><th>Received By</th></tr>';
    while($r=mysqli_fetch_assoc($q)) {
      echo '<tr>
              <td>'.h($r['paid_date']).'</td>
              <td>'.number_format($r['paid_now']).'</td>
              <td>'.number_format($r['discount']).'</td>
              <td>'.number_format($r['extra_charges']).'</td>
              <td>'.h($r['received_by']).'</td>
            </tr>';
    }
    echo '</table>';
  }
  exit;
}

/* ===========================================
   MAIN LOGIC
=========================================== */
require_once __DIR__ . '/_layout.php';
admin_header('Fee Control');

$msg = $err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $id = (int)($_POST['student_id'] ?? 0);
  $pay_now = (float)($_POST['pay_now'] ?? 0);
  $discount = (float)($_POST['discount'] ?? 0);
  $extra = (float)($_POST['extra_charges'] ?? 0);
  $admin = $_SESSION['admin_name'] ?? 'Admin';

  if ($id > 0) {

    // Prevent empty submission (no values)
    if ($pay_now <= 0 && $discount <= 0 && $extra <= 0) {
      $err = "⚠️ No payment, discount, or extra entered — nothing to update.";
    } else {
      // Ensure record exists
      $chk = mysqli_query($conn, "SELECT * FROM fee_payments WHERE student_id=$id LIMIT 1");
      if (mysqli_num_rows($chk) === 0) {
        $r = mysqli_query($conn, "SELECT course_id FROM registrations WHERE student_id=$id LIMIT 1");
        $rc = mysqli_fetch_assoc($r);
        $cid = (int)$rc['course_id'];
        mysqli_query($conn, "
          INSERT INTO fee_payments (student_id, course_id, total_fee, paid_amount, discount, extra_charges, status)
          SELECT s.id, c.id,
            CASE WHEN c.fee_type='PER_MONTH' THEN (c.monthly_fee * c.duration_months)
                 ELSE c.course_fee END,
            0,0,0,'UNPAID'
          FROM students s
          JOIN courses c ON c.id=$cid
          WHERE s.id=$id
        ");
      }

      // Anti-duplicate safeguard: Check recent same entry within 60 seconds
      $dupe = mysqli_query($conn, "
        SELECT id FROM fee_history 
        WHERE student_id=$id 
          AND paid_now=$pay_now 
          AND discount=$discount 
          AND extra_charges=$extra 
          AND paid_date >= (NOW() - INTERVAL 1 MINUTE)
        LIMIT 1
      ");
      if (mysqli_num_rows($dupe) > 0) {
        $err = "⚠️ Duplicate payment detected (same values recently added).";
      } else {
        // Update payment totals
        mysqli_query($conn, "
          UPDATE fee_payments
          SET paid_amount = paid_amount + $pay_now,
              discount=$discount,
              extra_charges=$extra
          WHERE student_id=$id
        ");

        // Log valid payment
        mysqli_query($conn, "
          INSERT INTO fee_history (student_id, paid_now, discount, extra_charges, received_by, paid_date)
          VALUES ($id, $pay_now, $discount, $extra, '".mysqli_real_escape_string($conn,$admin)."', NOW())
        ");

        // Update balance status
        $chk = mysqli_query($conn, "SELECT total_fee, paid_amount, discount, extra_charges FROM fee_payments WHERE student_id=$id LIMIT 1");
        $row = mysqli_fetch_assoc($chk);
        $balance = $row['total_fee'] - ($row['paid_amount'] + $row['discount'] - $row['extra_charges']);
        $status = $balance <= 0 ? 'PAID' : ($row['paid_amount'] > 0 ? 'PARTIAL' : 'UNPAID');
        mysqli_query($conn, "UPDATE fee_payments SET status='$status' WHERE student_id=$id");
        mysqli_query($conn, "UPDATE registrations SET fee_status='$status' WHERE student_id=$id");

        $msg = '✅ Fee updated successfully.';
      }
    }
  } else $err = 'Please select a student first.';
}

/* ===========================================
   LOAD DATA
=========================================== */
$students = mysqli_query($conn, "
  SELECT s.id, s.full_name, c.name AS course
  FROM registrations r
  JOIN students s ON s.id=r.student_id
  JOIN courses c ON c.id=r.course_id
  ORDER BY s.full_name
");

$unpaid = mysqli_query($conn, "
  SELECT f.*, s.full_name, c.name AS course
  FROM fee_payments f
  JOIN students s ON s.id=f.student_id
  JOIN courses c ON c.id=f.course_id
  WHERE f.status!='PAID'
  ORDER BY f.updated_at DESC
");
?>

<h2 style="color:#2563eb;margin-bottom:10px">💳 Fee Control Panel</h2>
<?php if($msg): ?><div class="card" style="background:#dcfce7;color:#166534"><?=h($msg)?></div><?php endif; ?>
<?php if($err): ?><div class="card" style="background:#fee2e2;color:#991b1b"><?=h($err)?></div><?php endif; ?>

<div class="card mt-3">
  <h3 style="margin:0 0 12px;color:#2563eb">🎓 Receive / Update Student Fee</h3>
  <form method="post" id="feeForm" onsubmit="return validateForm()" style="display:grid;gap:10px;grid-template-columns:repeat(12,1fr)">
    <div class="col-4">
      <label>Student</label>
      <select name="student_id" id="studentSelect" required>
        <option value="">— Select Student —</option>
        <?php while($s=mysqli_fetch_assoc($students)): ?>
          <option value="<?=$s['id']?>"><?=h($s['full_name'])?> (<?=h($s['course'])?>)</option>
        <?php endwhile; ?>
      </select>
    </div>
    <div class="col-2"><label>Total Fee</label><input id="totalFee" readonly></div>
    <div class="col-2"><label>Paid</label><input id="paidFee" readonly></div>
    <div class="col-2"><label>Balance</label><input id="balanceFee" readonly></div>
    <div class="col-2"><label>Pay Now</label><input type="number" name="pay_now" id="payNow" value="0" min="0"></div>
    <div class="col-2"><label>Discount</label><input type="number" name="discount" id="discount" value="0" min="0"></div>
    <div class="col-2"><label>Extra Charges</label><input type="number" name="extra_charges" id="extra" value="0" min="0"></div>
    <div class="col-2" style="display:flex;align-items:flex-end">
      <button class="btn primary" style="width:100%">💾 Save</button>
    </div>
  </form>

  <div id="paymentHistory" class="mt-3" style="border-top:1px solid #e5e7eb;padding-top:10px">
    <h4 style="color:#2563eb;margin-bottom:6px">📜 Payment History</h4>
    <div id="historyData" style="max-height:240px;overflow:auto;border:1px solid #e5e7eb;border-radius:8px;padding:6px"></div>
  </div>
</div>

<div class="card mt-4">
  <h3 style="margin:0 0 10px;color:#dc2626">❗ Unpaid / Partial Students</h3>
  <div style="overflow:auto;border-radius:8px;border:1px solid #e5e7eb;">
    <table style="width:100%;min-width:900px;border-collapse:collapse">
      <thead style="background:#f1f5f9">
        <tr><th>ID</th><th>Student</th><th>Course</th><th>Total Fee</th><th>Paid</th><th>Balance</th><th>Status</th></tr>
      </thead>
      <tbody>
        <?php while($r=mysqli_fetch_assoc($unpaid)):
          $bal=$r['total_fee']-($r['paid_amount']+$r['discount']-$r['extra_charges']);
          $badge=$r['status']==='PARTIAL'
            ? '<span class="badge warn">PARTIAL</span>'
            : '<span class="badge danger">UNPAID</span>';
        ?>
        <tr>
          <td><?=$r['id']?></td>
          <td><?=h($r['full_name'])?></td>
          <td><?=h($r['course'])?></td>
          <td><?=number_format($r['total_fee'])?></td>
          <td><?=number_format($r['paid_amount'])?></td>
          <td style="color:#dc2626;font-weight:600"><?=number_format($bal)?></td>
          <td><?=$badge?></td>
        </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
  </div>
</div>

<script>
// Validate before submit (no 0 entries)
function validateForm(){
  const pay = parseFloat(document.getElementById('payNow').value||0);
  const disc = parseFloat(document.getElementById('discount').value||0);
  const extra = parseFloat(document.getElementById('extra').value||0);
  if(pay<=0 && disc<=0 && extra<=0){
    alert('⚠️ Enter payment, discount, or extra before saving.');
    return false;
  }
  return true;
}

// Load student info + history
document.getElementById('studentSelect').addEventListener('change', async e=>{
  const id = e.target.value;
  if(!id) return;
  const res = await fetch(`fee_control.php?ajax=student&id=${id}`);
  const data = await res.json();
  const total=parseFloat(data.total_fee||0), paid=parseFloat(data.paid_amount||0),
        discount=parseFloat(data.discount||0), extra=parseFloat(data.extra_charges||0);
  const balance = total - (paid + discount - extra);
  document.getElementById('totalFee').value = total.toLocaleString();
  document.getElementById('paidFee').value = paid.toLocaleString();
  document.getElementById('balanceFee').value = balance.toLocaleString();

  const hist = await fetch(`fee_control.php?ajax=history&id=${id}`);
  document.getElementById('historyData').innerHTML = await hist.text();
});
</script>

<?php admin_footer(); ?>
