<?php
session_name('small_admin_session');
if (!is_dir(dirname(__DIR__) . '/session_data/small')) {
  mkdir(dirname(__DIR__) . '/session_data/small', 0700, true);
}
session_save_path(dirname(__DIR__) . '/session_data/small');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();
error_reporting(0);
include('includes/dbconnection.php');
require_once __DIR__ . '/includes/session_term_helper.php';
// Fetch current session and term (with gap/fallback support)
$stResult = resolveCurrentSessionTerm($con);
$currentSessionId   = $stResult['session_id'];
$currentSessionName = $stResult['session_name'];
$currentTermId      = $stResult['term_id'];
$currentTermName    = $stResult['term_name'];

/* 1. ACCESS CONTROL */
if (!isset($_SESSION['sid']) || strlen($_SESSION['sid']) == 0) {
  header('location:logoutsmall.php');
  exit;
}

/* 2. AJAX HANDLER (Must stay at the very top) */
if (isset($_GET['ajax']) && $_GET['ajax'] == 1) {
  $conditions = [];
  $params = [];
  $types = "";

  if (!empty($_GET['studentno'])) {
    $conditions[] = "studentno LIKE ?";
    $params[] = "%" . trim($_GET['studentno']) . "%";
    $types .= "s";
  }
  if (!empty($_GET['studentName'])) {
    $conditions[] = "studentName LIKE ?";
    $params[] = "%" . trim($_GET['studentName']) . "%";
    $types .= "s";
  }
  if (!empty($_GET['class'])) {
    $conditions[] = "class = ?";
    $params[] = $_GET['class'];
    $types .= "s";
  }
  if (!empty($_GET['section'])) {
    $conditions[] = "section = ?";
    $params[] = $_GET['section'];
    $types .= "s";
  }
  if (!empty($_GET['pay_for'])) {
    $conditions[] = "pay_for = ?";
    $params[] = $_GET['pay_for'];
    $types .= "s";
  }
  if (!empty($_GET['session'])) {
    $conditions[] = "session = ?";
    $params[] = $_GET['session'];
    $types .= "s";
  }
  if (!empty($_GET['term'])) {
    $conditions[] = "Term = ?";
    $params[] = $_GET['term'];
    $types .= "s";
  }
  if (!empty($_GET['from'])) {
    $conditions[] = "payment_date >= ?";
    $params[] = $_GET['from'] . " 00:00:00";
    $types .= "s";
  }
  if (!empty($_GET['to'])) {
    $conditions[] = "payment_date <= ?";
    $params[] = $_GET['to'] . " 23:59:59";
    $types .= "s";
  }

  $sql = "SELECT studentno, studentName, class, section, Term, session, payment_type, method, amount, payment_date, status FROM payment";
  if (!empty($conditions)) {
    $sql .= " WHERE " . implode(" AND ", $conditions);
  }
  $sql .= " ORDER BY payment_date DESC LIMIT 50";

  $stmt = $con->prepare($sql);
  if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
  }
  $stmt->execute();
  $result = $stmt->get_result();

  if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
      echo "<tr>
                <td>" . date("d M Y H:i", strtotime($row['payment_date'])) . "</td>
                <td>" . htmlspecialchars($row['studentno']) . "</td>
                <td>" . htmlspecialchars($row['studentName']) . "</td>
                <td>" . htmlspecialchars($row['class'] . ' ' . $row['section']) . "</td>
                <td>" . htmlspecialchars($row['Term']) . "</td>
                <td>" . htmlspecialchars($row['session']) . "</td>
                <td>" . htmlspecialchars($row['method']) . "</td>
                <td><strong>₦" . number_format($row['amount']) . "</strong></td>
                <td><span class='badge badge-success'>" . htmlspecialchars($row['status']) . "</span></td>
              </tr>";
    }
  } else {
    echo "<tr><td colspan='9' class='text-center'>No records found</td></tr>";
  }
  exit; // Stop executing the rest of the HTML
}
?>

<!DOCTYPE html>
<html>
<?php @include("includes/head.php"); ?>

