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

require_once '../config.php';
require_once 'tcpdf/tcpdf.php';

//var_dump($_POST);
// 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 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)) {
    //echo $row['nominee_name'];
    //date magic
    $dateString = '2024-10-02';
    $date = new DateTime($dateString);
    $formattedDate = $date->format('jS \Day of F Y');

    // Separate the components
    $day = substr($formattedDate, 0, 2);
    $month = substr($formattedDate, 9, -8);
    $year = substr($formattedDate, -4);
    $shortYear = substr($formattedDate, -2);

/**
echo "Day: " . $day . "\n";
    echo "Month: " . $month . "\n";
    echo "Year (4 digits): " . $year . "\n";
    echo "Year (2 digits): " . $shortYear . "\n";
    **/


    // Create a new PDF document
    $pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8');

    // Set document information and meta tags
    $pdf->SetCreator('Your Organization');
    $pdf->SetAuthor('Your Organization');
    $pdf->SetTitle('Certificate');
    $pdf->SetSubject('Certificate for ' . $row['nominee_name']);

    // Add a page to the PDF
    $pdf->AddPage();

    // Customize the certificate layout using HTML and CSS
  /**  $html = '
        <style>
        </style>
        <h1>Certificate of Achievement</h1>
        <p>This is to certify that ' . $row['nominee_name'] . ' has been nominated from ' . $row['zone_ministry_centre'] . '.</p>
        <!-- Add more HTML content specific to the certificate -->
    ';**/

     // Load the certificate template
     //$template = file_get_contents(__DIR__.'/cert/certhtml.html');
     //$template = file_get_contents(__DIR__.'/cert/certsimplified.html');
	 $template = file_get_contents(__DIR__.'/cert/testmine2.php');
     //$template = htmlentities($template0);

     // Replace the placeholder fields with actual data
    $html = str_replace('[[nomineename]]', $row['nominee_name'], $template);
    $html = str_replace('[[day]]', $day, $html);
    $html = str_replace('[[month]]', $month, $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;



//echo $html;
// Open the PDF
$pdf->open();

    // Write the HTML content to the PDF
    $pdf->writeHTML($html, true, false, true, false, '');

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

    // Save the PDF file
    $filename = $userDir . '/certificate_' . $row['nominee_id'] . '.pdf';
    $pdf->Output($filename, 'F');

    // Check for errors
// Check for errors
if($pdf->Error) {
  echo 'Error: ' . $pdf->getError();
}

    // Clear the PDF object to generate the next certificate
    unset($pdf);
}

// 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>.'
?>
