<?php
session_name('mini_admin_session');
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');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

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

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

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

        $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);
            $email = $fecthemail['email'];
            $id = $fecthemail['id'];
        }

        $mail = new PHPMailer(true);
        try {
          $mail->isSMTP();
          $mail->Host = 'mail.acionlineportal.com.ng';
          $mail->SMTPAuth = true;
          $mail->Username = 'noreply@acionlineportal.com.ng'; // SMTP username
          $mail->Password = 'acionlineportal';          // SMTP password
          $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
          $mail->Port = 465;
          $mail->Timeout = 10;
  
          $mail->setFrom('noreply@acionlineportal.com.ng', 'ADESINA COLLEGE');
            $mail->addAddress($email, $studentname);

            // Email content
            $mail->isHTML(true);
            $mail->Subject = 'ACI School Fees 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>We regret to inform you that your payment of NGN $amount has been disapproved.</p>
                    <p>Kindly bring your transaction receipt to school for verification of your payment.</p>
                    <p>Thank you!</p>
                    <hr>
                    <center>
                        <p>Adesina College Ibadan &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!', 'otherpay1.php');
        header('Location: otherpay1.php'); exit;
        } catch (Exception $e) {
            flash_alert('Email could not be sent. Payment disapproval skipped: ' . $e->getMessage(), 'otherpay1.php');
        header('Location: otherpay1.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'];

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

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

            $mail = new PHPMailer(true);
        try {
          $mail->isSMTP();
          $mail->Host = 'mail.acionlineportal.com.ng';
          $mail->SMTPAuth = true;
          $mail->Username = 'noreply@acionlineportal.com.ng'; // SMTP username
          $mail->Password = 'acionlineportal';          // SMTP password
          $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
          $mail->Port = 465;
          $mail->Timeout = 10;
  
          $mail->setFrom('noreply@acionlineportal.com.ng', 'ADESINA COLLEGE');
                $mail->addAddress($email, $studentname);

                $mail->isHTML(true);
                $mail->Subject = 'ACI OTHER SERVICE 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>
                        <p>Please login to your student portal to download your receipt.</p>
                        <p>Thank you!</p>
                    </div>
                </body>
                </html>";
                                 // Attach PDF 
                                 $boardinglist = ('ACI_BOARDING_LIST.pdf');
                                 if ($payment_for =='Boarding Form' || $payment_for=='boarding form' || $payment_for=='BOARDING FORM'){
                                 $mail->addAttachment($boardinglist, 'ACI_BOARDING_LIST.pdf');
                                 }
                

                $mail->send();

                // 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)
                    VALUES ('$adno', '$studentname', '$term', '$session', '$class', '$school_type', '$payment_type', '$pay_id', '$amount', '$payment_for', '$id')");

                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!', 'otherpay1.php');
        header('Location: otherpay1.php'); exit;
                } else {
                    throw new Exception('Database operation failed.');
                }
            } catch (Exception $e) {
                flash_alert('Email could not be sent. Payment approval skipped: ' . $e->getMessage(), 'otherpay1.php');
        header('Location: otherpay1.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/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">Approve 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="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">Other Services</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">
                    <h3 class="card-title">Other Services</h3>
                  </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"onchange="passValue()" required>
                            <option value=""></option>
                            <?php
                            $result = mysqli_query($con,"SELECT studentno,studentName FROM students");
                            //fecth result
                            while ($row = mysqli_fetch_array($result)) {
                               echo"<option value =".$row['studentno'].">".$row['studentno']."|".$row['studentName']."</option>";
                            }
                            ?>
                          </select>
                        </div>
                        <div class="form-group col-md-4">
                          <label for="age">Stundent'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>
                          <input type="text" class="form-control" id="term" name="term"  value="<?php echo $messageData['term'];?>" required>

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

                          
                        </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">
                            <option></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 >
                          <span  style="font-size: 12px; color: red;" class="hint">Type "Boarding Form" for Boarding form payment</span>
                        </div>

                      </div>
                      <div class = "row">
                      <div class="form-group col-md-4">
                          <label for="age">Amount to Pay</label>
                          <input type="number" class="form-control" id="amount" name="amount" placeholder="Amount" value="<?php echo $messageData['amount'];?>" required >
                        </div>
                              </div>
                   
                      
                    <!-- /.card-body -->
                    <div class="card-footer">
    <center>
        <button type="submit" name="submit" id="submit" class="btn btn-primary">Approve</button>
        <button type="submit" name="disapprove" id="disapprove" class="btn btn-danger">Disapprove</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>
      // In your Javascript (external .js resource or <script> tag)
$(document).ready(function() {
    $('#fullname').select2();
});

function passValue() {
    var value = document.getElementById("fullname").value;
    if (value) {
        // Make an AJAX request to the PHP script
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "fetch_value.php?option=" + encodeURIComponent(value), true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                // Parse the JSON response
                var response = JSON.parse(xhr.responseText);
                // Fill the fields with the returned values
                document.getElementById("stdname").value = response.studentName || ''; // Assuming you also want to fill this field
                document.getElementById("class").value = response.class || '';
                document.getElementById("school_type").value = response.stream || '';
            }
        };
        xhr.send();
    } else {
        document.getElementById("stdname").value = '';
        document.getElementById("class").value = '';
        document.getElementById("school_type").value = '';
        alert('Please select an option.');
    }
}
</script>
  </body>
  </html>
 
