<?php
require_once 'db_admin.php';
require_once __DIR__ . '/vendor/autoload.php';

ini_set("pcre.backtrack_limit", "10000000");    
ini_set('max_execution_time', 7200); 
ini_set('memory_limit', '-1');

checkLogin();

// --- MODIFICATION 1: FETCH INFO & CHECK CACHE ---

$center_id = $_GET['center_id'] ?? 0;
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 2000;
$offset = isset($_GET['offset']) ? (int)$_GET['offset'] : 0;

// 1. Fetch Center Info FIRST (Moved up so we can use the name)
$cStmt = $conn->prepare("SELECT * FROM vote_centers WHERE id = ?");
$cStmt->execute([$center_id]);
$center = $cStmt->fetch(PDO::FETCH_ASSOC);

if (!$center) die("Center not found");

// 2. Construct Filename
// Calculate Part Number (0=Part1, 2000=Part2)
$part_num = floor($offset / $limit) + 1;

// Sanitize Name: Replace slashes/colons with underscores to prevent errors
// This regex keeps Bangla characters but removes illegal file system characters
$safe_name = preg_replace('/[\\/\\\:*?"<>|]/', '_', $center['center_name'].'-'.$center['gender']);

// Final Name: "CenterName_Part_1.pdf"
$pdf_filename = $safe_name . "_Part_" . $part_num . ".pdf";

$save_dir = __DIR__ . '/pdfs/';
if (!is_dir($save_dir)) mkdir($save_dir, 0755, true);

$file_path = $save_dir . $pdf_filename;

// 3. Check if file exists
if (file_exists($file_path)) {
    // Serve existing file
    header("Content-Type: application/pdf");
    // 'filename' attribute here controls what the user sees when downloading
    header("Content-Disposition: inline; filename=\"{$pdf_filename}\"");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . filesize($file_path));
    readfile($file_path);
    exit(); 
}

// --- END TOP MODIFICATION ---

// 1. Fetch Center Info
$cStmt = $conn->prepare("SELECT * FROM vote_centers WHERE id = ?");
$cStmt->execute([$center_id]);
$center = $cStmt->fetch(PDO::FETCH_ASSOC);

if (!$center) die("Center not found");