<body class="hold-transition sidebar-mini layout-fixed">
  <div class="wrapper">
    <?php @include("includes/header3.php"); ?>
    <?php @include("includes/sidebar3.php"); ?>

    <div class="content-wrapper">
      <section class="content-header premium-header">
        <div class="container-fluid">
          <div class="header-glass-card">
            <div class="row align-items-center">
              <div class="col-md-8">
                <div class="title-section">
                  <div class="icon-box bg-primary-gradient shadow-sm">
                    <i class="fas fa-wallet"></i>
                  </div>
                  <div>
                    <h1 class="premium-title text-primary">
                      Payment Management
                      <span class="premium-subtitle text-secondary">Manage Payment</span>
                    </h1>
                    <div class="mt-1">
                      <?php if ($currentSessionName): ?>
                        <span class="badge badge-primary mr-1">
                          <i class="fas fa-calendar-alt"></i>
                          <?= htmlspecialchars($currentSessionName) ?>
                        </span>
                      <?php endif; ?>
                      <?php if ($currentTermName): ?>
                        <span class="badge badge-success">
                          <i class="fas fa-bookmark"></i>
                          <?= htmlspecialchars($currentTermName) ?>
                        </span>
                      <?php else: ?>
                        <span class="badge badge-warning">
                          <i class="fas fa-exclamation-triangle"></i> No active term
                        </span>
                      <?php endif; ?>
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-md-4">
                <nav aria-label="breadcrumb">
                  <ol class="breadcrumb premium-breadcrumb">
                    <li class="breadcrumb-item"><a href="oldstdboard.php" class="text-primary">Home</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Payment History</li>
                  </ol>
                </nav>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section class="content">
        <div class="container-fluid">
          <div class="card card-primary">
            <div class="card-header">
              <h3 class="card-title"><i class="fas fa-history"></i> Student Payment History</h3>
            </div>

            <div class="card-body">
              <h6 style="color: brown;"><b>Use one field to filter</b></h6>
              <hr>
              <form id="ajaxSearchForm">
                <div class="row">
                  <div class="form-group col-md-4">
                    <label>Admission No (Optional)</label>
                    <input type="text" name="studentno" class="form-control" placeholder="Search using Admission No.">
                  </div>
                  <div class="form-group col-md-4">
                    <label>Student Name (Optional)</label>
                    <input type="text" name="studentName" class="form-control" placeholder="Search using Student Name">
                  </div>

                  <div class="form-group col-md-4">
                    <label>Class (Optional)</label>
                    <select name="class" id="class" class="form-control" onchange="fetchArms()">
                      <option value="">Select Class</option>
                      <?php
                      $q = $con->query("SELECT DISTINCT class FROM class_section ORDER BY class");
                      while ($r = $q->fetch_assoc()) {
                        echo "<option>{$r['class']}</option>";
                      }
                      ?>
                    </select>
                  </div>

                  <div class="form-group col-md-4">
                    <label>Arm (Optional)</label>
                    <select name="section" id="section" class="form-control">
                      <option value="">Select Arm</option>
                    </select>
                  </div>

                  <div class="form-group col-md-4">
                    <label>Fee Name (Optional)</label>
                    <select name="pay_for" class="form-control" id="pay_for">
                      <option value="">Select Fee</option>
                      <?php
                      $q = $con->query("SELECT DISTINCT name FROM fees");
                      while ($r = $q->fetch_assoc()) {
                        echo "<option>{$r['name']}</option>";
                      }
                      ?>
                    </select>
                  </div>

                  <div class="form-group col-md-4">
                    <label>Session</label>
                    <select name="session" class="form-control" id="session">
                      <option value="">Select Session</option>
                      <?php
                      $q = $con->query("SELECT session_name FROM school_sessions ORDER BY id DESC");
                      while ($r = $q->fetch_assoc()) {
                        echo "<option>{$r['session_name']}</option>";
                      }
                      ?>
                    </select>
                  </div>

                  <div class="form-group col-md-4">
                    <label>Term (Optional)</label>
                    <select name="term" class="form-control" id="term">
                      <option value="">Select Term</option>
                      <?php
                      $q = $con->query("SELECT DISTINCT term_name FROM school_terms");
                      while ($r = $q->fetch_assoc()) {
                        echo "<option>{$r['term_name']}</option>";
                      }
                      ?>
                    </select>
                  </div>

                  <div class="form-group col-md-4">
                    <label>Start Date (Optional)</label>
                    <input type="date" name="from" class="form-control">
                  </div>
                  <div class="form-group col-md-4">
                    <label>End Date (Optional)</label>
                    <input type="date" name="to" class="form-control">
                  </div>

                  <div class="col-md-12 mt-3 text-center">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Search</button>
                  </div>
                </div>
              </form>
            </div>

            <hr>

            <div class="card-body mt-2">
              <div id="loader" style="display:none;" class="text-center mb-2"><i class="fas fa-spinner fa-spin"></i>
                Fetching records...</div>
              <table id="example1" class="table table-bordered table-hover">
                <thead>
                  <tr>
                    <th>Date</th>
                    <th>Admission No</th>
                    <th>Name</th>
                    <th>Class</th>
                    <th>Term</th>
                    <th>Session</th>
                    <th>Method</th>
                    <th>Amount</th>
                    <th>Status</th>
                  </tr>
                </thead>
                <tbody id="resultBody">
                  <tr>
                    <td colspan="9" class="text-center">Use the filters above to search for payments.</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </section>
    </div>

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

  <?php include("includes/foot.php"); ?>
  <script src="dist/js/select2.min.js"></script>

  <script>
    $(document).ready(function () {
      // Initialize Select2
      $('#class, #pay_for, #session, #term, #section').select2();

      // THE AJAX SEARCH INTEGRATION
      $('#ajaxSearchForm').on('submit', function (e) {
        e.preventDefault();

        $('#loader').show();
        $('#resultBody').css('opacity', '0.4');

        // Send data to the same page with ajax=1 flag
        $.ajax({
          url: window.location.href,
          type: 'GET',
          data: $(this).serialize() + "&ajax=1",
          success: function (response) {
            $('#resultBody').html(response);
            $('#loader').hide();
            $('#resultBody').css('opacity', '1');
          },
          error: function () {
            alert("Error loading data.");
            $('#loader').hide();
            $('#resultBody').css('opacity', '1');
          }
        });
      });
    });

    function fetchArms() {
      let cls = document.getElementById("class").value;
      let arm = $("#section"); // Using jQuery for select2 compatibility
      arm.empty().append('<option value="">Select Arm</option>');
      if (cls) {
        fetch("fetch_arms.php?class=" + cls)
          .then(res => res.json())
          .then(data => {
            data.forEach(a => {
              arm.append(`<option value="${a}">${a}</option>`);
            });
          });
      }
    }
  </script>
</body>

</html>