<?php
// Initialize all form variables
$reg = $_POST['reg_number'] ?? '';
$name = $_POST['student_name'] ?? '';
$class = $_POST['student_class'] ?? '';
$term = $_POST['fee_payment_term'] ?? '';
$sessionVal = $_POST['fee_payment_session'] ?? '';
$amount = $_POST['fee_payment_amount'] ?? '';
$teller = $_POST['fee_payment_teller_no'] ?? '';
$cashier = $_POST['cashier'] ?? ''; // NEW

if (isset($_POST['fetch_student'])) {
    // Fetch student info from DB
    $stmt = $connection->prepare("SELECT firstname, othername, lastname, class FROM students WHERE reg_number = ?");
    $stmt->bind_param("s", $reg);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $name = $row['firstname'] . ' ' . $row['othername'] . ' ' . $row['lastname'];
        $class = $row['class'];
        $_SESSION['msg'] = "Student found!";
        $_SESSION['type'] = "success";
    } else {
        $_SESSION['msg'] = "Student not found.";
        $_SESSION['type'] = "danger";
    }
}

if (isset($_POST['save_fee'])) {
    if (empty($reg) || empty($name) || empty($class) || empty($term) || empty($sessionVal) || empty($amount)) {
        $_SESSION['msg'] = "Please fill all required fields.";
        $_SESSION['type'] = "danger";
    } else {
        // 1. Get expected fee
        $stmt = $connection->prepare("SELECT amount FROM fee_structure WHERE class = ? AND term = ? AND session = ?");
        $stmt->bind_param("sss", $class, $term, $sessionVal);
        $stmt->execute();
        $res = $stmt->get_result();

        if ($res->num_rows === 0) {
            $_SESSION['msg'] = "Fee structure not found. Please define it first.";
            $_SESSION['type'] = "danger";
            header("Location: fee_payment");
            exit;
        }

        $expected = (float)$res->fetch_assoc()['amount'];

        // 2. Check for existing payment record
        $stmt = $connection->prepare("SELECT id, amount_paid FROM fee_payment WHERE reg_number = ? AND fee_term = ? AND fee_session = ? AND student_class = ?");
        $stmt->bind_param("ssss", $reg, $term, $sessionVal, $class);
        $stmt->execute();
        $res = $stmt->get_result();

        $existing = $res->fetch_assoc();
        $existing_id = $existing['id'] ?? null;
        $paid_so_far = (float)($existing['amount_paid'] ?? 0);

        $new_total = $paid_so_far + $amount;

        if ($new_total > $expected) {
            $_SESSION['msg'] = "Payment exceeds required fee (₦" . number_format($expected, 2) . "). You have already paid ₦" . number_format($paid_so_far, 2) . ".";
            $_SESSION['type'] = "danger";
            header("Location: fee_payment");
            exit;
        }

        $balance = $expected - $new_total;
        $status = ($balance <= 0) ? "Cleared" : "Owing";
        $date_today = date('Y-m-d');

        if ($existing_id) {
            // 3a. Update existing payment record
            $stmt = $connection->prepare("
                UPDATE fee_payment 
                SET amount_paid = ?, student_balance = ?, teller_no = ?, payment_status = ?, date_of_upload = ?, created_by = ?
                WHERE id = ?
            ");
            $stmt->bind_param("dsssssi", $new_total, $balance, $teller, $status, $date_today, $cashier, $existing_id);
        } else {
            // 3b. Insert new record
            $stmt = $connection->prepare("
                INSERT INTO fee_payment 
                (reg_number, student_name, student_class, fee_term, fee_session, amount_paid, student_balance, teller_no, payment_status, date_of_upload, created_by) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->bind_param("ssssssdsssss", $reg, $name, $class, $term, $sessionVal, $amount, $balance, $teller, $status, $date_today, $cashier);
        }

        if ($stmt->execute()) {
            $_SESSION['msg'] = "₦" . number_format($amount, 2) . " recorded for $name. <br /> Balance: ₦" . number_format($balance, 2);
            $_SESSION['type'] = "success";
            header("Location: fee_payment");
            exit;
        } else {
            $_SESSION['msg'] = "Error: " . $stmt->error;
            $_SESSION['type'] = "danger";
        }
    }
}
?>
<div class="page-title">
  <div>
    <h1><i class="fa fa-laptop"></i> Fee Management</h1>
    <p>Record Student Fees</p>
  </div>
</div>

<div class="card">
  <div class="panel panel-primary">
    <div class="panel-heading">
      <h4 class="text-center">Record Student Fees</h4>
    </div>
    <div class="panel-body">
      <form method="POST" action="">
        <div class="row">
          <!-- Cashier -->
          <div class="col-md-4">
            <div class="input-group">
              <span class="input-group-addon">Cashier</span>
              <input type="text" name="cashier" class="form-control" value="<?php echo htmlspecialchars($staff_username ?? ''); ?>" readonly>
            </div>
          </div>
        </div>

        <br>

        <div class="row">
          <!-- Reg No -->
          <div class="col-md-4">
            <div class="input-group">
              <span class="input-group-addon">Reg No</span>
              <input type="text" name="reg_number" class="form-control" value="<?php echo htmlspecialchars($reg); ?>" required>
            </div>
          </div>

          <!-- Fetch Student -->
          <div class="col-md-2">
            <button type="submit" name="fetch_student" class="btn btn-info">Fetch Student</button>
          </div>

          <!-- Name -->
          <div class="col-md-6">
            <div class="input-group">
              <span class="input-group-addon">Name</span>
              <input type="text" name="student_name" class="form-control" value="<?php echo htmlspecialchars($name); ?>" readonly>
            </div>
          </div>
        </div>

        <br>

        <div class="row">
          <!-- Class -->
          <div class="col-md-4">
            <div class="input-group">
              <span class="input-group-addon">Class</span>
              <input type="text" name="student_class" class="form-control" value="<?php echo htmlspecialchars($class); ?>" readonly>
            </div>
          </div>

          <!-- Term -->
          <div class="col-md-4">
            <div class="input-group">
              <span class="input-group-addon">Term</span>
              <select name="fee_payment_term" class="form-control" required>
                <option disabled selected>Select</option>
                <?php
                $terms = ["First Term", "Second Term", "Third Term"];
                foreach ($terms as $opt) {
                    $sel = ($term == $opt) ? "selected" : "";
                    echo "<option $sel>$opt</option>";
                }
                ?>
              </select>
            </div>
          </div>
        </div>

        <br>

        <div class="row">
          <!-- Session -->
          <div class="col-md-4">
            <div class="input-group">
              <span class="input-group-addon">Session</span>
              <select name="fee_payment_session" class="form-control" required>
                <option disabled selected>Select</option>
                <?php
                $sessions = mysqli_query($connection, "SELECT sessions FROM sessions");
                while ($r = mysqli_fetch_assoc($sessions)) {
                    $sel = ($sessionVal == $r['sessions']) ? "selected" : "";
                    echo "<option $sel>{$r['sessions']}</option>";
                }
                ?>
              </select>
            </div>
          </div>

          <!-- Amount -->
          <div class="col-md-4">
            <div class="input-group">
              <span class="input-group-addon">Amount Paid</span>
              <input type="number" step="0.01" name="fee_payment_amount" class="form-control" value="<?php echo htmlspecialchars($amount); ?>" >
            </div>
          </div>

          <!-- Teller -->
          <div class="col-md-4">
            <div class="input-group">
              <span class="input-group-addon">Teller No</span>
              <input type="text" name="fee_payment_teller_no" class="form-control" value="<?php echo htmlspecialchars($teller); ?>">
            </div>
          </div>
        </div>

        <br>

        <div class="text-center">
          <button type="submit" name="save_fee" class="btn btn-success">Save Fee Payment</button>
        </div>
      </form>
    </div>

    <?php if (!empty($reg)): ?>
      <hr>
      <h4 class="text-center">Fee Payment Records for <strong><?= htmlspecialchars($name) ?></strong></h4>
      <?php
      $stmt = $connection->prepare("SELECT * FROM fee_payment WHERE reg_number = ? ORDER BY id DESC");
      $stmt->bind_param("s", $reg);
      $stmt->execute();
      $result = $stmt->get_result();

      if ($result->num_rows > 0): ?>
        <div class="table-responsive">
          <table class="table table-striped">
            <thead class="bg-primary text-white">
              <tr>
                <th>#</th>
                <th>Reg No</th>
                <th>Name</th>
                <th>Class</th>
                <th>Term</th>
                <th>Session</th>
                <th>Amount Paid</th>
                <th>Balance</th>
                <th>Teller No</th>
                <th>Cashier</th>
                <th>Date</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              <?php $sn = 1;
              while ($row = $result->fetch_assoc()): ?>
                <tr>
                  <td><?= $sn++ ?></td>
                  <td><?= htmlspecialchars($row['reg_number']) ?></td>
                  <td><?= htmlspecialchars($row['student_name']) ?></td>
                  <td><?= htmlspecialchars($row['student_class']) ?></td>
                  <td><?= htmlspecialchars($row['fee_term']) ?></td>
                  <td><?= htmlspecialchars($row['fee_session']) ?></td>
                  <td class="text-success"><b>₦<?= number_format($row['amount_paid'], 2) ?></b></td>
                  <td class="text-danger"><b>₦<?= number_format($row['student_balance'], 2) ?></b></td>
                  <td><?= htmlspecialchars($row['teller_no']) ?></td>
                  <td><?= htmlspecialchars($row['created_by'] ?? '') ?></td>
                  <td><?= date("d-M-Y", strtotime($row['date_of_upload'] ?? $row['created_at'] ?? "now")) ?></td>
                  <td>
                    <?php if ($row['payment_status'] === "Cleared"): ?>
                      <span class="text-success"><strong><?= $row['payment_status'] ?></strong> <i class="glyphicon glyphicon-ok"></i></span>
                    <?php else: ?>
                      <span class="text-danger"><strong><?= $row['payment_status'] ?></strong> <i class="glyphicon glyphicon-remove"></i></span>
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endwhile; ?>
            </tbody>
          </table>
        </div>
      <?php else: ?>
        <p class="text-danger">No payment records found for this student.</p>
      <?php endif; ?>
    <?php endif; ?>
  </div>
</div>