// 2. Fetch Voters with LIMIT and OFFSET
$vStmt = $conn->prepare("
    SELECT 
        _pk_id, Id, Serial, Serial_Int, Gender, Name, Voter_No, 
        Husband_Father, Mother, Occupation, DOB_Bangla, Address, 
        Ward_No, Area_Name, Center_Id, Is_Father, Pdf_Information_Id, serial_number
    FROM voters 
    WHERE Center_Id = :cid 
    ORDER BY Serial_Int ASC
    LIMIT :lim OFFSET :off
");

// Bind parameters (PDO requires bindValue for Limit/Offset in some versions)
$vStmt->bindValue(':cid', $center_id, PDO::PARAM_INT);
$vStmt->bindValue(':lim', $limit, PDO::PARAM_INT);
$vStmt->bindValue(':off', $offset, PDO::PARAM_INT);
$vStmt->execute();

$voters = $vStmt->fetchAll(PDO::FETCH_ASSOC);

// If chunk is empty
if (count($voters) == 0) die("No voters found in this range.");


// 3. HTML Structure
$html = '
<style>
    body { font-family: "freeserif", sans-serif; }
    
    .container { width: 100%; }

    /* Main Card Box - 2 per row */
    .card-box {
        width: 47.5%;
        float: left;
        margin-right: 12px;
        margin-bottom: 12px;
        border: 2px solid #000; /* Thicker border like image */
        padding: 5px;
        height: 330px; /* Adjusted height for content */
        max-height: 330px; /* Adjusted height for content */
        min-height: 330px; /* Adjusted height for content */
        box-sizing: border-box;
        overflow: hidden;
        position: relative;
        /* background-image: url("watermark.png"); */ /* Uncomment if you have a watermark */
        background-size: center;
        background-repeat: no-repeat;
    }

    /* Top Small Header (Bangladesh - Bismillah - Jindabad) */
    .top-row { width: 100%; font-size: 10px; margin-bottom: 0px; }
    .top-left { width: 20%; text-align: left; }
    .top-center { width: 60%; text-align: center; }
    .top-right { width: 20%; text-align: right; }

    /* Main Header Title */
    .main-title {
        text-align: center;
        font-size: 22px;
        /*font-weight: bold;*/
        margin-top: -5px;
        margin-bottom: 2px;
    }

    /* Seat Name Pill (Dhaka - 9) */
    .seat-badge {
        background-color: #333; /* Dark grey/black background */
        color: white;
        padding: 3px 15px;
        border-radius: 15px; /* Pill shape */
        font-size: 16px;
        /*font-weight: bold;*/
        display: inline-block;
    }

    /* Voter Slip Badge */
    .slip-badge {
        border: 1px solid #000;
        border-radius: 10px;
        padding: 1px 8px;
        font-size: 17px;
        margin-top: 2px;
        display: inline-block;
        background: #fff;
    }

    /* Layout Table for Content */
    .content-table { width: 100%; margin-top: 5px; border-collapse: collapse; }
    .col-info { width: 75%; vertical-align: top; }
    .col-graphic { width: 25%; vertical-align: top; text-align: center; border-left: 0px dotted #ccc; }

    /* Text Styles */
    .center-info { font-size: 18px; /*font-weight: bold;*/ margin-bottom: 5px; border-bottom: 1px solid #000; }
    .area-info { font-size: 18px; margin-bottom: 8px; margin-bottom: 5px; }
    
    .voter-data { font-size: 16px; line-height: 1.4; }
    .label {  }
    
    /* Right Side Graphic Styles */
    .thana-list {
        font-size: 20px;
        /*font-weight: bold;*/
        line-height: 1.2;
        color: #444;
        margin-top: 5px;
        text-align: center;
    }
    .ballot-img {
        width: 100px;
        height: auto;
    }

    /* Footer */
    .footer-date {
        text-align: center;
        /*font-weight: bold;*/
        font-size: 12px;
        border-top: 1px solid #000;
        margin-top: 5px;
        padding-top: 2px;
    }
    .footer-credit {
        text-align: right;
        font-size: 8px;
        margin-top: 2px;
    }
</style>
<div class="container">
';

$count = 0;
$total_voters = count($voters);
$html .= '<div>';
foreach ($voters as $v) {
    $count++;
    // Logic for Father vs Husband based on Is_Father column
    // Assuming Is_Father: 1 = Father, 0 = Husband (or NULL)
    // If column is Is_Father, usually 1 means Yes (Father). 
    $guardianLabel = ($v['Is_Father'] == 1) ? 'পিতা' : 'স্বামী';
    
    // Address Construction
    $fullAddress = $v['Address']; 

    $gapStyle = ($count % 2 != 0) ? 'margin-right: 4%;' : '';
    $float = ($count % 2 != 0) ? 'float: left;' : 'float: right;';

    $html .= '
    <div class="card-box" style="' . $gapStyle . $float . '">        
        <!-- 1. Top Mini Header -->
        <table class="top-row">
            <tr>
                <!-- <td class="top-left">বাংলাদেশ</td> -->
                <td class="top-center">বিসমিল্লাহির রহমানির রাহিম</td>
                <!-- <td class="top-right">জিন্দাবাদ</td> -->
            </tr>
        </table>

        <!-- 2. Main Titles -->
        <div style="text-align:center;">
            <div class="main-title">ত্রয়োদশ জাতীয় সংসদ নির্বাচন</div>
            <div class="seat-badge">ঢাকা - ৯ আসন</div>
            <div class="slip-badge">ভোটার স্লিপ</div>
        </div>

        <!-- 3. Split Layout: Info vs Image -->
        <table class="content-table">
            <tr>
                <!-- LEFT COLUMN: Voter Info -->
                <td class="col-info">
                    <div class="center-info">কেন্দ্র: ' . $center['center_name'] . '</div>
                    <div class="area-info">
                        এলাকা: ' . $v['Area_Name'] . ' <br> ওয়ার্ড: ' . $v['Ward_No'] . '
                    </div>
                    <div class="voter-data">
                        <!-- Serial is bold and part of the first line -->
                        <span style="font-size: 18px; text-decoration: underline;"> '. $v['Serial'] . '. নাম: ' . $v['Name'] . '</span><br>
                        ভোটার নং: <span style="font-size: 16px; text-decoration: underline;"> ' . $v['Voter_No'] . '</span><br>
                        ' . $guardianLabel . ': ' . $v['Husband_Father'] . '<br>
                        মাতা: ' . $v['Mother'] . '<br>
                        পেশা: ' . str_replace(',','',$v['Occupation']) . ', জন্ম তারিখ: ' . $v['DOB_Bangla'] . '<br>
                        ঠিকানা: ' . $fullAddress . '
                    </div>
                </td>

                <!-- RIGHT COLUMN: Graphic & Thanas -->
                <td class="col-graphic">
                    <!-- Ensure ballot_box.png exists in the admin folder -->
                    <img src="ballot_box.png" class="ballot-img"><br>
                    <div class="thana-list">
                        • সবুজবাগ<br>
                        • খিলগাঁও<br>
                        • মুগদা
                    </div>
                </td>
            </tr>
        </table>

        <!-- 4. Footer -->
        <div class="footer-date">
            নির্বাচনের তারিখ: ১২ ফেব্রুয়ারি, বৃহস্পতিবার
        </div>

    </div>';

    // --- PAGE BREAK LOGIC ---
    // Insert page break after every 4th card, but NOT after the very last card
    if ($count % 2 == 0 && $count < $total_voters) {
        $html .= '</div><div>';
    }
    if ($count % 4 == 0 && $count < $total_voters) {
        $html .= '<pagebreak />';
    }
}
$html .= '</div>';

$html .= '</div>'; // End container

// 4. Generate PDF
$mpdf = new \Mpdf\Mpdf([
    'mode' => 'utf-8', 
    'format' => 'A4-L', // A4 Landscape gives more width for 2 cards side-by-side
    'margin_left' => 10,
    'margin_right' => 10,
    'margin_top' => 5,
    'margin_bottom' => 5
]);

$mpdf->autoScriptToLang = true;
$mpdf->autoLangToFont = true;

$mpdf->WriteHTML($html);
$mpdf->SetTitle(str_replace('.pdf','',$pdf_filename));
$filename = $pdf_filename;
//$mpdf->Output($filename, 'I');


$mpdf->Output($file_path, \Mpdf\Output\Destination::FILE);

if (file_exists($file_path)) {
    echo 'done';
    /*header("Content-Type: application/pdf");
    // Ensure quotes around filename to handle spaces in center names
    header("Content-Disposition: inline; filename=\"{$pdf_filename}\"");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . filesize($file_path));
    readfile($file_path);*/
} else {
    echo "Error generating PDF file.";
}
exit();


?>