<?php

session_name('mini_admin_session');

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'];
if (!isset($_SESSION['sid']) || strlen($_SESSION['sid']) == 0) {

  header('location:logoutmini.php');

  exit();

}



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

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

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

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

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

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

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

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



$query = "SELECT * FROM payment";



$conditions = [];



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

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

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

  $conditions[] = "DATE(payment_date) BETWEEN '$start_date' AND '$end_date'";

}

if (!empty($class)) {

  $class = mysqli_real_escape_string($con, $class);

  $conditions[] = "class = '$class'";

}

if (!empty($section)) {

  $section = mysqli_real_escape_string($con, $section);

  $conditions[] = "section = '$section'";

}

if (!empty($pay_for)) {

  $pay_for = mysqli_real_escape_string($con, $pay_for);

  $conditions[] = "pay_for = '$pay_for'";

}

if (!empty($session)) {

  $session = mysqli_real_escape_string($con, $session);

  $conditions[] = "session = '$session'";

}

if (!empty($Term)) {

  $Term = mysqli_real_escape_string($con, $Term);

  $conditions[] = "Term = '$Term'";

}

if (!empty($school_type)) {

  $school_type = mysqli_real_escape_string($con, $school_type);

  $conditions[] = "school_type = '$school_type'";

}



if (!empty($conditions)) {

  $query .= " WHERE " . implode(' AND ', $conditions);

}

$query .= " ORDER BY payment_date DESC";



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

if (!$result) {

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

}

?>





<!DOCTYPE html>

<html>

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



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

  <div class="wrapper">

    <!-- Navbar -->

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

    <!-- /.navbar -->



    <!-- Main Sidebar Container -->

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



    <!-- Content Wrapper. Contains page content -->

    <div class="content-wrapper">

      <!-- Content Header (Page header) -->

                                <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="dashboard1.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">

                  </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>



                <!-- Payment Details Modal -->

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

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

                    <div class="modal-content" id="receiptContent">

                      <div class="modal-header bg-primary font-weight-bold">

                        <h5 class="modal-title"><i class="fas fa-wallet"></i> Payment details</h5>

                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">

                          <span aria-hidden="true">&times;</span>

                        </button>

                      </div>

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

                      </div>

                      <div class="modal-footer">

                        <button type="button" class="btn btn-success" onclick="printContent()">

                          <i class="fa fa-download"> Print</i>

                        </button>

                        <button type="button" class="btn btn-danger" data-dismiss="modal">

                          <i class="fa fa-times"> Cancel</i>

                        </button>

                      </div>

                    </div>

                  </div>

                </div>

                <!-- End Modal -->

                <!-- Payment Table -->

                <div class="card-body 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 = 1;

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

                      ?>

                        <tr>

                          <td><?php echo htmlentities($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 htmlentities($row['id']); ?></td>

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

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

                          <td><?php echo htmlentities($row['amount']); ?></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']; ?>" title="click for edit">

                              <i class="fa fa-eye"></i>

                            </button>

                            <!-- <a href="viewpayment1.php?del=<?php echo $row['id']; ?>" onClick="return confirm('Are you sure you want to delete?')" class="btn btn-danger btn-xs">

                              <i class="fa fa-trash"></i>

                            </a> -->

                          </td>

                        </tr>

                      <?php $cnt++;

                      } ?>

                    </tbody>

                  </table>

                </div>

                <!-- /.card-body -->

              </div>

              <!-- /.card -->

            </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>

    // In your Javascript (external .js resource or <script> tag)

    $(document).ready(function() {

      $('#class').select2();



    });

    $(document).ready(function() {

      $('#pay_for').select2();

    });

    $(document).ready(function() {

      $('#session').select2();

    });

    $(document).ready(function() {

      $('#Term').select2();

    });

    $(document).ready(function() {

      $('#arm').select2();

    });

    $(document).ready(function() {

      $('#school_type').select2();

    });

    $(document).ready(function() {

      $('#payment_percentage').select2();

    });

  </script>



  <script type="text/javascript">

    $(document).ready(function() {

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

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

        console.log("Editing ID: " + edit_id); // Debugging

        $.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');

          },

          error: function(xhr, status, error) {

            console.error("AJAX Error: ", error); // Debugging

          }

        });

      });

    });



    function printContent() {

      var modalContent = document.querySelector('.modal-content').innerHTML;

      var originalContent = document.body.innerHTML;

      document.body.innerHTML = modalContent;

      window.print();

      document.body.innerHTML = originalContent;

      window.location.reload();

    }





    function downloadFilteredPDF() {

      var start_date = document.getElementById("start_date").value;

      var end_date = document.getElementById("end_date").value;

      var section = document.getElementById("arm").value;

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

      var pay_for = document.getElementById("pay_for").value;

      var Term = document.getElementById("Term").value;

      var session = document.getElementById("session").value;

      var school_type = document.getElementById("school_type").value;

      // Check if start and end dates are provided

      if (start_date && end_date) {

        var url = "generate_pdf.php?start_date=" + start_date + "&end_date=" + end_date;



        if (section) {

          url += "&section=" + section;

        }

        if (pay_for) {

          url += "&pay_for=" + pay_for;

        }

        if (Term) {

          url += "&Term=" + Term;

        }

        if (session) {

          url += "&session=" + session;

        }

        if (school_type) {

          url += "&school_type=" + school_type;

        }

        if (classs) {

          url += "&class=" + classs;

        }



        // Redirect to generate PDF

        window.location.href = url;

      } else {

        alert("Please select both start and end dates to filter.");

      }

    }





    function fetchArms() {

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

      var armDropdown = document.getElementById("arm");



      // Clear previous options

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



      if (classSelected) {

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

          .then(response => response.json())

          .then(data => {

            data.forEach(arm => {

              let option = document.createElement("option");

              option.value = arm;

              option.textContent = arm;

              armDropdown.appendChild(option);

            });

          })

          .catch(error => console.error("Error fetching arms:", error));

      }

    }

  </script>

  <script>

    function resetForm() {

      setTimeout(() => {

        document.querySelector("form").reset();

      }, 100); // Small delay to ensure reset happens after form submission

    }

  </script>

</body>



</html>