<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 1);

// Increase execution time limit for PDF generation
set_time_limit(3000); // 5 minutes
ini_set('memory_limit', '5120M'); // Increase memory limit

require_once '../config.php';
require_once 'dompdf/autoload.inc.php';
use Dompdf\Dompdf;; // Include the Composer autoloader


// Establish the database connection
$connection = mysqli_connect($db_host, $db_user, $db_password, $db_name);
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Get the selected batch ID from the POST variables
$selectedBatchId = $_POST['batch_id']; // Assuming you retrieve the selected batch ID from a form submission
//$selectedBatchId = "20240418155209";

// Get the logged-in user ID from the session
session_start();

// Check if the user is logged in as a system admin
if (!isset($_SESSION['userType']) || $_SESSION['userType'] !== 'member') {
    header('Location: ../indexX.php');
    exit;
}

$loggedInUserId = $_SESSION['id']; // Assuming you have stored the user ID in a session variable
//echo $loggedInUserId;

// Prepare the SQL query with the batch ID and user ID conditions
$query = "SELECT nominee_id, nominee_name, zone_ministry_centre, nominee_code, title, inductionDate FROM NomineeData WHERE batchid = '$selectedBatchId' AND user_id = '$loggedInUserId'";
$result = mysqli_query($connection, $query);

if (!$result) {
    die("Error retrieving data from the database: " . mysqli_error($connection));
}

// Get total count for progress tracking
$totalCount = mysqli_num_rows($result);
mysqli_data_seek($result, 0); // Reset result pointer
$processedCount = 0;

// Create a directory for the user if it doesn't exist
$userDir = 'certificates/' . $loggedInUserId . '/' . $selectedBatchId;
if (!is_dir($userDir)) {
    mkdir($userDir, 0755, true);
}

// Load the certificate template once (outside the loop for efficiency)
$htmlTemplate = file_get_contents(__DIR__ . '/testmine.php');

// Generate certificates
while ($row = mysqli_fetch_assoc($result)) {
    $processedCount++;
    
    // Show progress
    echo "Processing certificate $processedCount of $totalCount: " . $row['nominee_name'] . "<br>";
    flush(); // Force output to browser
    
    try {
        // Date magic
        $dateString = $row['inductionDate'];
        $date = new DateTime($dateString);
        $date4day = $date;
        $formattedDate = $date->format('jS \Day of F Y');

        // Separate the components
        $formattedDate4Day = $date4day->format('jS \D\a\y');
        $day = $date->format('jS'); 
        
        $month = substr($formattedDate, 9, -8);
        $monthName = date('F', strtotime($dateString));
        $year = substr($formattedDate, -4);
        $shortYear = substr($formattedDate, -2);

        // Create a copy of the template for this certificate
        $html = $htmlTemplate;

        // Replace the placeholder fields with actual data
        $html = str_replace('[[nomineename]]', $row['title'].' '.$row['nominee_name'], $html);
        $html = str_replace('[[day]]', $day, $html);
        $html = str_replace('[[month]]', $monthName, $html);
        $html = str_replace('[[year]]', $shortYear, $html);
        $html = str_replace('[[nomineeid]]', $row['nominee_code'], $html);
        $html = str_replace('[[church_zone]]', $row['zone_ministry_centre'], $html);

        // Initialize dompdf with optimized settings
        $dompdf = new Dompdf();
        $dompdf->setPaper('A4', 'portrait');
        
        // Set options for better performance
        $dompdf->getOptions()->set([
            'isRemoteEnabled' => false,
            'isHtml5ParserEnabled' => true,
            'isPhpEnabled' => false,
            'defaultFont' => 'DejaVu Sans'
        ]);

        // Load the HTML content into dompdf
        $dompdf->loadHtml($html);

        // Render the HTML as PDF
        $dompdf->render();

        // Generate the PDF file
        $filename = $userDir . '/certificate_' . $row['nominee_id'] . '.pdf';
        file_put_contents($filename, $dompdf->output());

        // Clear memory
        unset($html);
        unset($dompdf);
        
        // Force garbage collection every 10 certificates
        if ($processedCount % 10 === 0) {
            gc_collect_cycles();
        }
        
    } catch (Exception $e) {
        echo "Error processing certificate for " . $row['nominee_name'] . ": " . $e->getMessage() . "<br>";
        continue; // Continue with next certificate
    }
}

// Close the database connection
mysqli_close($connection);

include('../headerspecial.php');

echo '<h2>Certificate generation complete!</h2>';
//echo '<p><a href="INDUCTION_CERTIFICATE_LOWER_QUALITY.png-2 (1).jpg.zip">Please click here to download the certificates in this batch</a>';
echo '<p><a href="download_certificates.php?bid='.$selectedBatchId.'">Please click here to download the certificates in this batch</a>.';