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

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

  header('location:logout.php');

}



// Handle deletion of payment record

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

  $del_id = $_GET['del'];

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

  }

}





// Fetch the current session

$currentSessionQuery = "SELECT id, session_name 

                        FROM school_sessions 

                        WHERE start_date <= CURDATE() 

                          AND end_date >= CURDATE() 

                        ORDER BY start_date ASC 

                        LIMIT 1";

$currentSessionResult = $con->query($currentSessionQuery);



if ($currentSessionResult && $currentSessionResult->num_rows > 0) {

  $currentSession = $currentSessionResult->fetch_assoc();

  $currentSessionId = $currentSession['id'];

  $currentSessionName = $currentSession['session_name'];

} else {

  $currentSessionId = null;

  $currentSessionName = null;

}



// Fetch the current term

$termQuery = "SELECT id, term_name 

              FROM school_terms 

              WHERE session_id = '$currentSessionId'

                AND start_date <= CURDATE() 

                AND end_date >= CURDATE() 

              ORDER BY start_date ASC 

              LIMIT 1";

$termResult = mysqli_query($con, $termQuery);

$termRow = mysqli_fetch_assoc($termResult);

$currentTermId = $termRow['id'];

$currentTermName = $termRow['term_name'];



// Handle approval request

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['request_approval'])) {

  $regno = $_POST['regno'];

  $fullname = $_POST['fullname'];

  $class = $_POST['class'];

  $term = $_POST['term'] ?? $currentTermName;

  $session = $_POST['session'] ?? $currentSessionName;

  $school_type = $_POST['stream'] ?? 'Day';

  $amount = $_POST['amount'];

  $purpose = $_POST['purpose'];

  $method = $_POST['method'];

  $email = $_POST['email'];

  $class1 = $_POST['class1']; // Honeypot



  $discountUsed = $_POST['discount_used'] ?? 0;

  $discountAmount = $_POST['discount_amount'] ?? 0;

  $discountPercent = $_POST['discount_percent'] ?? 0;



  if (!empty($class1)) {

    flash_alert('Bot/spam detected!', 'viewpayment3.php');
    header('Location: viewpayment3.php');
    exit;

    exit();

  }



  // Save to message table

  $sql = "INSERT INTO message (regno, fullname, class, term, session, school_type, amount, purpose, method, email, discount_used, discount_amount, discount_percent, timestamp) 

            VALUES (:regno, :fullname, :class, :term, :session, :school_type, :amount, :purpose, :method, :email, :discount_used, :discount_amount, :discount_percent, NOW())";

  $stmt = $dbh->prepare($sql);

  $stmt->bindParam(':regno', $regno);

  $stmt->bindParam(':fullname', $fullname);

  $stmt->bindParam(':class', $class);

  $stmt->bindParam(':term', $term);

  $stmt->bindParam(':session', $session);

  $stmt->bindParam(':school_type', $school_type);

  $stmt->bindParam(':amount', $amount);

  $stmt->bindParam(':purpose', $purpose);

  $stmt->bindParam(':method', $method);

  $stmt->bindParam(':email', $email);

  $stmt->bindParam(':discount_used', $discountUsed);

  $stmt->bindParam(':discount_amount', $discountAmount);

  $stmt->bindParam(':discount_percent', $discountPercent);

  $stmt->execute();



  flash_alert('Approval request submitted successfully.', 'viewpayment3.php');
  header('Location: viewpayment3.php');
  exit;

  exit();

}



// Get filter dates

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

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



// Payments query with JOIN to fetch class and school_type

$query = "

SELECT p.*, s.stream 

FROM initiate_payment p

LEFT JOIN students s ON p.student_id = s.id

";



if ($start_date && $end_date) {

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

} else {

  $query .= " ORDER BY p.payment_date DESC";

}



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

?>



<!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">Web Payment Logs</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>



      <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 Initialization Logs</h3>

                  <div class="card-tools">

                    <a href="reconcile_payment.php" class="btn btn-sm btn-primary">

                      <i class="fas fa-sync"></i> Reconcile Payment

                    </a>

                    <a href="viewpayment.php" class="btn btn-sm btn-primary">

                      <i class="fa fa-list"></i> Approved Payment

                    </a>

                  </div>

                </div>



                <div class="card-body">

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

                    <div class="row p-0 m-0">

                      <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"><i class="fas fa-filter"></i>
                          Filter</button>

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

                      </div>

                    </div>

                  </form>

                </div>

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

                        <th>Email</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['class']); ?></td>

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

                          <td>

                            <form method="POST" action="">

                              <input type="hidden" name="regno" value="<?php echo htmlentities($row['studentno']); ?>">

                              <input type="hidden" name="fullname"
                                value="<?php echo htmlentities($row['studentName']); ?>">

                              <input type="hidden" name="email" value="<?php echo htmlentities($row['email']); ?>">

                              <input type="hidden" name="amount" value="<?php echo htmlentities($row['amount']); ?>">

                              <input type="hidden" name="purpose" value="<?php echo htmlentities($row['fee_type']); ?>">

                              <input type="hidden" name="method"
                                value="<?php echo htmlentities($row['payment_method']); ?>">

                              <input type="hidden" name="term" value="<?php echo htmlentities($row['term_id']); ?>">

                              <input type="hidden" name="session" value="<?php echo htmlentities($row['session_id']); ?>">

                              <input type="hidden" name="class" value="<?php echo htmlentities($row['class']); ?>">

                              <input type="hidden" name="stream"
                                value="<?php echo htmlentities(!empty($row['stream']) ? $row['stream'] : 'Day'); ?>">

                              <input type="hidden" name="discount_used"
                                value="<?php echo htmlentities($row['discount_used']); ?>">

                              <input type="hidden" name="discount_amount"
                                value="<?php echo htmlentities($row['discount_amount']); ?>">

                              <input type="hidden" name="discount_percent"
                                value="<?php echo htmlentities($row['discount_percent']); ?>">

                              <input type="text" name="class1" style="display:none;">

                              <button type="submit" name="request_approval" class="btn btn-sm btn-primary"><i
                                  class="fa fa-check-circle"></i> Request Approval</button>

                            </form>

                          </td>

                        </tr>

                        <?php $cnt++;

                      } ?>

                    </tbody>

                  </table>

                </div>

              </div>

            </div>

          </div>

        </div>

      </section>

    </div>



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

  </div>



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



  <script type="text/javascript">

    function downloadFilteredPDF() {

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

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

      if (start_date && end_date) {

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

      } else {

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

      }

    }

  </script>

</body>



</html>