<?php
include('includes/session.php');
error_reporting(0);
include('includes/dbconnection.php');

// Get the student's class from the session
$userClass = isset($_SESSION['class']) ? $_SESSION['class'] : ''; // Example: JSS1, JSS2, 

// 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'];


  // 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 payment table
  $sql = "INSERT INTO message (regno, fullname, class, term, session, school_type, amount, purpose, method, email) VALUES (:regno, :fullname, :class, :term, :session, :school_type, :amount, :purpose, :method, :email)";
  $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->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; text-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('Message was sent successfully. Thank you for the payment made!');
                document.location.href = 'confirmpaymentold.php';
            </script>
        ";
  } catch (Exception $e) {
    echo "
            <script>
                alert('Message was sent successfully. Thank you for the payment made!');
                document.location.href = 'confirmpaymentold.php';
            </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"); ?>
  <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
  <style>
    .cpf-wrapper {
      max-width: 960px;
      margin: 0 auto;
      padding: 0 0 40px;
    }

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

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

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

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

    .form-card-body {
      padding: 24px;
    }

    .field-label {
      font-size: .72rem;
      font-weight: 600;
      text-transform: uppercase;
      letter-spacing: .06em;
      color: #64748b;
      margin-bottom: 6px;
      display: block;
    }

    .wpf-input {
      width: 100%;
      height: 44px;
      border: 1.5px solid #e2e8f0;
      border-radius: 12px;
      padding: 0 14px;
      font-size: .88rem;
      color: #0f172a;
      background: #f8fafc;
      transition: border-color .2s, box-shadow .2s;
      outline: none;
    }

    .wpf-input:focus {
      border-color: #6366f1;
      box-shadow: 0 0 0 4px rgba(99, 102, 241, .1);
      background: #fff;
    }

    .wpf-input[readonly] {
      background: #f1f5f9;
      color: #64748b;
      cursor: default;
    }

    .select2-container {
      width: 100% !important;
    }

    .select2-container--default .select2-selection--single {
      height: 44px !important;
      border: 1.5px solid #e2e8f0 !important;
      border-radius: 12px !important;
      background: #f8fafc !important;
      display: flex;
      align-items: center;
      padding: 0 14px;
    }

    .select2-container--default.select2-container--open .select2-selection--single,
    .select2-container--default.select2-container--focus .select2-selection--single {
      border-color: #6366f1 !important;
      box-shadow: 0 0 0 4px rgba(99, 102, 241, .1) !important;
      background: #fff !important;
    }

    .select2-container--default .select2-selection--single .select2-selection__rendered {
      color: #0f172a;
      font-size: .88rem;
      line-height: 44px !important;
      padding: 0;
    }

    .select2-container--default .select2-selection--single .select2-selection__arrow {
      height: 44px !important;
      right: 12px;
    }

    .select2-dropdown {
      border: 1.5px solid #e2e8f0 !important;
      border-radius: 12px !important;
      box-shadow: 0 10px 40px rgba(15, 23, 42, .12) !important;
      overflow: hidden;
    }

    .select2-container--default .select2-results__option--highlighted {
      background: #6366f1 !important;
    }

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

    .btn-submit:hover {
      transform: translateY(-2px);
    }

    .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: 20px;
    }

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

    .section-divider {
      height: 1px;
      background: #f1f5f9;
      margin: 20px 0;
    }
  </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">
          <div class="container-fluid">
            <div class="row mb-2">
              <div class="col-sm-8">
                <h3 class="text-primary font-weight-bold">
                  <i class="fas fa-credit-card"></i> Payment Management â†’
                  <span class="font-italic text-secondary" style="font-size: 0.5em;">Approval Request</span>
                </h3>
              </div>
              <div class="col-sm-4">
                <ol class="breadcrumb float-sm-right">
                  <li class="breadcrumb-item"><a href="oldstdday.php">Home</a></li>
                  <li class="breadcrumb-item active">Confirm Payment</li>
                </ol>
              </div>
            </div>
          </div>
        </section>

        <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="form-card">
                <div class="form-card-header">
                  <div class="form-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="form-card-body">
                    <div class="notice-bar">
                      <i class="fas fa-exclamation-triangle"></i>
                      <span>Always click the <strong>Submit</strong> button before you leave this page.</span>
                    </div>
                    <div class="row">
                      <div class="form-group col-md-4" style="margin-bottom:18px;">
                        <label class="field-label">Admission No.</label>
                        <input type="text" class="wpf-input" id="regno" name="regno"
                          value="<?php echo $row['studentno']; ?>" required readonly>
                      </div>

                      <div class="form-group col-md-4" style="margin-bottom:18px;">
                        <label class="field-label">Student's Fullname</label>
                        <input type="text" class="wpf-input" id="fullname" name="fullname"
                          value="<?php echo $row['studentName']; ?>" required readonly>
                      </div>

                      <div class="form-group col-md-4" style="margin-bottom:18px;">
                        <label class="field-label">Email</label>
                        <input type="email" class="wpf-input" id="email" name="email" value="<?php echo $row['email']; ?>"
                          required>
                      </div>
                    </div>
                    <div class="row">
                      <div class="form-group col-md-4" style="margin-bottom:18px;">
                        <label class="field-label">Class</label>
                        <input type="text" class="wpf-input" id="class" name="class" value="<?php echo $row['class']; ?>"
                          required readonly>
                      </div>
                      <div class="form-group col-md-4" style="margin-bottom:18px;">
                        <label class="field-label">Term</label>
                        <select class="select2-field" id="term" name="term">
                          <option></option>
                          <option value="First Term">First Term</option>
                          <option value="Second Term">Second Term</option>
                          <option value="Third Term">Third Term</option>
                          <option value="Full Session">Full Session</option>
                          <option value="First and Second Term">First and Second Term</option>
                          <option value="Second and Third Term">Second and Third Term</option>
                        </select>
                      </div>
                      <div class="form-group col-md-4" style="margin-bottom:18px;">
                        <label class="field-label">Session</label>
                        <select class="select2-field" id="session" name="session" required>
                          <option></option>
                          <option value="2023/2024">2023/2024</option>
                          <option value="2024/2025">2024/2025</option>
                          <option value="2025/2026">2025/2026</option>
                          <option value="2026/2027">2026/2027</option>
                          <option data-class="JSS 1" value="2027/2028">2027/2028</option>
                          <option data-class="JSS 1" value="2028/2029">2028/2029</option>
                          <option data-class="JSS 1" value="2029/2030">2029/2030</option>
                          <option data-class="JSS 1" value="2030/2031">2030/2031</option>
                          <option data-class="JSS 1" value="2031/2032">2031/2032</option>
                          <option data-class="JSS 1" value="2032/2033">2032/2033</option>
                          <option data-class="JSS 1" value="2033/2034">2033/2034</option>
                          <option data-class="JSS 1" value="2034/2035">2034/2035</option>
                        </select>
                      </div>





                    </div>
                    <div class="row">

                      <div class="form-group col-md-4">
                        <label for="age">School Type</label>
                        <input type="text" class="form-control" id="school_type" name="school_type"
                          value="<?php echo $row['stream']; ?>" required readonly>

                      </div>

                      <div class="form-group col-md-4">
                        <label for="age">Amount Paid</label>
                        <input type="number" class="form-control" id="amount" name="amount" placeholder="Amount Paid"
                          required>
                      </div>

                      <div class="form-group col-md-4">
                        <label for="purpose">Purpose of Payment</label>
                        <select class="form-control" id="purpose" name="purpose" required>
                          <option value=""></option>

                          <option data-class="JSS 1" value="JSS 1 SCHOLARSHIP STUDENT FEES (DAY)">JSS 1 SCHOLARSHIP
                            STUDENT FEES (DAY)</option>
                          <option data-class="JSS 2" value="JSS 2 SCHOLARSHIP STUDENT FEES (DAY)">JSS 2 SCHOLARSHIP
                            STUDENT FEES (DAY)</option>
                          <option data-class="JSS 3" value="JSS 3 SCHOLARSHIP STUDENT FEES (DAY)">JSS 3 SCHOLARSHIP
                            STUDENT FEES (DAY)</option>

                          <option data-class="SS 1" value="SS 1 SCHOLARSHIP STUDENT FEES (DAY)">SS 1 SCHOLARSHIP STUDENT
                            FEES (DAY)</option>
                          <option data-class="SS 2" value="SS 2 SCHOLARSHIP STUDENT FEES (DAY)">SS 2 SCHOLARSHIP STUDENT
                            FEES (DAY)</option>
                          <option data-class="SS 3" value="SS 3 SCHOLARSHIP STUDENT FEES (DAY)">SS 3 SCHOLARSHIP STUDENT
                            FEES (DAY)</option>



                          <option data-class="JSS 1" value="JSS1 Lesson Fees">JSS1 LESSON FEES</option>
                          <option data-class="JSS 2" value="JSS2 Lesson Fees">JSS2 LESSON FEES</option>
                          <option data-class="JSS 3" value="JSS3 Lesson Fees">JSS3 LESSON FEES</option>
                          <option data-class="SS 1" value="SSS1 Lesson Fees">SSS1 LESSON FEES</option>
                          <option data-class="SS 2" value="SSS2 Lesson Fees">SSS2 LESSON FEES</option>
                          <option data-class="SS 3" value="SSS3 Lesson Fees">SSS3 LESSON FEES</option>

                          <option data-class="SS 2" value="GCE Class Fees">GCE CLASS FEES</option>

                          <option data-class="JSS 1" value="JSS 1-3 SUMMER SCHOOL">JSS 1-3 SUMMER SCHOOL</option>
                          <option data-class="SS 1" value="SS 1-3 SUMMER SCHOOL">SS 1-3 SUMMER SCHOOL</option>
                          <option data-class="JSS 2" value="JSS 1-3 SUMMER SCHOOL">JSS 1-3 SUMMER SCHOOL</option>
                          <option data-class="SS 2" value="SS 1-3 SUMMER SCHOOL">SS 1-3 SUMMER SCHOOL</option>
                          <option data-class="JSS 3" value="JSS 1-3 SUMMER SCHOOL">JSS 1-3 SUMMER SCHOOL</option>
                          <option data-class="SS 3" value="SS 1-3 SUMMER SCHOOL">SS 1-3 SUMMER SCHOOL</option>


                          <option value="EXCURSION">EXCURSION</option>
                          <option value="SCHOOL YEARBOOK">SCHOOL YEARBOOK</option>
                          <option value="BOARDING FORM">BOARDING FORM (REGISTERED STUDENT)</option>
                          <option value="SCHOOL UNIFORM (ONE PIECE)">SCHOOL UNIFORM (ONE PIECE)</option>
                          <option value="SCHOOL UNIFORM (FULL SET)">SCHOOL UNIFORM (FULL SET)</option>
                          <option value="SCHOOL CARDIGAN">SCHOOL CARDIGAN</option>
                          <option value="SCHOOL SPORTWEAR">SCHOOL SPORTWEAR</option>
                        </select>
                      </div>
                      <div class="form-group col-md-4">
                        <label for="purpose">Payment Method</label>
                        <select class="form-control" id="method" name="method" required>
                          <option value=""></option>
                          <option value="Web Payment">Website / Portal Payment</option>
                          <option value="Others">Others</option>
                        </select>
                      </div>

                    </div>


                    <!-- /.card-body -->
                    <div class="card-footer">
                      <center><button type="submit" name="submit" id="submit" class="btn btn-primary">Submit</button>
                      </center>
                    </div>
                </form>
              </div>
              <!-- /.card -->
            </div>
            <!-- /.col -->
          </div>
          <!-- /.row -->
      </div>
      <!-- /.container-fluid -->
      </section>
      <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->
    <?php @include("includes/footer.php"); ?>

    </div>


    <!-- ./wrapper -->
    <?php @include("includes/foot.php"); ?>
    <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>
    <script>
      // In your Javascript (external .js resource or <script> tag)
      $(document).ready(function () {
        $('#method').select2();
      });
    </script>

  </body>

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