<?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');
include('includes/flash.php');

require_once 'vendor/autoload.php'; // Load Composer's autoloader for mPDF
require_once __DIR__ . '/vendor/autoload.php'; // Adjust the path if necessary
// Include the PHP QR Code library
include('phpqrcode/qrlib.php'); // Adjust path as neede

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Mpdf\Mpdf; // Import the mPDF class

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

function convertAmountToWords($number) {
  $hyphen      = '-';
  $conjunction = ' and ';
  $separator   = ', ';
  $negative    = 'negative ';
  $decimal     = ' point ';
  $dictionary  = array(
      0 => 'Zero',
      1 => 'One',
      2 => 'Two',
      3 => 'Three',
      4 => 'Four',
      5 => 'Five',
      6 => 'Six',
      7 => 'Seven',
      8 => 'Eight',
      9 => 'Nine',
      10 => 'Ten',
      11 => 'Eleven',
      12 => 'Twelve',
      13 => 'Thirteen',
      14 => 'Fourteen',
      15 => 'Fifteen',
      16 => 'Sixteen',
      17 => 'Seventeen',
      18 => 'Eighteen',
      19 => 'Nineteen',
      20 => 'Twenty',
      30 => 'Thirty',
      40 => 'Forty',
      50 => 'Fifty',
      60 => 'Sixty',
      70 => 'Seventy',
      80 => 'Eighty',
      90 => 'ninety',
      100 => 'Hundred',
      1000 => 'Thousand',
      1000000 => 'Million',
      1000000000 => 'Billion'
  );

  if (!is_numeric($number)) {
      return false;
  }

  if ($number < 0) {
      return $negative . convertAmountToWords(abs($number));
  }

  $string = $fraction = null;

  if (strpos((string)$number, '.') !== false) {
      list($number, $fraction) = explode('.', (string)$number);
  }

  switch (true) {
      case $number < 21:
          $string = $dictionary[$number];
          break;
      case $number < 100:
          $tens   = ((int) ($number / 10)) * 10;
          $units  = $number % 10;
          $string = $dictionary[$tens];
          if ($units) {
              $string .= $hyphen . $dictionary[$units];
          }
          break;
      case $number < 1000:
          $hundreds  = (int) ($number / 100);
          $remainder = $number % 100;
          $string = $dictionary[$hundreds] . ' ' . $dictionary[100];
          if ($remainder) {
              $string .= $conjunction . convertAmountToWords($remainder);
          }
          break;
      default:
          $baseUnit = pow(1000, floor(log($number, 1000)));
          $numBaseUnits = (int) ($number / $baseUnit);
          $remainder = $number % $baseUnit;
          $string = convertAmountToWords($numBaseUnits) . ' ' . $dictionary[$baseUnit];
          if ($remainder) {
              $string .= $remainder < 100 ? $conjunction : $separator;
              $string .= convertAmountToWords($remainder);
          }
          break;
  }

  if ($fraction !== null && is_numeric($fraction)) {
      $string .= $decimal;
      $words = array();
      foreach (str_split((string) $fraction) as $digit) {
          $words[] = $dictionary[$digit];
      }
      $string .= implode(' ', $words);
  }

  return $string;
}

