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


// Ensure session contains payment details
if (!isset($_SESSION['payment_details'])) {
  echo "No payment details found!";
  exit();
}
$payment = $_SESSION['payment_details'];
// Get the student's class from the session
$userClass = isset($_SESSION['class']) ? $_SESSION['class'] : ''; // Example: JSS1, JSS2, 
$tabSessionID = $_GET['tab_id']; // Tab ID


// Load Composer dependencies
require_once 'vendor/autoload.php';
// Required files
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Dotenv\Dotenv;

// Load environment variables
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

$school_name = $_ENV['SCHOOL_NAME'];


if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $regno = $_POST['regno'];
  $fullname = $_POST['fullname'];
  $class = $_POST['class'];
  $term = $_POST['term'];
  $session = $_POST['session'];
  $school_type = $_POST['school_type'];
  $amount = $_POST['amount'];
  $purpose = $_POST['purpose'];
  $method = $_POST['method'];
  $email = $_POST['email'];
  $class1 = $_POST['class1'];


  $discountUsed = isset($payment['discount_used']) ? $payment['discount_used'] : 0;
  $discountAmount = isset($payment['discount_amount']) ? $payment['discount_amount'] : 0;
  $discountPercent = isset($payment['discount_percent']) ? $payment['discount_percent'] : 0;


  if (!empty($class1)) {
    file_put_contents('honeypot_log.txt', date('Y-m-d H:i:s') . " | IP: {$_SERVER['REMOTE_ADDR']}\n", FILE_APPEND);

    echo "
      <script>
          alert('We Caught you Bot/spam!');
          document.location.href = 'oldstdday.php?tab_id=$tabSessionID';
      </script>";
  }



  // Check the last request time for this student and payment purpose
  $query = "SELECT UNIX_TIMESTAMP(timestamp) AS lastRequestTime 
          FROM message 
          WHERE regno = :regno AND purpose = :purpose 
          ORDER BY timestamp DESC 
          LIMIT 1";
  $stmt = $dbh->prepare($query);
  $stmt->bindParam(':regno', $regno);
  $stmt->bindParam(':purpose', $purpose);
  $stmt->execute();
  $row = $stmt->fetch(PDO::FETCH_ASSOC);





  // Insert payment details into the 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();

  // Send Email Notification
  $mail = new PHPMailer(true);

  try {
    // SMTP configuration from .env
    $mail->isSMTP();
    $mail->Host = $_ENV['SMTP_HOST'];
    $mail->SMTPAuth = true;
    $mail->Username = $_ENV['SMTP_USERNAME'];
    $mail->Password = $_ENV['SMTP_PASSWORD'];
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    $mail->Port = $_ENV['SMTP_PORT'];
    $mail->Timeout = 10;

    $mail->setFrom($_ENV['SMTP_USERNAME'], $fullname);
    $mail->addAddress($_ENV['ADMIN_EMAIL'], 'Administrator');

    // Content
    $mail->isHTML(true);
    $mail->Subject = 'REQUEST FOR PAYMENT APPROVAL';
    $mail->Body = "
            <html>
                <body>
                    <div style='max-width: 600px; margin: auto; font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px;'>
                        <h1 style='color: #ffffff; hidden-align: center; padding: 10px 0; background-color: #4CAF50;'>Request for Payment Approval</h1>
                        <p>Dear Administrator,</p>
                        <p>This is to notify you that $fullname with the Admission No: $regno has successfully requested approval for their fees payment.</p>
                        <hr>
                        <h3>Payment Details</h3>
                        <hr>
                        <p><strong>Amount Paid:</strong> $amount</p>
                        <p><strong>Class:</strong> $class</p>
                        <p><strong>Term:</strong> $term</p>
                        <p><strong>Session:</strong> $session</p>
                        <p><strong>Purpose of Payment:</strong> $purpose</p>
                        <p><strong>Payment Method:</strong> $method</p>
                        <p><strong>Thank you!</strong></p>
                        <hr>
                        <center>
                            <p>$school_name &copy; " . date("Y") . ". All Rights Reserved.</p>
                        </center>
                        <hr>
                    </div>
                </body>
            </html>
        ";

    $mail->send();
    echo "
            <script>
                alert('Payment Approval Request sent Successfully. Thank you for the payment made!');
                document.location.href = 'oldstdday.php?tab_id=$tabSessionID';
            </script>";
  } catch (Exception $e) {
    echo "
            <script>
                alert('Payment Approval Request could not be sent. Please try again later.');
                document.location.href = 'oldstdday.php?tab_id=$tabSessionID';
            </script>";
  }
}
?>
<?php
// Get logged-in student's ID from session
$eid2 = $_SESSION['student_id'];
$query = "SELECT * FROM students WHERE id='$eid2'";
$result = mysqli_query($con, $query);

