<?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 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName    = $stResult['term_name'];

include('includes/flash.php');
require_once 'vendor/autoload.php';

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

// required files
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';

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

$school_name = $_ENV['SCHOOL_NAME'];
$school_address = $_ENV['SCHOOL_ADDRESS'];

$message_id = $_GET['id'];
$messageData = $_SESSION['message_data'];
$studentNo = $messageData['regno'];
$demote = 0;


$sqld = "SELECT * FROM students WHERE studentno = ?";
$stmtd = $dbh->prepare($sqld);
$stmtd->execute([$studentNo]);

if ($stmtd->rowCount() > 0) {

  $fecthemaild = $stmtd->fetch(PDO::FETCH_ASSOC);
  $demote = $fecthemaild['demote_status'];
}

if (strlen($_SESSION['sid'] == 0)) {
  header('location:logout.php');
} else {


  if (isset($_POST['disapprove'])) {
    $studentname = $_POST['stdname'];
    $email = $_POST['email'];
    try {
      $dbh->beginTransaction();

      $mail = new PHPMailer(true);
      // 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'], $_ENV['SCHOOL_NAME']);
      $mail->addAddress($email, $studentname);

      $mail->isHTML(true);
      $mail->Subject = $school_name . ' ' . 'Payment Disapproval Notification';
      $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: #FF0000;'>Payment Disapproved</h1>
                    <p>Dear $studentname,</p>
                    <p>We regret to inform you that your payment of NGN $amount has been disapproved.</p>
                     <p>The payment was disapproved due to uncertainity of the payment</p>
                    <p>Kindly wait for two days to confirm if your bank has reversed the transaction made. Then, make the payment again.</p>
                    <p>For more questions and clarifications, please fill the feedback form at the bottom right of the student portal and you will be responded to.</p>
                    <p>Thank you!</p>
                <hr>
                <center>
                    <p>$school_name &copy; " . date("Y") . ". All Rights Reserved.</p>
                </center>
            </div>
        </body>
        </html>";

      $mail->send();

      if (!empty($message_id)) {
        $stmtUpdate = $dbh->prepare("UPDATE message SET status = 2 WHERE id = :message_id AND status = 0 LIMIT 1");
        $stmtUpdate->bindParam(':message_id', $message_id);
        $stmtUpdate->execute();
      }
      $dbh->commit();
      unset($_SESSION['id']);
      unset($_SESSION['message_data']);
      flash_alert('Payment disapproved and Email sent successfully!', 'acec.php');
      header('Location: acec.php');
      exit;
    } catch (Exception $e) {
      $dbh->rollBack();
      flash_alert('Payment was not disapproved because the email could not be sent. Please try again.', 'acec.php');
      header('Location: acec.php');
      exit;
    }
  }
  if (isset($_POST['unresolved'])) {
    try {
      $dbh->beginTransaction();

      // Update the message status to 2 for unresolved payments
      if (!empty($message_id)) {
        $stmtUpdate = $dbh->prepare("UPDATE message SET status = 3 WHERE id = :message_id AND status = 0 LIMIT 1");
        $stmtUpdate->bindParam(':message_id', $message_id, PDO::PARAM_INT);
        $stmtUpdate->execute();
      }

      $dbh->commit();
      unset($_SESSION['id']);
      unset($_SESSION['message_data']);
      flash_alert('Payment marked as unresolved, and message status updated successfully!', 'acec.php');
      header('Location: acec.php');
      exit;
    } catch (Exception $e) {
      $dbh->rollBack();
      flash_alert('Failed to mark payment as unresolved. Please try again.', 'acec.php');
      header('Location: acec.php');
      exit;
    }
  }
  if (isset($_POST['unrelated'])) {
    try {
      $dbh->beginTransaction();

      // Update the message status to 2 for unresolved payments
      if (!empty($message_id)) {
        $stmtUpdate = $dbh->prepare("UPDATE message SET status = 5 WHERE id = :message_id AND status = 0 LIMIT 1");
        $stmtUpdate->bindParam(':message_id', $message_id, PDO::PARAM_INT);
        $stmtUpdate->execute();
      }

      $dbh->commit();
      unset($_SESSION['id']);
      unset($_SESSION['message_data']);
      flash_alert('Payment marked as unrelated, and message status updated successfully!', 'acec.php');
      header('Location: acec.php');
      exit;
    } catch (Exception $e) {
      $dbh->rollBack();
      flash_alert('Failed to mark payment as unrelated. Please try again.', 'acec.php');
      header('Location: acec.php');
      exit;
    }
  }


  if (isset($_POST['submit'])) {

    $regno = $_POST['fullname'];
    $adno = $_POST['fullname'];
    $term = $_POST['term'];
    $session = $_POST['session'];
    $class = $_POST['class'];
    $school_type = $_POST['school_type'];
    $payment_type = $_POST['payment_type'];
    $pay_id = $_POST['pay_id'];
    $amount = $_POST['amount'];
    $payment_for = $_POST['pay_for'];
    $studentname = $_POST['stdname'];
    $method = $_POST['method'];
    $email = $_POST['email'];

    // Check for duplicate payment
    $checkQuery = mysqli_query($con, "SELECT * FROM payment WHERE studentno = '$adno' AND pay_id = '$pay_id'");
    if (mysqli_num_rows($checkQuery) > 0) {
      flash_alert('Duplicate payment detected! This payment has already been Approved.', 'approve.php');
      header('Location: approve.php');
      exit;
      exit;
    }

    $sql = "SELECT * FROM students WHERE studentno = ?";
    $stmt = $dbh->prepare($sql);
    $stmt->execute([$adno]);

    if ($stmt->rowCount() > 0) {

      $fecthemail = $stmt->fetch(PDO::FETCH_ASSOC);
      $id = $fecthemail['id'];
      $section = $fecthemail['section'];


      try {
        // Check for duplicate payment before proceeding
        $duplicateCheck = mysqli_query($con, "SELECT id FROM payment WHERE studentno = '$adno' AND pay_id = '$pay_id' LIMIT 1");
        if (mysqli_num_rows($duplicateCheck) > 0) {
          flash_alert('Duplicate payment detected! This payment has already been approved.', 'acec.php');
          header('Location: acec.php');
          exit;
          exit;
        }
        $dbh->beginTransaction();

        $mail = new PHPMailer(true);
        // 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'], $_ENV['SCHOOL_NAME']);
        $mail->addAddress($email, $studentname);

        $mail->isHTML(true);
        $mail->Subject = $school_name . ' ' . 'Lesson Fees Payment Approval Notification';
        $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;'>Payment Approved</h1>
                  <p>Dear $studentname,</p>
                  <p>We are pleased to inform you that your payment of NGN $amount has been confirmed successfully.</p>
                  <hr>
                  <h5>Payment Details</h5>
                  <hr>
                  <p><strong>Amount Paid:</strong> NGN $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> $payment_for</p>
                  <p>Please login to your student portal to view and download your receipt and other necessary documents.</p>
                  <p>Thank you!</p>
                  <hr>
                  <center>
                      <p>$school_name &copy; " . date("Y") . ". All Rights Reserved.</p>
                  </center>
              </div>
          </body>
          </html>";

        $mail->send();

        $query = mysqli_query($con, "INSERT INTO payment(studentno, studentName, Term, session, class, school_type, payment_type, pay_id, amount, pay_for, student_id,method,section) 
          VALUES ('$adno', '$studentname', '$term', '$session', '$class', '$school_type', '$payment_type', '$pay_id', '$amount', '$payment_for', '$id','$method','$section')");

        if ($query) {
          if (!empty($message_id)) {
            $stmtUpdate = $dbh->prepare("UPDATE message SET status = 1 WHERE id = :message_id AND status = 0 LIMIT 1");
            $stmtUpdate->bindParam(':message_id', $message_id);
            $stmtUpdate->execute();
          }
          $dbh->commit();
          unset($_SESSION['id']);
          unset($_SESSION['message_data']);
          flash_alert('Payment approved and Email sent successfully!', 'acec.php');
          header('Location: acec.php');
          exit;
        } else {
          $dbh->rollBack();
          flash_alert('Something went wrong. Payment was not approved. Please try again.');
        }
      } catch (Exception $e) {
        $dbh->rollBack();
        flash_alert('Payment was not approved because email could not be sent. Please try again.', 'acec.php');
        header('Location: acec.php');
        exit;
      }
    }
  }
  ?>
  <!DOCTYPE html>
  <html>
  <?php @include("includes/head.php"); ?>

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

      <!-- Main Sidebar Container -->
      <?php @include("includes/sidebar.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">Pay Lesson Fees (Admitted Students)</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">Home</a></li>
                      <li class="breadcrumb-item active"><a href="approve.php" class="text-primary">Approve Payment</a>
                      </li>
                      <li class="breadcrumb-item active" aria-current="page">Pay Lesson Fee</li>
                    </ol>
                  </nav>
                </div>
              </div>
            </div>
          </div>
        </section>

        <!-- Main content -->
        <section class="content">
          <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-book"></i> Pay Lesson Fees</h5>
                  </div>
                  <!-- /.card-header -->
                  <!-- form start -->
                  <form role="form" method="post" enctype="multipart/form-data">
                    <div class="card-body">
                      <span style="color: brown">
                        <h5>Student's Details</h5>
                      </span>
                      <hr>
                      <div class="row">

                        <div class="form-group col-md-4">
                          <label for="sex">Admission No. | Fullname</label>
                          <select class="form-control" id="fullname" name="fullname" required style="width:100%">
                            <?php
                            $preRegno = htmlspecialchars($messageData['regno'] ?? '');
                            $preName  = htmlspecialchars($messageData['fullname'] ?? '');
                            if ($preRegno): ?>
                              <option value="<?php echo $preRegno; ?>" selected>
                                <?php echo $preRegno . ($preName ? ' | ' . $preName : ''); ?>
                              </option>
                            <?php endif; ?>
                          </select>
                          <small class="text-muted">Search by admission no. or name</small>
                        </div>
                        <div class="form-group col-md-4">
                          <label for="age">Student's Fullname</label>
                          <input type="text" class="form-control" id="stdname" name="stdname"
                            value="<?php echo $messageData['fullname']; ?>" required readonly>
                        </div>
                        <div class="form-group col-md-4">
                          <label for="age">Term</label>
                          <select name="term" id="term" class="form-control" required>
                            <?php
                            $termResult = $con->query("SELECT DISTINCT id, term_name FROM school_terms ORDER BY term_name ASC");
                            while ($row = $termResult->fetch_assoc()) {
                              $selected = ($messageData['term'] ?? '') == $row['term_name'] ? 'selected' : '';
                              echo "<option value='{$row['term_name']}' $selected>{$row['term_name']}</option>";
                            }
                            ?>
                            <option value="Fourth Term">Fourth Term</option>
                          </select>
                        </div>
                        <div class="form-group col-md-4">
                          <label for="sex">Session</label>
                          <!-- option for session using preselect -->
                          <select name="session" id="session" class="form-control" required>
                            <option value="">-- Select Session --</option>

                            <?php
                            $sessionResult = $con->query("SELECT DISTINCT id, session_name FROM school_sessions ORDER BY session_name DESC");
                            while ($row = $sessionResult->fetch_assoc()) {
                              $selected = ($messageData['session'] ?? '') == $row['session_name'] ? 'selected' : '';
                              echo "<option value='{$row['session_name']}' $selected>{$row['session_name']}</option>";
                            }
                            ?>
                          </select>

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

                        </div>

                        <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 $messageData['school_type']; ?>" required>

                        </div>
                      </div>
                      <div class="row">
                        <div class="form-group col-md-4">
                          <label for="age">Payment Type</label>
                          <select type="select" class="form-control" id="payment_type" name="payment_type" required>
                            <option value=""></option>
                            <option value="Full Payment">Full Payment</option>
                            <option value="Part Payment">Part Payment</option>
                          </select>
                        </div>
                        <div class="form-group col-md-4">
                          <label for="age">Payment ID</label>
                          <input type="text" class="form-control" name="pay_id" id="pay_id"
                            value="<?php
                            function generate_pay_ID($length = 15)
                            {
                              $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSQTUVWXYZ';
                              $charlength = strlen($char);
                              $randomString = '';
                              for ($i = 0; $i < $length; $i++) {
                                # code...
                                $randomString .= $char[rand(0, $charlength - 1)];
                              }
                              return $randomString;
                            }
                            $tid = generate_pay_ID();
                            echo isset($pay_id) ? $pay_id : $tid ?>" required readonly>
                        </div>

                        <div class="form-group col-md-4">
                          <label for="age">Payment For</label>
                          <input type="text" class="form-control" id="pay_for" name="pay_for"
                            value="<?php echo $messageData['purpose']; ?>" required>
                        </div>

                        <div class="form-group col-md-4">
                          <label for="age">Payment Method</label>
                          <input type="text" class="form-control" id="method" name="method"
                            value="<?php echo $messageData['method']; ?>" required>
                        </div>
                        <div class="form-group col-md-4">
                          <label for="amount_display">Amount Paid (NGN)</label>
                          <!-- Visible, formatted for user -->
                          <input type="text" class="form-control" id="amount_display"
                            value="<?php echo number_format($messageData['amount']); ?>"
                            oninput="updateHiddenAmount(this)">

                          <!-- Hidden, real value for DB -->
                          <input type="hidden" id="amount" name="amount" value="<?php echo $messageData['amount']; ?>">
                        </div>

                        <div class="form-group col-md-4">
                          <label for="age">Email</label>
                          <input type="email" class="form-control" id="email" name="email"
                            value="<?php echo $messageData['email']; ?>" required>
                        </div>

                      </div>



                      <!-- /.card-body -->
                      <div class="card-footer">
                        <center>
                          <button type="submit" name="unrelated" id="unrelated" class="btn btn-warning mb-3"><i
                              class="fas fa-exclamation-circle"></i> Mark as Unrelated</button>
                          <button type="submit" name="submit" id="submit" class="btn btn-success mb-3"
                            onclick="<?php if ($demote == 1) { ?> return confirm('This student is marked as DEMOTED. Are you sure you want to approve payment?'); <?php } ?>">
                            <i class="fas fa-check-circle"></i> Approve
                          </button>
                          <button type="submit" name="disapprove" id="disapprove" class="btn btn-danger mb-3"><i
                              class="fas fa-times-circle"></i> Disapprove</button>
                          <button type="submit" name="unresolved" id="unresolved" class="btn btn-info mb-3"><i
                              class="fas fa-question-circle"></i> Mark as Unresolved</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/jquery-3.7.1.min.js"></script>
    <script src="dist/js/select2.min.js"></script>

    <script>
      $(document).ready(function () {
        // Student search: Select2 with AJAX — admitted students only
        $('#fullname').select2({
          placeholder: 'Search by admission no. or name',
          allowClear: true,
          minimumInputLength: 1,
          ajax: {
            url: 'fetch_student_search1.php',
            dataType: 'json',
            delay: 300,
            data: function (params) {
              return { q: params.term };
            },
            processResults: function (data) {
              return { results: data.results };
            },
            cache: true
          }
        });

        // Update fields only when a different student is selected
        $('#fullname').on('select2:select', function (e) {
          var data = e.params.data;
          $('#stdname').val(data.studentName || '');
          $('#class').val(data.class || '');
          $('#school_type').val(data.stream || '');
          if (data.email) $('#email').val(data.email);
        });

        // Clear fields only when selection is explicitly removed
        $('#fullname').on('select2:clear', function () {
          $('#stdname').val('');
          $('#class').val('');
          $('#school_type').val('');
        });

        $('#payment_type').select2();
        $('#session').select2();
        $('#term').select2();
      });

      function updateHiddenAmount(displayInput) {
        let cleanValue = displayInput.value.replace(/[^0-9.]/g, '');
        document.getElementById('amount').value = cleanValue;
        console.log("Hidden value is now: " + document.getElementById('amount').value);
      }
    </script>
  </body>

  </html>
  <?php
} ?>