$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['fullname'];
    $email = $_POST['email'];

    try {
        // Update the message status to 'disapproved' (set status = 2, assuming 2 indicates disapproval)
        $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();

        // Notify user via email about disapproval
        $mail = new PHPMailer(true);
        try {
            // SMTP configuration
            $mail->isSMTP();
            $mail->Host = 'smtp.gmail.com';
            $mail->SMTPAuth = true;
            $mail->Username   = 'popkotconsultancy@gmail.com'; // SMTP username
            $mail->Password   = 'vfogygdfuuksdxbj';    // SMTP password
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port = 465;
            $mail->Timeout = 10;

            // Recipients
            $mail->setFrom('popkotconsultancy@gmail.com', 'Adesina College');
            $mail->addAddress($email, $studentname);

            $mail->isHTML(true);
            $mail->Subject = 'ACI 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();
            flash_alert('Payment disapproved and Email sent successfully!', 'entrancepay2.php');
        header('Location: entrancepay2.php'); exit;
        } catch (Exception $e) {
            flash_alert('Payment disapproved, but email could not be sent. Please try again.', 'entrancepay2.php');
        header('Location: entrancepay2.php'); exit;
        }
    } catch (Exception $e) {
        flash_alert('Something went wrong. Payment disapproval failed. Please try again.');
    }
}
 
  if (isset($_POST['submit'])) {
    $adno = $_POST['fullname'];
    $regno = $_POST['email'];
    $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['fullname'];
    $email = $_POST['email'];

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

    if ($query) {

        $payment_date = date('Y-m-d');
        $payment_time = date('H:i:s');
      $qrContent = 'Student Name: ' . $studentname ."\n" .
      'Receipt No: 000' . $pay_id. "\n" .
      'Amount Paid: ' . number_format($amount) . "\n" .
      'Payment For: ' . $pay_for . "\n" .
      'Term: ' . $Term. "\n" .
      'Session: ' . $session. "\n" .
      'Payment Date: ' . $payment_date;
      $qrFile = 'qrcodes/payment_' . $studentname. '.png';
      QRcode::png($qrContent, $qrFile, QR_ECLEVEL_L, 4); // Adjust size if needed

      $amountInWords = convertAmountToWords($amount);
      
      // Update message status using the passed id
      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();
    }


        // Generate PDF receipt
        $mpdf = new Mpdf();
         // Set the watermark image
         $mpdf->SetWatermarkImage('company/logo1.jpeg', 0.1); // 0.1 for light opacity, 'F' for fit to page
         $mpdf->showWatermarkImage = true;
        $html = "
             <style>
     body {
        font-family: Times New Roman, serif;
        margin: 0;
        padding: 0;
    }
        .details {
     
       
        width: 100%;
    
    }
    .child{
    float: left;
    width: 50%;
    
    }
    .left {
    margin-left: 100%;

        font-size: 14px;
        font-weight: bold;
    }
         .right {
    margin-left: 50%;
    
        font-size: 14px;
        font-weight: bold;
    }
        .text-center {
            text-align: center;
        }
        .text-right {
            text-align: right;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        table, th, td {
            border: 1px solid black;
        }
        th, td {
            padding: 8px;
            font-size: 12px;
            text-align: left;
        }
        p {
            margin: 5px 0;
            font-size: 12px;
        }
        .header, .footer {
            font-size: 14px;
        }
        .flex-container {
            display: flex;
            justify-content: space-between;
            width: 100%;
        }
        .flex-container > div {
            width: 45%; /* Adjust as needed */
        }
        .qr-code {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-left: 20px; /* Space between the text and QR code */
        }
    </style>
    <body>
    <div class='text-center header'>
        <h1>ADESINA COLLEGE, IBADAN</h1>
    <b><i> 2, Kolawole Ajadi Crescent, Alagbayun, Akobo, Ibadan<br>
    www.adesinacollegeibadanonline.com<br>08055481880, 08023240174</i></b><br>
    <img src='company/logo.jpeg' alt='logo' width ='70' height ='70'><br>
        <hr>
        <strong>Receipt</strong>
    </div>
    <hr>
     <!-- Details Section -->
<div class='details'>
<div class='child'>
    <div class='left'> <p>Student Name: <strong>$adno</strong></p>
            <p>Transaction ID: <strong>$pay_id</strong></p>
            <p>Class: <strong>$class</strong></p>
            <p>Payment Status: <strong>Paid</strong></p>
            </div>
    </div>
    <div class='child'>
    <div class='right'><img src='$qrFile'alt='QR Code' width='100' height='100'></div>
</div>
</div>

    <hr>
    <div>
        <p class='text-center'><strong>Payment Summary</strong></p>
        <table>
            <tr>
                <th>Fee Details</th>
                <th>Payment Details</th>
            </tr>
            <tr>
                <td>
                    <p>Payment Received from <strong>$adno</strong> </p><br><p>The sum of <strong>NGN $amount</strong> (<strong> $amountInWords Naira only.</strong>)</p><br>
                    <p>Being paid for <strong>$payment_for</strong> </p><br>
                    <p>Term: <strong>$term</strong></p><br>
                    <p>Session: <strong>$session</strong> academic session.</p><br>
                    
                </td>
                <td>
                    <table style='width: 100%; border-collapse: collapse;'>
                        <tr>
                            <td><strong>Date</strong></td>
                             <td class='text-right'><strong>$payment_date</strong></td>
                            
                        </tr>
                        <tr>
                                <td><strong>Time</strong></td>
                                <td class='text-right'><strong>$payment_time</strong></td>
                        </tr>
                        <tr>
                            <th>Amount (NGN)</th>
                            <th class='text-right'><strong>".number_format($amount)."</strong></th>
                        </tr>
                        
                    </table>
                </td>
            </tr>
            <tr>
                <td>
                <center>
                <em> Thank you for your payment</em>
                </center>
                </td>
                <td class ='text-right'>
                <center>
                <em>No Refund Policy</em>
                </center>
                </td>
                </tr>
        </table>
        <div class='text-center footer'>
            <hr>
            <strong>Adesina College Ibadan &copy; " . date('Y') . "</strong>
            <hr>
        </div>
    </div>
    <body>";
    $mpdf->WriteHTML($html);
    $pdfContent = $mpdf->Output('', 'S'); // Output to string (do not save to file)



        // Send Email Notification
        $mail = new PHPMailer(true);
        try {
            // SMTP configuration
            $mail->isSMTP();
            $mail->Host = 'smtp.gmail.com';
            $mail->SMTPAuth = true;
            $mail->Username   = 'popkotconsultancy@gmail.com'; // SMTP username
            $mail->Password   = 'vfogygdfuuksdxbj';    // SMTP password
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port = 465;
            $mail->Timeout = 10;

            // Recipients
            $mail->setFrom('popkotconsultancy@gmail.com', 'Adesina College');
         $mail->addAddress($email, $studentname);

         // Email content
         $mail->isHTML(true);
         $mail->Subject = '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 find your receipt attached.</p>
                 <p>Thank you!</p>
                 <hr>
                 <p>If you have any questions or need further assistance, please feel free to reach out to us. Thank you!</p>
                                <hr>
                                <center>
                            <p>Adesina College Ibadan &copy; " . date("Y") . ". All Rights Reserved.</p>
                                </center>
                 <hr>
             </div>
         </body>
         </html>";

         // Attach PDF receipt
         $mail->addStringAttachment($pdfContent, 'receipt.pdf', 'base64', 'application/pdf');

        
            $mail->send();
            unset($_SESSION['id']);
            unset($_SESSION['message_data']);
            flash_alert('Payment approved and Email sent successfully!', 'entrancepay2.php');
        header('Location: entrancepay2.php'); exit;
        } catch (Exception $e) {
            flash_alert('Payment approved, but email could not be sent. Please try again.', 'entrancepay2.php');
        header('Location: entrancepay2.php'); exit;
        }
    } else {
        flash_alert('Something went wrong. Payment was not approved. 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/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">
          <div class="container-fluid">
            <div class="row mb-2">
              <div class="col-sm-6">
              </div>
              <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                  <li class="breadcrumb-item"><a href="approve.php">Approve Payment</a></li>
                  <li class="breadcrumb-item active">Certificate / Testimonial</li>
                </ol>
              </div>
            </div>
          </div><!-- /.container-fluid -->
        </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">Pay Certificate / Testimonial Fees</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">Student's Fullname</label>
                          <input type="text" class="form-control" id="fullname" name="fullname"  value="<?php echo $messageData['fullname']; ?>" required >
                        </div>
                        <div class="form-group col-md-4">
                          <label for="sex">Email</label>
                          <input type="text" class="form-control" id="email" name="email"  value="<?php echo $messageData['regno']; ?>" required >
                        </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>
                      <div class="row">
                      <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="sex">Session Graduated</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">School Type</label>
                          <input type="text" class="form-control" id="school_type" name="school_type"  value="Nil" required >
                        </div>

                        
                        
                      </div>
                      <div class="row">
                      <div class="form-group col-md-4">
                          <label for="age">Payment Type</label>
                          <input type="text" class="form-control" id="payment_type" name="payment_type" value ="Full Payment"  required>
                        </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">Amount Paid</label>
                          <input type="number" class="form-control" id="amount" name="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"); ?>
   
  </body>
  </html>