if ($row = mysqli_fetch_assoc($result)) {
  ?>
  <!DOCTYPE html>
  <html lang="en">
  <?php @include("includes/head.php"); ?>
  <style>
    .cpf-wrapper {
      max-width: 640px;
      margin: 0 auto;
      padding: 0 0 40px;
    }

    .confirm-card {
      background: #fff;
      border-radius: 20px;
      box-shadow: 0 4px 30px rgba(15, 23, 42, .07);
      overflow: hidden;
      border: 1px solid #e8ecf4;
    }

    .confirm-card-header {
      padding: 20px 28px;
      border-bottom: 1px solid #f1f5f9;
      display: flex;
      align-items: center;
      gap: 10px;
      background: linear-gradient(135deg, #0f172a, #1e293b);
    }

    .confirm-card-header-icon {
      width: 36px;
      height: 36px;
      background: rgba(255, 255, 255, .1);
      border-radius: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-size: .9rem;
    }

    .confirm-card-header h5 {
      margin: 0;
      font-size: .95rem;
      font-weight: 700;
      color: #f8fafc;
    }

    .confirm-card-body {
      padding: 28px;
    }

    .success-badge {
      background: #f0fdf4;
      border: 1.5px solid #bbf7d0;
      border-radius: 14px;
      padding: 16px 20px;
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 24px;
    }

    .success-badge i {
      font-size: 1.4rem;
      color: #22c55e;
      flex-shrink: 0;
    }

    .success-badge-text h6 {
      margin: 0 0 2px;
      font-weight: 700;
      color: #166534;
      font-size: .95rem;
    }

    .success-badge-text p {
      margin: 0;
      font-size: .82rem;
      color: #15803d;
    }

    .notice-bar {
      background: #fffbeb;
      border: 1.5px solid #fde68a;
      border-radius: 12px;
      padding: 12px 16px;
      font-size: .82rem;
      color: #92400e;
      display: flex;
      align-items: flex-start;
      gap: 8px;
      margin-bottom: 24px;
    }

    .notice-bar i {
      margin-top: 1px;
      color: #f59e0b;
      flex-shrink: 0;
    }

    .btn-continue {
      color: #fff;
      border: none;
      height: 50px;
      padding: 0 40px;
      border-radius: 14px;
      font-size: .95rem;
      font-weight: 700;
      display: inline-flex;
      align-items: center;
      gap: 10px;
      cursor: pointer;
      background: linear-gradient(135deg, #6366f1, #8b5cf6);
      box-shadow: 0 6px 20px rgba(99, 102, 241, .35);
      transition: transform .15s, box-shadow .15s;
    }

    .btn-continue:hover {
      transform: translateY(-2px);
      box-shadow: 0 10px 28px rgba(99, 102, 241, .45);
    }
  </style>

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

      <div class="content-wrapper" style="background:#f0f2f8;">
        <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-credit-card"></i>
                    </div>
                    <div>
                      <h1 class="premium-title text-primary">
                        Payment Management
                        <span class="premium-subtitle text-secondary">Approval Request</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="oldstdday.php" class="text-primary">Home</a></li>
                      <li class="breadcrumb-item active" aria-current="page">Confirm Payment</li>
                    </ol>
                  </nav>
                </div>
              </div>
            </div>
          </div>
        </section>
        <section class="content-body">
          <div class="container-fluid">
            <div class="row">
              <div class="col-md-12">
                <!-- general form elements -->
                <div class="card card-primary">
                  <div class="card-header">
                    <h5 class="card-title font-weight-bold">
                      <i class="fas fa-wallet"></i> Payment Status Confirmation
                    </h5>
                  </div>
                  <div class="card-body">
                    <section class="content" style="padding:16px 12px 40px;">
                      <div class="container-fluid" style="padding-left:0;padding-right:0;">
                        <div class="cpf-wrapper">
                          <div class="confirm-card">
                            <div class="confirm-card-header">
                              <div class="confirm-card-header-icon"><i class="fas fa-check-circle"></i></div>
                              <h5>Payment Status Confirmation</h5>
                            </div>
                            <form role="form" method="post" enctype="multipart/form-data">
                              <div class="confirm-card-body">
                                <div class="success-badge">
                                  <i class="fas fa-check-circle"></i>
                                  <div class="success-badge-text">
                                    <h6>Payment Successful</h6>
                                    <p>Click Continue below to complete your payment approval.</p>
                                  </div>
                                </div>
                                <div class="notice-bar">
                                  <i class="fas fa-exclamation-triangle"></i>
                                  <span>Always click the <strong>Continue</strong> button before you leave this page.
                                    Skipping this step may leave your payment unverified.</span>
                                </div>

                                <input type="hidden" id="regno" name="regno"
                                  value="<?php echo htmlspecialchars($row['studentno']); ?>" required readonly>
                                <input type="hidden" id="fullname" name="fullname"
                                  value="<?php echo htmlspecialchars($row['studentName']); ?>" required readonly>
                                <input type="hidden" name="email" value="<?= htmlspecialchars($payment['email']); ?>"
                                  readonly>
                                <input type="hidden" id="class" name="class"
                                  value="<?php echo htmlspecialchars($row['class']); ?>" required readonly>
                                <input type="hidden" id="class1" name="class1" value="">
                                <input type="hidden" id="term" name="term"
                                  value="<?= htmlspecialchars($payment['term']); ?>" required readonly>
                                <input type="hidden" id="session" name="session"
                                  value="<?= htmlspecialchars($payment['session']); ?>" required readonly>
                                <input type="hidden" id="school_type" name="school_type"
                                  value="<?php echo htmlspecialchars($row['stream']); ?>" required readonly>
                                <input type="hidden" name="amount" value="<?= htmlspecialchars($payment['amount']); ?>"
                                  readonly>
                                <input type="hidden" name="purpose" value="<?= htmlspecialchars($payment['fee_type']); ?>"
                                  readonly>
                                <input type="hidden" name="method" id="method"
                                  value="<?= htmlspecialchars($payment['payment_method']); ?>" readonly>

                                <div style="text-align:center;">
                                  <button type="submit" name="submit" id="submit" class="btn-continue">
                                    <i class="fas fa-arrow-right"></i> Continue
                                  </button>
                                </div>
                              </div>
                            </form>
                          </div>
                        </div>
                      </div>
                    </section>
                  </div><!-- /.wpf-wrapper -->
                </div>
        </section>
      </div><!-- /.content-wrapper -->

      <?php @include("includes/footer.php"); ?>
      <?php @include("includes/foot.php"); ?>
    </div><!-- /.wrapper -->
    <script src="dist/js/select2.min.js"></script>
    <script>
      $(document).ready(function () {
        // Initialize Select2
        $('.select2').select2();

        // Debugging: Check the session value
        const userClass = "<?php echo $userClass; ?>";
        console.log("User class from session:", userClass);

        if (userClass) {
          // Loop through each option and hide irrelevant ones
          $('#purpose option').each(function () {
            const optionClass = $(this).data('class'); // Get the data-class attribute
            if (optionClass && optionClass !== userClass) {
              $(this).remove(); // Remove irrelevant options
            }
          });

          // Refresh Select2 to reflect changes
          $('#purpose').select2();
        } else {
          console.error("User class is not set in the session.");
        }
      });
    </script>

  </body>

  </html>
  <?php
} ?>
</div>
