<?php
session_start();
ob_start();
include('../includes/config.php');
ob_clean();

mysqli_set_charset($tng_conn, "utf8mb4");


if (isset($_POST['download_pdf']) && isset($_SESSION['voter_pdf_binary'])) {

    $pdfBinary = $_SESSION['voter_pdf_binary'];
    $filename  = $_SESSION['voter_pdf_name'] ?? 'voter.pdf';

    unset($_SESSION['voter_pdf_binary'], $_SESSION['voter_pdf_name']);

    header("Content-Type: application/pdf");
    header("Content-Disposition: attachment; filename=\"$filename\"");
    header("Content-Length: " . strlen($pdfBinary));
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Pragma: no-cache");

    echo $pdfBinary;
    exit;
}


if (!isset($_GET['voterautoid'], $_GET['type'])) {
    die("Missing voterautoid or type");
}

$voterautoid = intval(base64_decode($_GET['voterautoid']));
$type        = base64_decode($_GET['type']);


$q = mysqli_query(
    $tng_conn,
    "SELECT * FROM voterauto1 WHERE voterautoid='$voterautoid' LIMIT 1"
);
if (!$q || mysqli_num_rows($q) == 0) {
    die("No record found");
}
$data = mysqli_fetch_assoc($q);

$postData = [
    "data_base64" => base64_encode(json_encode($data, JSON_UNESCAPED_UNICODE)),
    "type"        => $type
];

$ch = curl_init($voterpdfapi);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $postData
]);
$response  = curl_exec($ch);
$curlError = curl_error($ch);
curl_close($ch);

if ($curlError) {
    die("Curl Error: $curlError");
}

$resData = json_decode($response, true);
if (empty($resData['pdf'])) {
    die("Invalid response from API");
}


$pdfBase64 = preg_replace('/^data:application\/pdf;base64,/', '', $resData['pdf']);
$pdfBinary = base64_decode($pdfBase64);

if ($pdfBinary === false || strlen($pdfBinary) < 100) {
    die("Failed to decode PDF");
}

$filename = preg_replace(
    '/[^a-zA-Z0-9_\-]/',
    '_',
    ($resData['file_name'] ?? "Voter_$voterautoid")
) . ".pdf";


$_SESSION['voter_pdf_binary'] = $pdfBinary;
$_SESSION['voter_pdf_name']   = $filename;
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Voter PDF Ready</title>

<style>
body{
    margin:0;
    height:100vh;
    display:flex;
    align-items:center;
    justify-content:center;
    background:radial-gradient(circle at center,#0f2027,#203a43,#2c5364);
    font-family:Segoe UI,Roboto,sans-serif;
}
.card{
    background:#fff;
    padding:40px;
    border-radius:18px;
    text-align:center;
    box-shadow:0 20px 50px rgba(0,0,0,.35);
    animation:shine 1.8s infinite alternate;
    width:360px;
}
@keyframes shine{
    from{box-shadow:0 15px 35px rgba(0,0,0,.3);}
    to{box-shadow:0 25px 60px rgba(0,0,0,.5);}
}
h2{color:#203a43;margin-bottom:8px;}
p{color:#555;margin-bottom:25px;}
.btn{
    display:block;
    width:100%;
    padding:14px;
    font-size:17px;
    border-radius:50px;
    border:none;
    cursor:pointer;
    margin-bottom:12px;
    transition:.3s;
}
.download{
    background:linear-gradient(45deg,#00c6ff,#0072ff);
    color:#fff;
    box-shadow:0 8px 20px rgba(0,0,0,.3);
}
.download:hover{
    transform:scale(1.05);
    box-shadow:0 14px 30px rgba(0,0,0,.45);
}
.back{
    background:#f1f1f1;
    color:#333;
}
.back:hover{
    background:#e0e0e0;
}
</style>
</head>

<body>

<div class="card">
    <h2>✅ PDF Ready</h2>
    <p>Your Voter PDF is generated successfully</p>

    <!-- DOWNLOAD -->
    <form method="POST">
        <button class="btn download" type="submit" name="download_pdf">
            ⬇ Download PDF
        </button>
    </form>

    <!-- BACK -->
    <button class="btn back" onclick="window.history.back();">
        🔙 Go Back
    </button>
</div>

</body>
</html>
