<?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');
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'];
$prefix = $_ENV['Admission_prefix'];
$url = $_ENV['BASE_URL'];

$message_id = $_GET['id'];
$messageData = $_SESSION['message_data'];

// âœ… Generate 10-character uppercase alphanumeric token
function generateToken($length = 10)
{
  $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  $charactersLength = strlen($characters);
  $token = '';
  for ($i = 0; $i < $length; $i++) {
    $token .= $characters[random_int(0, $charactersLength - 1)];
  }
  return $token;
}

$registration_token = generateToken();

if (strlen($_SESSION['sid']) == 0) {
  header('location:logout.php');
} else {
  if (isset($_POST['disapprove'])) {
    $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'];
    $email = $_POST['email'];

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

    if ($stmt->rowCount() > 0) {
      // Check student and email
      $fecthemail = $stmt->fetch(PDO::FETCH_ASSOC);
      $id = $fecthemail['id'];
    }

    $mail = new PHPMailer(true);
    try {
      $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: #f44336;'>Payment Disapproved</h1>
                    <p>Dear $studentname,</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();

      // Perform database updates only after successful email sending
      $stmtDisapprove = $dbh->prepare("UPDATE message SET status = 2 WHERE id = :message_id AND status = 0 LIMIT 1");
      $stmtDisapprove->bindParam(':message_id', $message_id);
      $stmtDisapprove->execute();

      flash_alert('Payment disapproved and Email sent successfully!', 'otherpay.php');
        header('Location: otherpay.php'); exit;
    } catch (Exception $e) {
      flash_alert('Email could not be sent. Payment disapproval skipped: ' . $e->getMessage(), 'otherpay.php');
        header('Location: otherpay.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!', 'pay_tuition.php');
        header('Location: pay_tuition.php'); exit;
    } catch (Exception $e) {
      $dbh->rollBack();
      flash_alert('Failed to mark payment as unresolved. Please try again.', 'pay_tuition.php');
        header('Location: pay_tuition.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!', 'otherpay.php');
        header('Location: otherpay.php'); exit;
    } catch (Exception $e) {
      $dbh->rollBack();
      flash_alert('Failed to mark payment as unrelated. Please try again.', 'otherpay.php');
        header('Location: otherpay.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'];
    $token_for = $_POST['pay_for'];
    $studentname = $_POST['stdname'];
    $method = $_POST['method'];
    $email = $_POST['email'];





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

      // 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.', 'otherpay.php');
        header('Location: otherpay.php'); exit;
    exit;
}

      $mail = new PHPMailer(true);
      try {
        $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 Approval Notification';
        $registrationLink = "$url/boarding_registration.php";

        $mailBody = "
<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>
        <p>Please login to your student portal to download your receipt.</p>";

        if (strtoupper(trim($payment_for)) == 'BOARDING FORM (REGISTERED STUDENT)') {
          $mailBody .= "<p> Kindly pay your boarding fees to enable you to complete your boarding registration.</p>";
        }


        $boardingFeeNames = [
          'JSS 1-3 FULL (ONE TERM) BOARDING FEES (NEW STUDENT)',
          'JSS 1-3 FULL (2 TERMS) BOARDING FEES (NEW STUDENT)',
          'JSS 1-3 FULL SESSION BOARDING FEES (NEW STUDENT)',
          'SS 1-3 FULL (ONE TERM) BOARDING FEES (NEW STUDENT)',
          'SS 1-3 FULL (2 TERMS) BOARDING FEES (NEW STUDENT)',
          'SS 1-3 FULL SESSION BOARDING FEES (NEW STUDENT)'
        ];


        if (in_array(trim($payment_for), $boardingFeeNames)) {
          $mailBody .= "
        <p style='margin-top: 20px;'>
            <strong>Next Step:</strong><br>
            <p><strong>Registration Token:</strong> <span style='font-size: 18px; color: red;'>$registration_token</span></p>
            <strong>Note:</strong> This token is required to complete your boarding registration.
            Please complete your boarding registration by clicking the link below:<br>
            <a href='$registrationLink' target='_blank' style='color: #4CAF50;'>Complete Boarding Registration</a>
        </p>";
        }

        $mailBody .= "
        <p>Thank you!</p>
        <hr>
        <center>
            <p>$school_name &copy; " . date("Y") . ". All Rights Reserved.</p>
        </center>
    </div>
</body>
</html>";

        $mail->Body = $mailBody;

        $mail->send();

        // if payment type is boarding form (registered student) insert registration token 
        $boardingFeeNames = [
          'JSS 1-3 FULL (ONE TERM) BOARDING FEES (NEW STUDENT)',
          'JSS 1-3 FULL (2 TERMS) BOARDING FEES (NEW STUDENT)',
          'JSS 1-3 FULL SESSION BOARDING FEES (NEW STUDENT)',
          'SS 1-3 FULL (ONE TERM) BOARDING FEES (NEW STUDENT)',
          'SS 1-3 FULL (2 TERMS) BOARDING FEES (NEW STUDENT)',
          'SS 1-3 FULL SESSION BOARDING FEES (NEW STUDENT)'
        ];

        if (in_array(trim($payment_for), $boardingFeeNames)) {
          // âœ… Save token in a separate table
          mysqli_query($con, "INSERT INTO registration_tokens (studentno, student_name, token_for, class, term, session, school_type, email, token, token_status) 
                      VALUES ('$adno','$studentname', '$token_for', '$class', '$term', '$session', '$school_type', '$email', '$registration_token', 'pending')");
        }
        // Perform database updates after successful email sending
        $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();
          }
          unset($_SESSION['id']);
          unset($_SESSION['message_data']);
          flash_alert('Payment approved and Email sent successfully!', 'otherpay.php');
        header('Location: otherpay.php'); exit;
        } else {
          throw new Exception('Database operation failed.');
        }
      } catch (Exception $e) {
        flash_alert('Email could not be sent. Payment approval skipped: ' . $e->getMessage(), 'otherpay.php');
        header('Location: otherpay.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">Other Serveices 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">Home</a></li>
                            <li class="breadcrumb-item"><rove href="approve.php" class="text-primary">Approve Payment</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Other Fees</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-wallet"></i> Payment For Other Services</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, or type a new 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']); ?>" readonly
                            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"> <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 + tags (free-text fallback)
      $('#fullname').select2({
        placeholder: 'Search by admission no. or name, or type a new name',
        allowClear: true,
        tags: true,           // allows typing a value not in the list
        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
        },
        createTag: function(params) {
          var term = $.trim(params.term);
          if (term === '') return null;
          return { id: term, text: term, newTag: true };
        }
      });

      // When a student is selected from the dropdown
      $('#fullname').on('select2:select', function(e) {
        var data = e.params.data;
        if (data.newTag) {
          // Free-typed value: clear auto-filled fields, let user fill stdname manually
          $('#stdname').val('').prop('readonly', false).focus();
          $('#class').val('');
          $('#school_type').val('');
        } else {
          // Matched student from DB: auto-fill and keep intact until changed
          $('#stdname').val(data.studentName || '').prop('readonly', true);
          $('#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('').prop('readonly', false);
        $('#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>
