<?php
require 'includes/db_connect.php';
require 'tcpdf/tcpdf.php';
require 'includes/PHPMailer/PHPMailerAutoload.php';

$id = intval($_GET['id']);
$reference = $_GET['reference'] ?? '';

// Verify payment with Paystack API
$secret_key = "YOUR_SECRET_KEY";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.paystack.co/transaction/verify/".$reference);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer ".$secret_key
]);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);

if($result['status'] && $result['data']['status'] == 'success'){
    // Payment confirmed
    $conn->query("UPDATE lgid_applications SET payment_status='paid' WHERE id=$id");
    $row = $conn->query("SELECT * FROM lgid_applications WHERE id=$id")->fetch_assoc();

    // Generate PDF
    $pdf = new TCPDF();
    $pdf->AddPage();
    $html = "
        <h1 style='color:#f57c00;text-align:center;'>Local Government ID</h1>
        <p><strong>Full Name:</strong> {$row['full_name']}</p>
        <p><strong>Email:</strong> {$row['email']}</p>
        <p><strong>Phone:</strong> {$row['phone']}</p>
        <p><strong>LGID Number:</strong> LGID-".str_pad($id,5,'0',STR_PAD_LEFT)."</p>
    ";
    $pdf->writeHTML($html, true, false, true, false, '');
    $file_path = "certificates/LGID-".$id.".pdf";
    $pdf->Output($file_path, 'F');

    // Send email
    $mail = new PHPMailer;
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your@email.com';
    $mail->Password = 'yourpassword';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    $mail->setFrom('admin@localgov.com','Local Government Admin');
    $mail->addAddress($row['email']);
    $mail->Subject = 'Your Local Government ID';
    $mail->Body = "Dear {$row['full_name']},\n\nYour Local Government ID certificate is attached.";
    $mail->addAttachment($file_path);

    $mail->send();

    header("Location: lgid_dashboard.php?success=1");
    exit;
}else{
    die("Payment verification failed. Please contact support.");
}
?>
