<?php

session_name('super_admin_session');

if (!is_dir(dirname(__DIR__) . '/session_data/super')) {

  mkdir(dirname(__DIR__) . '/session_data/super', 0700, true);

}

session_save_path(dirname(__DIR__) . '/session_data/super');

session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);

session_start();

error_reporting(0);

include('includes/dbconnection.php');

include('includes/flash.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'];

if (!isset($_SESSION['sid']) || strlen($_SESSION['sid']) == 0) {

  header('location:logout.php');

  exit();

}



// Handle delete

if (isset($_GET['del']) && is_numeric($_GET['del'])) {

  $del_id = intval($_GET['del']);

  $del = mysqli_query($con, "DELETE FROM payment WHERE id = '$del_id'");

  if ($del) {

    flash_alert('Payment record deleted successfully.', 'viewpayment.php');

  } else {

    flash_alert('Failed to delete payment record.', 'viewpayment.php');

  }

  header('Location: viewpayment.php');

  exit;

}



// 1. Capture Filters (Checking both POST and GET to maintain pagination state)

$start_date = isset($_REQUEST['start_date']) ? htmlspecialchars(trim($_REQUEST['start_date'])) : '';

$end_date = isset($_REQUEST['end_date']) ? htmlspecialchars(trim($_REQUEST['end_date'])) : '';

$class = isset($_REQUEST['class']) ? htmlspecialchars(trim($_REQUEST['class'])) : '';

$pay_for = isset($_REQUEST['pay_for']) ? htmlspecialchars(trim($_REQUEST['pay_for'])) : '';

$session = isset($_REQUEST['session']) ? htmlspecialchars(trim($_REQUEST['session'])) : '';

$Term = isset($_REQUEST['Term']) ? htmlspecialchars(trim($_REQUEST['Term'])) : '';

$section = isset($_REQUEST['arm']) ? htmlspecialchars(trim($_REQUEST['arm'])) : '';

$school_type = isset($_REQUEST['school_type']) ? htmlspecialchars(trim($_REQUEST['school_type'])) : '';



// 2. Build Query Conditions

$conditions = [];

if (!empty($start_date) && !empty($end_date)) {

  $s_esc = mysqli_real_escape_string($con, $start_date);

  $e_esc = mysqli_real_escape_string($con, $end_date);

  $conditions[] = "DATE(payment_date) BETWEEN '$s_esc' AND '$e_esc'";

}

if (!empty($class))

  $conditions[] = "class = '" . mysqli_real_escape_string($con, $class) . "'";

if (!empty($section))

  $conditions[] = "section = '" . mysqli_real_escape_string($con, $section) . "'";

if (!empty($pay_for))

  $conditions[] = "pay_for = '" . mysqli_real_escape_string($con, $pay_for) . "'";

if (!empty($session))

  $conditions[] = "session = '" . mysqli_real_escape_string($con, $session) . "'";

if (!empty($Term))

  $conditions[] = "Term = '" . mysqli_real_escape_string($con, $Term) . "'";

if (!empty($school_type))

  $conditions[] = "school_type = '" . mysqli_real_escape_string($con, $school_type) . "'";



$where_clause = !empty($conditions) ? " WHERE " . implode(' AND ', $conditions) : "";



// 3. Pagination Logic

$limit = 100;

$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;

if ($page < 1)

  $page = 1;

$offset = ($page - 1) * $limit;



// Get Total Count for Pagination

$count_res = mysqli_query($con, "SELECT COUNT(*) as total FROM payment $where_clause");

$total_rows = mysqli_fetch_assoc($count_res)['total'];

$total_pages = ceil($total_rows / $limit);



// Build Main Data Query

$query = "SELECT * FROM payment $where_clause ORDER BY payment_date DESC LIMIT $limit OFFSET $offset";

$result = mysqli_query($con, $query);



if (!$result) {

  die("Query failed: " . mysqli_error($con));

}



// Helper function to keep filters in pagination links

function getPaginationUrl($p)
{

  $params = $_GET;

  $params['page'] = $p;

  return "viewpayment.php?" . http_build_query($params);

}

?>



<!DOCTYPE html>

<html>

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



