<?php
session_name('mini_admin_session');
session_start();

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');

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 Composer dependencies
require_once 'vendor/autoload.php';
// Load environment variables
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

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


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

  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'];
    $amount = $_POST['amount'];
    $payment_for = $_POST['pay_for'];
    $studentname = $_POST['stdname'];
    $mode = $_POST['mode'];
    $account = $_POST['account'];
    $sname = $_POST['sname'];
    $dop = $_POST['date'];
    $top = $_POST['time'];
    $form = $_POST['form'];
    $upload = $_POST['upload'];
    $addinfo = $_POST['addinfo'];
    $rate = $_POST['rate'];
    $issue = $_POST['issue'];
    $issue2 = $_POST['issue2'];
    $email = $_POST['email'];


    
    $admin = $_SESSION['sid'];

    $sql = "SELECT * FROM tblusers WHERE id = ?";
    $stmt = $dbh->prepare($sql);
    $stmt->execute([$admin]);

    if ($stmt->rowCount() > 0) {
      $fecthemail = $stmt->fetch(PDO::FETCH_ASSOC);
      $request = $fecthemail['id'];

      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_NO_REPLY'];
        $mail->Password = $_ENV['SMTP_NO_REPLY_PASSWORD'];
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = $_ENV['SMTP_PORT'];
        $mail->Timeout = 10;

        $mail->setFrom($_ENV['SMTP_NO_REPLY'], $studentname);
        $mail->addAddress($_ENV['ADMIN_EMAIL'], 'Administrator');
        $mail->isHTML(true);
        $mail->Subject = 'REQUEST FOR PAYMENT APPROVAL FROM ADMIN 2';
        $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 $studentname with the Admission No: $regno has successfully requested approval for their fees payment.</p>
                                <hr>
                                <h5>Payment Details</h5>
                                <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> $payment_for</p>
                                <p><strong>Mode of Payment:</strong> $mode</p>
                                <p><strong>Bank Account:</strong> $account</p>
                                <p><strong>Sender Name:</strong> $sname</p>
                                <p><strong>Date of Payment:</strong> $dop</p>
                                <p><strong>Time of Payment:</strong> $top</p>
                                <p><strong>Form Number:</strong> $form</p>
                                <p><strong>Receipt Upload:</strong> $upload</p>
                                <p><strong>Additional Information:</strong> $addinfo</p>
                                <p><strong>Rating:</strong> $rate</p>
                                <p><strong>Any Issue:</strong> $issue</p>
                                <p><strong>Type Issue:</strong> $issue</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();

        $sql = "INSERT INTO message (regno, fullname, email,class, term, session, school_type, amount, purpose, method, Bank_account, Sender, pay_type, dop, top, Form, Upload, Addinfo, Rating, Issue, Type,request)
                VALUES (:regno, :fullname, :email, :class, :term, :session, :school_type, :amount, :purpose, :mode, :account, :sname, :payment_for, :dop, :top, :form, :upload, :addinfo, :rate, :issue, :issue2,:request)";
        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(':regno', $regno);
        $stmt->bindParam(':fullname', $studentname); // Fixed binding variable
        $stmt->bindParam(':email', $email);
        $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', $payment_for); // Correct placeholder value
        $stmt->bindParam(':mode', $mode); // Corrected 'method' to 'mode'
        $stmt->bindParam(':account', $account);
        $stmt->bindParam(':sname', $sname);
        $stmt->bindParam(':payment_for', $payment_type);
        $stmt->bindParam(':dop', $dop);
        $stmt->bindParam(':top', $top);
        $stmt->bindParam(':form', $form);
        $stmt->bindParam(':upload', $upload);
        $stmt->bindParam(':addinfo', $addinfo);
        $stmt->bindParam(':rate', $rate);
        $stmt->bindParam(':issue', $issue);
        $stmt->bindParam(':issue2', $issue2);
        $stmt->bindParam(':request', $request);




        $stmt->execute();
        $dbh->commit();

        // Email sending logic here
        flash_alert('Payment request and Email sent successfully!', 'pay_tuition1.php');
        header('Location: pay_tuition1.php'); exit;
      } catch (Exception $e) {
        $dbh->rollBack();
        flash_alert('Something went wrong. Please try again.');
      }
    }
  }
}
?>
<!DOCTYPE html>
<html>
<?php @include("includes/head.php"); ?>

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

    <!-- Main Sidebar Container -->
    <?php @include("includes/sidebar2.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">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="dashboard1.php" class="text-primary">Home</a></li>
                            <li class="breadcrumb-item"><rove href="approve1.php" class="text-primary">Approve Payment</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Request</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-credit-card"></i> Payment Approval Request for Admitted Student</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%">
                          <option value=""></option>
                        </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" required readonly>
                      </div>
                      <div class="form-group col-md-4">
                        <label for="age">Email</label>
                        <input type="email" class="form-control" id="email" name="email" required>
                      </div>

                      <div class="form-group col-md-4">
                        <label for="age">Term</label>
                        <select type="select" class="form-control" id="term" name="term" required>
                          <option value="">Term</option>

                          <option value="Full Session">Full Session (First, Second & Third Term)</option>
                          <option value="First Term and Second Term">Two Terms (First & Second Term)</option>
                          <option value="Second Term and Third Term">Two Terms (Second & Third Term)</option>
                          <option value="Full Session 2 Instalment">Full Session in 2 Instalments</option>
                          <option value="Full Session 3 Instalment">Full Session in 3 Instalments</option>
                          <option value="Full Session 4 Instalment">Full Session in 4 Instalments</option>
                          <?php
                          $query4 = "SELECT DISTINCT term_name FROM school_terms ORDER BY term_name ASC";
                          $result4 = $con->query($query4);
                          while ($row4 = $result4->fetch_assoc()) {
                            echo "<option value='{$row4['term_name']}'>{$row4['term_name']}</option>";
                          }
                          ?>

                        </select>


                      </div>
                      <div class="form-group col-md-4">
                        <label for="sex">Session</label>
                        <select type="select" class="form-control" id="session" name="session" required>
                          <option value="">Session</option>
                          <?php
                          $query3 = "SELECT session_name FROM school_sessions ORDER BY id DESC";
                          $result3 = $con->query($query3);
                          while ($row3 = $result3->fetch_assoc()) {
                            echo "<option value='{$row3['session_name']}'>{$row3['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" readonly 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" readonly required>

                      </div>

                      <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="">Payment Type</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 For</label>
                        <select type="select" class="form-control" id="pay_for" name="pay_for" required>
                          <option value="">Payment For</option>
                          <?php
                          $query1 = "SELECT DISTINCT name FROM fees ORDER BY id";
                          $result1 = $con->query($query1);
                          while ($row1 = $result1->fetch_assoc()) {
                            echo "<option value='{$row1['name']}'>{$row1['name']}</option>";
                          }
                          ?>
                        </select>
                      </div>


                    </div>

                    <div class="row">

                      <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" required>
                      </div>

                      <div class="form-group col-md-4">
                        <label for="age">Mode of Payment</label>
                        <input type="text" class="form-control" id="mode" name="mode" placeholder="Mode of Payment" required>
                      </div>

                      <div class="form-group col-md-4">
                        <label for="age">School Bank Account</label>
                        <input type="text" class="form-control" id="account" name="account" placeholder="Bank Account" required>
                      </div>
                      <div class="form-group col-md-4">
                        <label for="age">Sender Name</label>
                        <input type="text" class="form-control" id="sname" name="sname" placeholder="Sender Name" required>
                      </div>

                      <div class="form-group col-md-4">
                        <label for="age">Date of Payment</label>
                        <input type="date" class="form-control" id="date" name="date" placeholder="Date of Payment" required>
                      </div>
                      <div class="form-group col-md-4">
                        <label for="age">Time of Payment</label>
                        <input type="time" class="form-control" id="time" name="time" placeholder="Time of Payment" required>
                      </div>

                      <div class="form-group col-md-4">
                        <label for="age">Form Number</label>
                        <input type="text" class="form-control" id="form" name="form" placeholder="form" required>
                      </div>
                      <div class="form-group col-md-4">
                        <label for="age">Receipt Upload</label>
                        <select type="select" class="form-control" id="upload" name="upload" required>
                          <option value=""></option>
                          <option value="Yes">Yes</option>
                          <option value="No">No</option>
                        </select>
                      </div>
                      <div class="form-group col-md-4">
                        <label for="age">Additional Information</label>
                        <textarea class="form-control" id="addinfo" name="addinfo" placeholder="Type Here....."></textarea>
                      </div>
                      <div class="form-group col-md-4">
                        <label for="age">Rating</label>
                        <input type="text" class="form-control" id="rate" name="rate" placeholder="Rating" required>
                      </div>
                      <div class="form-group col-md-4">
                        <label for="age">Request 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">Any Issue</label>
                        <select type="select" class="form-control" id="issue" name="issue" required>
                          <option value=""></option>
                          <option value="Yes">Yes</option>
                          <option value="No">No</option>
                        </select>
                      </div>

                      <div class="form-group col-md-4">
                        <label for="age">If Yes</label>
                        <textarea class="form-control" id="issue2" name="issue2" placeholder="Type Issue Here....."></textarea>
                      </div>




                    </div>


                    <!-- /.card-body -->
                    <div class="card-footer">
                      <center>
                        <button type="submit" name="submit" id="submit" class="btn btn-primary"><i class="fas fa-check-circle"></i> Request Approval</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, no free-typing
      $('#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
        }
      });

      // Auto-fill fields when a student is selected — stay intact until changed
      $('#fullname').on('select2:select', function(e) {
        var data = e.params.data;
        $('#stdname').val(data.studentName || '');
        $('#class').val(data.class || '');
        $('#school_type').val(data.stream || '');
        $('#email').val(data.email || '');
      });

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

      $('#pay_for').select2();
      $('#session').select2();
      $('#term').select2();
      $('#payment_type').select2();
    });
  </script>
</body>

</html>
