<?php
include('includes/session.php');
error_reporting(0);
include('includes/dbconnection.php');

// Include the mPDF library
require_once __DIR__ . '/vendor/autoload.php'; // Adjust the path if necessary
// Include the PHP QR Code library
include('phpqrcode/qrlib.php'); // Adjust path as needed

require_once('vendor/autoload.php'); // Include mPDF

use Mpdf\Mpdf;

use Dotenv\Dotenv;

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

$school_name = $_ENV['SCHOOL_NAME'];
$school_address = $_ENV['SCHOOL_ADDRESS'];
$logo = $_ENV['WEBSITE_LOGO'];
$prefix = $_ENV['Admission_prefix'];

// Function to convert numbers to words
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;
}

// Check if pay_id is set
if (isset($_GET['id'])) {
    $pay_id = $_GET['id'];

    // Retrieve payment details
    $ret2 = mysqli_query($con, "SELECT * FROM payment WHERE id='$pay_id'");
    if (!$ret2) {
        die("Database query failed: " . mysqli_error($con));
    }

    $row = mysqli_fetch_array($ret2);

    if ($row) {
        // Convert amount to words
        $amountInWords = convertAmountToWords($row['amount']);
        $discountUsed = $row['discount_used'] ?? 'No';
        $discountAmount = $row['discount_amount'] ?? 0;
        $discountPercent = $row['discount_percent'] ?? 0;

        // Generate the QR code with payment information
        $qrContent = 'Student Name: ' . $row['studentName'] . "\n" .
            'Receipt No: R0000' . $row['id'] . "\n" .
            'Amount Paid: ' . number_format($row['amount']) . "\n" .
            'Payment For: ' . $row['pay_for'] . "\n" .
            'Term: ' . $row['Term'] . "\n" .
            'Session: ' . $row['session'] . "\n" .
            'Payment Date: ' . $row['payment_date'];
        $qrFile = 'qrcodes/payment_' . $row['id'] . '.png';
        QRcode::png($qrContent, $qrFile, QR_ECLEVEL_L, 4); // Adjust size if needed

        // Create new mPDF instance
        $mpdf = new \Mpdf\Mpdf();

        // Set the watermark image
        $mpdf->SetWatermarkImage($logo, 0.1);
        $mpdf->showWatermarkImage = true;

        // Build the HTML content with QR code
        $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>' . strtoupper($school_name) . '</h1>
            <b><i>' . $school_address . '</i></b><br>
            <img src=' . $logo . ' alt="logo" width ="80" height ="100"><br>
            <hr>
            <strong>Receipt</strong>
        </div>
        <hr>
         <!-- Details Section -->
    <div class="details">
        <div class="child">
        <div class="left"> <p>Student Name: <strong>' . htmlspecialchars($row['studentName']) . '</strong></p>
                <p>Receipt No: <strong>R0000' . htmlspecialchars($row['id']) . '</strong></p>
                <p>Class: <strong>' . htmlspecialchars($row['class']) . '-' . htmlspecialchars($row['section']) . '</strong></p>
                <p>Payment Status: <strong>Approved</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>' . htmlspecialchars($row['studentName']) . '</strong> </p><br><p>The sum of <strong>NGN' . number_format($row['amount']) . '</strong> (<strong>' . ucwords($amountInWords) . ' Naira only</strong>)</p><br>
                        <p>Being paid for <strong>' . htmlspecialchars($row['pay_for']) . '</strong> </p><br>
                        <p>Term: <strong>' . htmlspecialchars($row['Term']) . '</strong></p><br>
                        <p>Session: <strong>' . htmlspecialchars($row['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>' . date('d-m-Y', strtotime($row['payment_date'])) . '</strong></td>
                            </tr>
                            <tr>
                                <td><strong>Time</strong></td>
                                <td class="text-right"><strong>' . date('H:i:s', strtotime($row['payment_date'])) . '</strong></td>
                            </tr>';

        if ($discountUsed === 'Yes') {
            $html .= '
                            <tr>
                                <td><strong>Original Amount</strong></td>
                                <td class="text-right"><strong>' . number_format($row['amount'], 2)  . '</strong></td>
                            </tr>
                            <tr>
                                <td><strong>Discount (' . $discountPercent . '%)</strong></td>
                                <td class="text-right"><strong> ' . number_format($discountAmount, 2) . '</strong></td>
                            </tr>
                            <tr>
                                <th>Amount Paid (NGN)</th>
                                <th class="text-right"><strong>' . number_format($row['amount'] - $discountAmount, 2) . '</strong></th>
                            </tr>';
        } else {
            $html .= '
            <tr>
                <th>Amount Paid (NGN)</th>
                <th class="text-right"><strong>' . number_format($row['amount'], 2) . '</strong></th>
            </tr>';
        }

        $html .= '
        </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">';
        if ($discountUsed === 'Yes') {
            $html .= '<em style="font-size: 11px; color: #555;">Note: This payment includes an approved discount.</em><br>';
        }
        $html .= '
                        <hr>
                        <strong>' . $school_name . ' &copy; ' . date("Y") . '</strong><br>';

        $html .= '<hr>
            </div>';
        $html .= '
        </div>
        <body>';

        // Write the HTML to the PDF
        $mpdf->WriteHTML($html);

        // Output the PDF to the browser
        $mpdf->Output('receipt_' . htmlspecialchars($row['studentno']) . '.pdf', 'D'); // D for download

        // Optionally delete the QR code image after PDF generation
        unlink($qrFile);
    } else {
        echo "No payment found.";
    }
} else {
    echo "Invalid request.";
}
