<?php
session_name('mini_admin_session');
session_start();
include('includes/dbconnection.php');
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'];
// Function to strictly validate date format (YYYY-MM-DD)
function validateDate($date, $format = 'Y-m-d') {
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) === $date;
}

// Get raw inputs (sanitize later after validation)
$start_date_raw = $_GET['start_date'] ?? '';
$end_date_raw = $_GET['end_date'] ?? '';

// Validate presence
if (empty($start_date_raw) || empty($end_date_raw)) {
    die("Start date and end date are required.");
}

// Validate format strictly
if (!validateDate($start_date_raw) || !validateDate($end_date_raw)) {
    die("Invalid date format. Please use YYYY-MM-DD.");
}

// Dates are valid, sanitize for safety (optional since validated)
$start_date = filter_var($start_date_raw, FILTER_SANITIZE_STRING);
$end_date = filter_var($end_date_raw, FILTER_SANITIZE_STRING);

// Prepare the query with ORDER BY before binding
$query = "SELECT * FROM initiate_payment WHERE DATE(payment_date) BETWEEN ? AND ? ORDER BY payment_date DESC";

$stmt = $con->prepare($query);
if (!$stmt) {
    die("Query preparation failed: " . $con->error);
}

$stmt->bind_param('ss', $start_date, $end_date);

if (!$stmt->execute()) {
    die("Query execution failed: " . $stmt->error);
}

$result = $stmt->get_result();


// Generate the HTML content for the PDF
$html = "
<style>
    table { width: 100%; border-collapse: collapse; font-size: 12px; }
    th, td { padding: 8px; text-align: left; }
    th { background-color: #007bff; color: white; }
    tr:nth-child(even) { background-color: #f9f9f9; }
    .text-center { text-align: center; }
</style>
<div class='text-center'>
    <img src=$logo alt='logo' width='70' height='70'><br>
    <h1>$school_name</h1>
    <b><i>$school_address</i></b><br>
    <hr>
    Web Payment Initialization Log from $start_date to $end_date
   
</div>
<hr>
<table border='1'>
    <thead>
        <tr>
            <th>#</th>
            <th>Admission No.</th>
            <th>Student Name</th>
            <th>Email</th>
            <th>Class</th>
            <th>Payment For</th>
            <th>Amount</th>
            <th>Payment Date</th>
        </tr>
    </thead>
    <tbody>";

$cnt = 1;
$total_amount = 0;

while ($row = $result->fetch_assoc()) {
    $total_amount += $row['amount'];
    $html .= "<tr>
                <td>" . $cnt . "</td>
                <td>" . htmlentities($row['studentno']) . "</td>
                <td>" . htmlentities($row['studentName']) . "</td>
                <td>" . htmlentities($row['email']) . "</td>
                <td>" . htmlentities($row['class']) . "</td>
                <td>" . htmlentities($row['fee_type']) . "</td>
                <td>" . number_format($row['amount'], 2) . "</td>
                <td>" . date("M d, Y H:i A", strtotime($row['payment_date'])) . "</td>
              </tr>";
    $cnt++;
}

if ($cnt == 1) {
    $html .= "<tr><td colspan='8' style='text-align: center;'>No records found for the selected date range.</td></tr>";
} 
$html .= "</tbody>
</table>";

// Initialize mPDF and generate the PDF
$mpdf = new Mpdf();
$mpdf->SetHeader($school_name.'||Payment History');
$mpdf->SetFooter('Generated on ' . date("M d, Y H:i A") . '||Page {PAGENO}');
$mpdf->WriteHTML($html);
$mpdf->Output('payment_initialization_log.pdf', 'D');

?>