<body class="hold-transition sidebar-mini layout-fixed">

  <div class="wrapper">

    <?php @include("includes/header.php"); ?>

    <?php @include("includes/sidebar.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">View 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="dashboard.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>



      <!-- Main content -->

      <section class="content">

        <div class="container-fluid">

          <div class="row">

            <div class="col-12">

              <div class="card card-primary">

                <div class="card-header">

                  <h3 class="card-title"> <i class="fas fa-history"></i> Recent Payment</h3>

                  <div class="card-tools">

                    <a href="viewpayment3.php">

                      <button type="button" class="btn btn-sm btn-primary">

                        <i class="fas fa-naira-sign"></i> Payment Initialization Logs

                      </button>

                    </a>

                    <a href="view_payment_percentage.php">

                      <button type="button" class="btn btn-sm btn-primary">

                        <span style="color: #fff;"><i class="fas fa-money-bill-wave"></i> Balance Report</span>

                      </button>

                    </a>

                    <a href="view_defaulter.php">

                      <button type="button" class="btn btn-sm btn-primary">

                        <span style="color: #fff;"><i class="fas fa-exclamation-triangle"></i> Fee Defaulters

                          List</span>

                      </button>

                    </a> <a href="reconcile_payment.php">

                      <button type="button" class="btn btn-sm btn-primary">

                        <span style="color: #fff;"><i class="fas fa-sync"></i> Reconcile Payment</span>

                      </button>

                    </a>

                    <a href="viewpayment2.php">

                      <button type="button" class="btn btn-sm btn-primary">

                        <span style="color: #fff;"><i class="fa fa-list"></i> Web Payment</span>

                      </button>

                    </a>

                    <a href="view_wallet_payment.php">

                      <button type="button" class="btn btn-sm btn-primary">

                        <span style="color: #fff;"><i class="fas fa-wallet"></i> Wallet Payment</span>

                      </button>

                    </a>

                  </div>

                </div>

                <!-- /.card-header -->



                <!-- Payment Filter Form -->

                <hr>



                <div class="card-body">

                  <!-- Date filter form -->

                  <form method="POST" action="viewpayment.php" onsubmit="resetForm()">

                    <div class="row p-0 m-0"> <!-- Removed padding and margin -->

                      <div class="form-group col-md-3">

                        <label for="start_date">Start Date</label>

                        <input type="date" name="start_date" id="start_date" class="form-control"
                          value="<?php echo $start_date; ?>" required>

                      </div>

                      <div class="form-group col-md-3">

                        <label for="end_date">End Date</label>

                        <input type="date" name="end_date" id="end_date" class="form-control"
                          value="<?php echo $end_date; ?>" required>

                      </div>



                      <div class="form-group col-md-3">

                        <label for="class">Class (Optional)</label>

                        <select name="class" id="class" class="form-control" onchange="fetchArms()">

                          <option value="">Select Class</option>

                          <?php

                          $query2 = "SELECT DISTINCT class FROM class_section ORDER BY class";

                          $result2 = $con->query($query2);

                          while ($row2 = $result2->fetch_assoc()) {

                            echo "<option value='{$row2['class']}'>{$row2['class']}</option>";

                          }

                          ?>

                        </select>

                      </div>

                      <div class="form-group col-md-3">

                        <label for="arm">Arm (Optional)</label>

                        <select name="arm" id="arm" class="form-control">

                          <option value="">Select Arm</option>

                        </select>

                      </div>





                      <div class="form-group col-md-3">

                        <label for="pay_for">Fee Name (Optional)</label>

                        <select name="pay_for" id="pay_for" class="form-control">

                          <option value="">Select Fee Name</option>

                          <?php

                          $query1 = "SELECT DISTINCT name FROM fees ORDER BY id";

                          $result1 = $con->query($query1);

                          while ($row1 = $result1->fetch_assoc()) {

                            echo "<option value='{$row1['name']}'>{$row1['name']}</option>";

                          }

                          ?>



                        </select>

                      </div>

                      <div class="form-group col-md-3">

                        <label for="sex">Session (Optional)</label>

                        <select type="select" class="form-control" id="session" name="session" required>

                          <option value="">Select Session</option>

                          <?php

                          $query3 = "SELECT session_name FROM school_sessions ORDER BY id DESC";

                          $result3 = $con->query($query3);

                          while ($row3 = $result3->fetch_assoc()) {

                            echo "<option value='{$row3['session_name']}'>{$row3['session_name']}</option>";

                          }

                          ?>

                        </select>

                      </div>

                      <div class="form-group col-md-3">

                        <label for="age">Term (Optional)</label>

                        <select type="select" class="form-control" id="Term" name="Term" required>

                          <option value="">Select Term</option>

                          <?php

                          $query4 = "SELECT DISTINCT term_name FROM school_terms ORDER BY term_name ASC";

                          $result4 = $con->query($query4);

                          while ($row4 = $result4->fetch_assoc()) {

                            echo "<option value='{$row4['term_name']}'>{$row4['term_name']}</option>";

                          }

                          ?>

                        </select>





                      </div>

                      <div class="form-group col-md-3">

                        <label for="arm">School Type (Optional)</label>

                        <select name="school_type" id="school_type" class="form-control">

                          <option value="">Select school type</option>

                          <option value="Day">Day Students</option>

                          <option value="Boarding">Boarding Students</option>

                        </select>

                      </div>



                      <div class="form-group col-md-12 text-right mt-3">

                        <button type="submit" class="btn btn-primary">

                          <i class="fas fa-search"></i> Search

                        </button>

                        <button type="button" class="btn btn-success" onclick="downloadFilteredPDF()" name="submit"><i
                            class="fas fa-file-pdf"></i>

                          Download PDF

                        </button>



                      </div>

                    </div>



                  </form>

                </div>

                <hr>



                <div class="card-body table-responsive mt-2">

                  <table id="example1" class="table table-bordered table-hover">

                    <thead>

                      <tr>

                        <th>#</th>

                        <th>Admission No.</th>

                        <th>Student Name</th>

                        <th>Payment ID</th>

                        <th>Receipt No.</th>

                        <th>Class</th>

                        <th>Payment For</th>

                        <th>Amount</th>

                        <th>Payment Date</th>

                        <th>Action</th>

                      </tr>

                    </thead>

                    <tbody>

                      <?php

                      $cnt = $offset + 1;

                      while ($row = mysqli_fetch_array($result)) {

                        ?>

                        <tr>

                          <td><?php echo $cnt; ?></td>

                          <td><?php echo htmlentities($row['studentno']); ?></td>

                          <td><?php echo htmlentities($row['studentName']); ?></td>

                          <td><?php echo htmlentities($row['pay_id']); ?></td>

                          <td>R0000<?php echo $row['id']; ?></td>

                          <td><?php echo htmlentities($row['class']) . " " . htmlentities($row['section']); ?></td>

                          <td><?php echo htmlentities($row['pay_for']); ?></td>

                          <td><?php echo number_format($row['amount'], 2); ?></td>

                          <td><?php echo date("M d,Y H:i A", strtotime($row['payment_date'])); ?></td>

                          <td>

                            <button class="btn btn-primary btn-xs edit_data" id="<?php echo $row['id']; ?>"><i
                                class="fa fa-eye"></i></button>

                            <a href="viewpayment.php?del=<?php echo $row['id']; ?>" class="btn btn-danger btn-xs"
                              onclick="return confirm('Delete?')"><i class="fa fa-trash"></i></a>

                          </td>

                        </tr>

                        <?php $cnt++;

                      } ?>

                    </tbody>

                  </table>

                </div>



                <div class="card-footer clearfix">

                  <ul class="pagination pagination-sm m-0 float-right">

                    <li class="page-item <?php if ($page <= 1)

                      echo 'disabled'; ?>">

                      <a class="page-link" href="<?php echo getPaginationUrl($page - 1); ?>">« Previous</a>

                    </li>

                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>

                      <?php if ($i == 1 || $i == $total_pages || ($i >= $page - 2 && $i <= $page + 2)): ?>

                        <li class="page-item <?php if ($page == $i)

                          echo 'active'; ?>">

                          <a class="page-link" href="<?php echo getPaginationUrl($i); ?>"><?php echo $i; ?></a>

                        </li>

                      <?php endif; ?>

                    <?php endfor; ?>

                    <li class="page-item <?php if ($page >= $total_pages)

                      echo 'disabled'; ?>">

                      <a class="page-link" href="<?php echo getPaginationUrl($page + 1); ?>">Next »</a>

                    </li>

                  </ul>

                  <span class="small text-muted">Showing page <?php echo $page; ?> of <?php echo $total_pages; ?>

                    (Total: <?php echo $total_rows; ?>)</span>

                </div>



              </div>

            </div>

          </div>

        </div>

      </section>

    </div>



    <div id="editData" class="modal fade">

      <div class="modal-dialog modal-xl">

        <div class="modal-content">

          <div class="modal-header bg-primary">

            <h5 class="modal-title">Receipt</h5><button type="button" class="close"
              data-dismiss="modal">&times;</button>

          </div>

          <div class="modal-body" id="info_update"></div>

          <div class="modal-footer"><button type="button" class="btn btn-success"
              onclick="printContent()">Print</button></div>

        </div>

      </div>

    </div>

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

  </div>



  <?php @include("includes/foot.php"); ?>

  <script src="dist/js/select2.min.js"></script>

  <script type="text/javascript">

    $(document).ready(function () {

      $('#class, #pay_for, #session, #Term, #arm, #school_type').select2();



      $(document).on('click', '.edit_data', function () {

        var edit_id = $(this).attr('id');

        $.ajax({

          url: "Receipt.php",

          type: "post",

          data: { edit_id: edit_id },

          success: function (data) {

            $("#info_update").html(data);

            $("#editData").data('ajax-src', 'Receipt.php').modal('show');
            $("#editData").find('form:not([action])').attr('data-ajax-action', 'Receipt.php');

          }

        });

      });

    });



    function printContent() {

      var content = document.getElementById('info_update').innerHTML;

      var win = window.open('', '', 'height=700,width=900');

      win.document.write('<html><body>' + content + '</body></html>');

      win.document.close();

      win.print();

    }



    function fetchArms() {

      var classSelected = document.getElementById("class").value;

      if (classSelected) {

        fetch("fetch_arms.php?class=" + classSelected)

          .then(r => r.json())

          .then(data => {

            let arm = document.getElementById("arm");

            arm.innerHTML = '<option value="">Select Arm</option>';

            data.forEach(a => { arm.innerHTML += `<option value="${a}">${a}</option>`; });

          });

      }

    }

  </script>

</body>



</html>