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

    header('location:logoutmini.php');

} 



// Handle deletion of payment record

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

    // Get the ID to delete

    $del_id = $_GET['del'];

    

    // Run the delete query and handle errors

    $deleteQuery = "DELETE FROM payments WHERE id = '$del_id'";

    if (!mysqli_query($con, $deleteQuery)) {

        die("Delete query failed: " . mysqli_error($con));

    } else {

        $_SESSION['delmsg'] = "Payment deleted successfully!";

    }

}



// Get the start and end date from the GET request

$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : '';

$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : '';



// Base query for payments

$query = "SELECT * FROM payments";



// If a date range is provided, update the query

if ($start_date && $end_date) {

    $query .= " WHERE DATE(payment_date) BETWEEN '$start_date' AND '$end_date'";

} else {

    $query .= " ORDER BY payment_date DESC"; // Default to showing all payments ordered by payment date

}



// Execute the query

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

?>



<!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">Web 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">Dashboard</a></li>

                            <li class="breadcrumb-item"><a href="wallet_payment.php" class="text-primary">Wallet Payment</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 Web Payment</h3>

                  <div class="card-tools">

                   

                    <a href="approve.php">

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

                        <span style="color: #fff;"><i class="ion ion-person-add"></i>  New Payment</span>

                      </button>

                    </a>                  

                  </div>

                </div>

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



                <!-- Payment Filter Form -->

<div class="card-body">

    <!-- Date filter form -->

    <form method="GET" action="viewpayment21.php">

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

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

                <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-4">

                <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-4 align-self-end">

                <button type="submit" name="filter" class="btn btn-primary">Filter</button>

                <button type="button" class="btn btn-success" onclick="downloadFilteredPDF()">Download PDF</button>

            </div>

        </div>

    </form>

</div>





                <!-- 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">

                        <h5 class="modal-title">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>Email</th>

                        <th>Reference</th>

                        <th>Payment For </th>

                        <th>Amount</th>

                        <th>Payment Date</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['email']);?></td>

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

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

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

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

        

        // Check if both dates are provided

        if (start_date && end_date) {

            window.location.href = "generate_pdf1.php?start_date=" + start_date + "&end_date=" + end_date;

        } else {

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

        }

    }

  </script>

</body>

</html>



