<?php
session_start();
require 'includes/db_connect.php';
require 'vendor/autoload.php';
require_once __DIR__ . '/tcpdf/tcpdf.php';



use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

if (class_exists('PHPMailer\PHPMailer\PHPMailer')) {
    echo "PHPMailer loaded successfully!";
} else {
    echo "PHPMailer NOT loaded!";
    exit;
}

// Fetch applicant, confirm payment...
$stmt = $conn->prepare("SELECT * FROM lgid WHERE id=?");
$stmt->bind_param("i", $_GET['id']);
$stmt->execute();
$applicantResult = $stmt->get_result();
$applicant = $applicantResult->fetch_assoc();

// Confirm payment
$conn->query("UPDATE lgid SET payment_status='paid' WHERE id={$applicant['id']}");

// Create certificate
$pdf = new TCPDF(); // THIS WORKS NOW
$pdf->AddPage();
$pdf->SetFont('helvetica','B',16);
$pdf->Cell(0,10,'LGID Certificate',0,1,'C');

// Passport image (if exists)
$passportPath = __DIR__ . '/../uploads/passports/' . $applicant['passport'];
if(file_exists($passportPath)){
    $pdf->Image($passportPath,150,20,40,40);
}

// Save PDF
$certificateFile = __DIR__ . '/../certificates/LGID-'.$applicant['id'].'.pdf';
$pdf->Output($certificateFile,'F');

// Create TCPDF object
$pdf = new TCPDF();
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Local Government');
$pdf->SetTitle('LGID Certificate');
$pdf->SetMargins(20, 20, 20);
$pdf->AddPage();

// Optional border
$pdf->SetDrawColor(0,0,0);
$pdf->Rect(10, 10, 190, 270, 'D');

// Add Passport Image (top-right)
$passportPath = __DIR__ . '/uploads/passports/' . $applicant['passport'];
if (!empty($applicant['passport']) && file_exists($passportPath)) {
    $pdf->Image($passportPath, 150, 20, 40, 40, '', '', '', false, 300);
}

// Certificate Title
$pdf->SetFont('helvetica', 'B', 16);
$pdf->Cell(0, 15, 'LOCAL GOVERNMENT IDENTIFICATION CERTIFICATE', 0, 1, 'C');
$pdf->Ln(10);

// Applicant Details
$pdf->SetFont('helvetica', '', 12);
$html = "
<p><strong>Full Name:</strong> {$applicant['full_name']}</p>
<p><strong>Gender:</strong> {$applicant['gender']}</p>
<p><strong>Date of Birth:</strong> ".date("d M Y", strtotime($applicant['date_of_birth']))."</p>
<p><strong>Phone:</strong> {$applicant['phone']}</p>
<p><strong>LGA:</strong> {$applicant['lga']}</p>
<p><strong>State:</strong> {$applicant['state']}</p>
<p><strong>Certificate No:</strong> LGID-{$applicant['id']}</p>
<p><strong>Date Issued:</strong> ".date("d M Y")."</p>
";

$pdf->writeHTML($html, true, false, true, false, '');

// Save PDF
$pdf->Output($certificateFile, 'F');

// Update DB: mark certificate generated
$conn->query("UPDATE lgid SET certificate_generated='yes' WHERE id={$applicant['id']}");

// 5. Send certificate via email (optional)
try {
    $mail = new PHPMailer(true);
    $mail->isSMTP();
    $mail->Host       = 'smtp.example.com'; // replace with your SMTP
    $mail->SMTPAuth   = true;
    $mail->Username   = 'you@example.com';
    $mail->Password   = 'yourpassword';
    $mail->SMTPSecure = 'tls';
    $mail->Port       = 587;

    $mail->setFrom('you@example.com', 'LGID Admin');
    $mail->addAddress($applicant['email'], $applicant['full_name']);
    $mail->addAttachment($certificateFile);

    $mail->isHTML(true);
    $mail->Subject = 'Your LGID Certificate';
    $mail->Body    = "Dear {$applicant['full_name']},<br><br>Your LGID certificate is attached.<br><br>Regards,<br>LGID Admin";

    $mail->send();
    echo "<div class='alert alert-success'>Payment confirmed, certificate generated, and email sent successfully.</div>";
} catch (Exception $e) {
    echo "<div class='alert alert-danger'>Payment confirmed, certificate generated, but email could not be sent. Mailer Error: {$mail->ErrorInfo}</div>";
}

// Optional: Redirect back to LGID management page
// header("Location: lgid_management.php");
exit;
?>
