<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once '../auth/auth.php';
require_once '../models/db_connection.php';

if (isset($_POST['addPayment'])) {
    // Sanitize inputs
    $enID = mysqli_real_escape_string($conn, $_POST['enID']);
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);
    $paymentDate = mysqli_real_escape_string($conn, $_POST['paymentDate']);

    // Find student_id by enrollment id
    $studentQuery = mysqli_query($conn, "SELECT student_id FROM students WHERE en_id = '$enID'");

    if (!$studentQuery) {
        echo "<script>alert('Error fetching student: " . mysqli_error($conn) . "');</script>";
    } else {
        $studentData = mysqli_fetch_assoc($studentQuery);
        if ($studentData) {
            $st_id = $studentData['student_id'];

            // Prepare due_id as NULL (if you don’t use it)
            $due_id = 'NULL';

            // Insert payment
            $sql = "INSERT INTO student_payments (st_id, due_id, amount, payament_date) 
                    VALUES ('$st_id', $due_id, '$amount', '$paymentDate')";

            if (mysqli_query($conn, $sql)) {
                echo "<script>
                        alert('Payment added successfully!');
                        window.location.href = 'view_payments.php';
                      </script>";
            } else {
                echo "<script>
                        alert('Error adding payment: " . mysqli_error($conn) . "');
                      </script>";
            }
        } else {
            echo "<script>alert('No student found with the given enrollment ID');</script>";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Add Student Payment</title>
  <?php include("../templates/header.php"); ?>
</head>

<body>
  <div class="container-scroller">
    <?php include("../templates/nav.php"); ?>
    <div class="container-fluid page-body-wrapper">
      <?php include("../templates/sidenav.php"); ?>
      <div class="main-panel">
        <div class="content-wrapper">
          <div class="col-md-6 grid-margin stretch-card">
            <div class="card">
              <div class="card-body">
                <h4 class="card-title">Add Student Payment</h4>
                <p class="card-description">Add student <code>payment</code> record</p>

                <form action="add_payments.php" method="POST">
                  <div class="form-group">
                    <label>Student (Enrollment ID)</label>
                    <input list="students" id="studentList" class="form-control" name="enID" onchange="getStudentDetails()" required>
                    <datalist id="students">
                      <?php
                      $studentsData = mysqli_query($conn, "SELECT * FROM students WHERE status = 'enrolled'");
                      while ($student = mysqli_fetch_array($studentsData)) {
                        echo '<option value="' . $student['en_id'] . '">' . $student['fullname'] . '</option>';
                      }
                      ?>
                    </datalist>
                  </div>

                  <div class="form-group">
                    <label>Course Price</label>
                    <input type="text" class="form-control" id="coursePrice" readonly>
                  </div>

                  <div class="form-group">
                    <label>Total Paid</label>
                    <input type="text" class="form-control" id="totalPaid" readonly>
                  </div>

                  <div class="form-group">
                    <label>Remaining Balance</label>
                    <input type="text" class="form-control" id="remainingBalance" readonly>
                  </div>

                  <div class="form-group">
                    <label>Amount</label>
                    <input type="number" class="form-control" id="amountField" name="amount" required>
                  </div>

                  <div class="form-group">
                    <label>Date</label>
                    <input type="date" class="form-control" name="paymentDate" required>
                  </div>

                  <div class="col-sm-9">
                    <button type="submit" name="addPayment" class="btn btn-dark btn-lg">Add Payment</button>
                  </div>
                </form>
              </div>
            </div>
          </div>

          <?php include("../templates/footer.php"); ?>
        </div>
      </div>
    </div>
  </div>

  <?php include("../templates/inc_scripts.php"); ?>
  <script>
    function getStudentDetails() {
      var studentID = document.getElementById('studentList').value;
      if (studentID) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'fetch_student_details.php?studentID=' + studentID, true);
        xhr.onload = function() {
          if (this.status == 200) {
            var response = JSON.parse(this.responseText);
            document.getElementById('coursePrice').value = response.coursePrice;
            document.getElementById('totalPaid').value = response.totalPaid;
            document.getElementById('remainingBalance').value = response.remainingBalance;
            document.getElementById('amountField').setAttribute('max', response.remainingBalance);
          }
        };
        xhr.send();
      }
    }
  </script>
</body>

</html>
