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

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));
}

// Generate certificates
while ($row = mysqli_fetch_assoc($result)) {
    // Date magic
    //$dateString = '2024-10-02';
	$dateString = $row['title'];
    $date = new DateTime($dateString);
    $formattedDate = $date->format('jS \Day of F Y');

    // Separate the components
    $day = substr($formattedDate, 0, 3);
    $month = substr($formattedDate, 9, -8);
    $monthName = date('F', strtotime($dateString));

    echo $monthName;
    $year = substr($formattedDate, -4);
    $shortYear = substr($formattedDate, -2);

    // Load the certificate template
    $html = file_get_contents(__DIR__ . '/testmine.php');

    // 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);
	
	//echo $html;

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

    // Initialize dompdf
    $dompdf = new Dompdf();
    $dompdf->setPaper('A4', 'portrait');


    // 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 the HTML content
    unset($html);
    unset($dompdf);
}

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