<?php
// api/routes/voter_final.php

// 1. SPEED BOOSTER
error_reporting(0);
ini_set('display_errors', 0);

// =======================================================================
// 🎛️ SUPER CONTROL ROOM (YAHAN SE SAB ADJUST KARO)
// =======================================================================

// --- 1. PHOTO SETTINGS (Passport Size) ---
$Photo_X      = 13.8;  
$Photo_Y      = 53.0;  
$Photo_W      = 20.0;  
$Photo_H      = 27.0;  

// --- 2. VERTICAL EPIC SETTINGS ---
$Vert_EPIC_X    = 90.5; 
$Vert_EPIC_Y    = 19.5; 
$Vert_EPIC_Size = 4.2;  

// --- 3. QR CODES ---
$BigQR_X      = 9.0;   $BigQR_Y      = 114.5;
$BigQR_W      = 44.0;  $BigQR_H      = 44.0;

$SmallQR_X    = 120.5; $SmallQR_Y    = 44.8;
$SmallQR_W    = 21.0;  $SmallQR_H    = 21.0;

// --- 4. TEXT SIZES ---
$EPIC_Top_Size   = 7.0; 
$Labels_Size     = 6.5; 
$Name_Size       = 7.0;
$Father_Size     = 7.0;
$Gender_Size     = 7.0;
$DOB_Size        = 7.0;
$Addr_Size       = 7.0; 
$ERO_Size        = 6.0;
$Date_Size       = 7.0;
$List_Head_Size  = 8.0;
$List_Val_Size   = 8.0;

// --- 5. BOLD SETTINGS ---
$Style_Name      = 'B';
$Style_Father    = 'B';
$Style_Address   = 'B';
$Style_DOB       = '';   // Normal

// =======================================================================


// 1. Load mPDF
if (file_exists(__DIR__ . '/../../libs/vendor/autoload.php')) {
    require_once __DIR__ . '/../../libs/vendor/autoload.php';
} else {
    require_once __DIR__ . '/../../vendor/autoload.php';
}

// 2. Data Mapping (UPDATED TO MATCH YOUR MAIN FILE)
// Hum dono keys check karenge (New vs Old) taaki data miss na ho.

// EPIC No
$voterNo = $data['voterNumber'] ?? $data['epicno'] ?? $data['epic_no'] ?? '';

// Name (votername se match kiya)
$rawName = $data['name'] ?? $data['votername'] ?? '';
$nameEn = ucwords(strtolower($rawName)); 
$nameHi = $data['nameLocal'] ?? $data['namelocal'] ?? '';

// Father Name
$rawFather = $data['fatherName'] ?? $data['fathername'] ?? '';
$fatherEn = ucwords(strtolower($rawFather)); 
$fatherHi = $data['fatherNameLocal'] ?? $data['fathernamelocal'] ?? '';

// Gender & DOB
$gender = $data['gender'] ?? ''; 
$dob = $data['dob'] ?? '';

// Address (fulladdress se match kiya)
$addrEn = $data['address'] ?? $data['fulladdress'] ?? '';
$addrHi = $data['addressLocal'] ?? $data['localaddress'] ?? '';

$downloadDate = $data['downloadDate'] ?? date('d-m-Y');

// Gender Logic
$gVal = $data['gender'] ?? ''; 
$gLoc = $data['genderlocal'] ?? '';
if ($gVal === '000000') $gVal = ''; 
if ($gLoc === '000000') $gLoc = '';
// Agar genderlocal nahi mila, to main file ke 'sexlocal' se check karo
if(empty($gLoc)) { $gLoc = $data['sexlocal'] ?? ''; }
$gender = (!empty($gLoc) && !empty($gVal)) ? "$gLoc / $gVal" : ($gLoc ?: $gVal);

// Bottom Data (Mapping Fixed)
$serialNo = $data['serial_no'] ?? $data['slnoinpart'] ?? ''; // slnoinpart add kiya
$acEn = $data['ac_name'] ?? $data['assconnonm'] ?? '';
$acHi = $data['ac_name_local'] ?? $data['assconnonmlocal'] ?? '';

$partNo = $data['part_no'] ?? $data['partno'] ?? ''; 
$partEn = $data['part_name'] ?? $data['partname'] ?? ''; 
$partHi = $data['part_name_local'] ?? $data['partnamelocal'] ?? '';

// Polling Station (policestation key use ki aapke code se)
$psEn = $data['polling_station'] ?? $data['policestation'] ?? ''; 
$psHi = $data['polling_station_local'] ?? ''; // Local shorcut agar available ho

// 3. Photo Logic (UPDATED)
$photoFile = ''; $photoFileBW = ''; 
// Aapke code me 'imagepathoriginal' use ho raha hai
$rawPhoto = $data['photo'] ?? $data['imagepathoriginal'] ?? '';

$tempPath = __DIR__ . '/../../libs/temp/';
if (!file_exists($tempPath)) { @mkdir($tempPath, 0755, true); }

if (!empty($rawPhoto)) {
    $imgData = null;
    if (strpos($rawPhoto, 'base64') !== false) {
        $parts = explode(',', $rawPhoto);
        $imgData = base64_decode(end($parts));
    } elseif (filter_var($rawPhoto, FILTER_VALIDATE_URL)) {
        $imgData = @file_get_contents($rawPhoto);
    }
    
    if($imgData) {
        $fileName = 'photo_' . time() . rand(100,999);
        $tempFile = $tempPath . $fileName . '.jpg';
        file_put_contents($tempFile, $imgData);
        $photoFile = $tempFile;
        // Ghost Image
        if(function_exists('imagecreatefromstring')) {
            $im = @imagecreatefromstring($imgData);
            if ($im && imageistruecolor($im)) {
                imagefilter($im, IMG_FILTER_GRAYSCALE);
                imagefilter($im, IMG_FILTER_BRIGHTNESS, 20);
                $tempFileBW = $tempPath . $fileName . '_bw.jpg';
                imagejpeg($im, $tempFileBW);
                imagedestroy($im);
                $photoFileBW = $tempFileBW;
            }
        }
    }
}
if(empty($photoFileBW)) { $photoFileBW = $photoFile; }

// 4. mPDF Setup
$mpdf = new \Mpdf\Mpdf([
    'mode' => 'utf-8', 
    'format' => 'A4',
    'margin_left' => 0, 'margin_right' => 0, 'margin_top' => 0, 'margin_bottom' => 0,
    'default_font' => 'freeserif', 
    'useOTL' => 0xFF,    
    'useKashida' => 75,  
    'autoScriptToLang' => true, 
    'autoLangToFont' => true,
]);

// Helpers
function putText($mpdf, $x, $y, $text, $font, $size, $style, $w=0, $align='L') {
    $weight = (strpos((string)$style, 'B') !== false) ? 'bold' : 'normal';
    $textAlign = ($align === 'C') ? 'center' : (($align === 'R') ? 'right' : 'left');
    $styleCSS = "position: absolute; left: {$x}mm; top: {$y}mm; font-family: {$font}; font-size: {$size}pt; font-weight: {$weight}; color: #000; text-align: {$textAlign};";
    if($w > 0) $styleCSS .= " width: {$w}mm; overflow: hidden; white-space: nowrap;";
    $mpdf->WriteHTML("<div style='{$styleCSS}'>{$text}</div>");
}

function putAddressText($mpdf, $x, $y, $w, $h, $text, $font, $size, $style) {
    $weight = (strpos((string)$style, 'B') !== false) ? 'bold' : 'normal';
    $styleCSS = "position: absolute; left: {$x}mm; top: {$y}mm; width: {$w}mm; font-family: {$font}; font-size: {$size}pt; font-weight: {$weight}; line-height: 1.25; text-align: left; overflow: visible;";
    $mpdf->WriteHTML("<div style='{$styleCSS}'>{$text}</div>");
}

function putImage($mpdf, $x, $y, $w, $h, $path) {
    $html = "<div style='position: absolute; left: {$x}mm; top: {$y}mm; width: {$w}mm; height: {$h}mm; z-index: 9999;'>";
    $html .= "<img src='{$path}' width='{$w}mm' height='{$h}mm' style='width: {$w}mm; height: {$h}mm;' />";
    $html .= "</div>";
    $mpdf->WriteHTML($html);
}

// Background
$templatePath = __DIR__ . '/../../assets/templates/voterid.jpg';
if (file_exists($templatePath)) {
    $mpdf->WriteHTML("<div style='position: fixed; left: 0; top: 0; width: 210mm; z-index: -1000;'>
                        <img src='{$templatePath}' style='width: 210mm; height: auto;' />
                      </div>");
}

// ================= FRONT SIDE =================

// EPIC NO
putText($mpdf, 15, 47, $voterNo, 'freeserif', $EPIC_Top_Size, 'B');

// PHOTO
if(!empty($photoFile) && file_exists($photoFile)){ 
    putImage($mpdf, $Photo_X, $Photo_Y, $Photo_W, $Photo_H, $photoFile); 
}

// NAME
putText($mpdf, 36.6, 53.0, "नाम:", 'freeserif', $Labels_Size, '');
putText($mpdf, 42, 53.0, $nameHi, 'freeserif', $Name_Size, $Style_Name);

putText($mpdf, 36.7, 56.8, "Name:", 'helvetica', $Labels_Size, '');
putText($mpdf, 44, 56.8, $nameEn, 'helvetica', $Name_Size, $Style_Name);

// FATHER NAME
putText($mpdf, 36.6, 61.5, "पिता का नाम:", 'freeserif', $Labels_Size, '');
putText($mpdf, 50, 61.5, $fatherHi, 'freeserif', $Father_Size, $Style_Father);

putText($mpdf, 36.8, 64.8, "Father's Name:", 'helvetica', $Labels_Size, '');
putText($mpdf, 54, 64.8, $fatherEn, 'helvetica', $Father_Size, $Style_Father);

// GENDER & DOB
putText($mpdf, 36.6, 68.8, "लिंग / Gender:", 'freeserif', $Labels_Size, '');
putText($mpdf, 51, 68.8, $gender, 'freeserif', $Gender_Size, '');

putText($mpdf, 36.6, 72.5, "जन्म तिथि / आयु:", 'freeserif', $Labels_Size, '');
putText($mpdf, 36.8, 76.2, "Date of Birth / Age:", 'helvetica', $Labels_Size, '');
putText($mpdf, 58, 76.2, $dob, 'helvetica', $DOB_Size, $Style_DOB,50);

// GHOST PHOTO
if(!empty($photoFileBW) && file_exists($photoFileBW)){ 
    putImage($mpdf, 84, 47.2, 10, 14.9, $photoFileBW); 
}

// --- VERTICAL EPIC ---
$mpdf->WriteHTML('
<div style="position: absolute; left: '.$Vert_EPIC_X.'mm; top: '.$Vert_EPIC_Y.'mm; z-index: 9999;">
    <svg width="10mm" height="40mm" viewBox="0 0 30 120">
        <text x="15" y="110" font-family="Helvetica" font-weight="normal" font-size="'.$Vert_EPIC_Size.'" fill="#000000" transform="rotate(-90 15,110)">
            '.$voterNo.'
        </text>
    </svg>
</div>
');


// ================= BACK SIDE =================

$qrCodeUrl = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" . urlencode("EPIC: $voterNo");

// 🟢 SMALL QR
putImage($mpdf, $SmallQR_X, $SmallQR_Y, $SmallQR_W, $SmallQR_H, $qrCodeUrl);

// ADDRESS
// Hindi
$fullAddrHi = "<b>पता:</b> " . $addrHi;
putAddressText($mpdf, 147.9, 34, 54, 20, $fullAddrHi, 'freeserif', $Addr_Size, '');

// English
$fullAddrEn = "<b>Address:</b> " . $addrEn;
putAddressText($mpdf, 147.9, 43.5, 54, 20, $fullAddrEn, 'helvetica', $Addr_Size, '');

// ERO DETAILS
$ac_text_hi = "निर्वाचक रजिस्ट्रीकरण अधिकारी, " . $acHi;
putAddressText($mpdf, 145.9, 63.5, 60, 10, $ac_text_hi, 'freeserif', $ERO_Size, 'B');

$ac_text_en = "Electoral Registration Officer, " . $acEn;
putAddressText($mpdf, 146.1, 66.8, 60, 10, $ac_text_en, 'helvetica', $ERO_Size, 'B');

// DOWNLOAD DATE
putText($mpdf, 146.1, 73.1, "Download Date: " . $downloadDate, 'helvetica', $Date_Size, 'B');

// BACK EPIC NO
putText($mpdf, 122.6, 72.5, $voterNo, 'helvetica', 7, 'B');


// ================= BOTTOM LIST =================

putText($mpdf, 65, 111, "मतदाता पहचान पत्र संख्या / Epic no. :", 'freeserif', $List_Head_Size, '');
putText($mpdf, 127.3, 111, $voterNo, 'helvetica', $List_Val_Size, 'B');

putText($mpdf, 65, 116.9, "मतदाता क्रमांक / Serial No. :", 'freeserif', $List_Head_Size, '');
putText($mpdf, 127.3, 116.9, $serialNo, 'helvetica', $List_Val_Size, 'B',40);

putText($mpdf, 65, 124.5, "विधानसभा निर्वाचन क्षेत्र की संख्या व नाम :", 'freeserif', $List_Head_Size, '');
putText($mpdf, 127.2, 124.5, $acHi, 'freeserif', $List_Val_Size, 'B');

putText($mpdf, 65, 131, "Assembly Constituency No. and Name :", 'helvetica', $List_Head_Size, '');
putText($mpdf, 127.3, 131, $acEn, 'helvetica', $List_Val_Size, 'B');

putText($mpdf, 65, 137, "भाग संख्या व नाम :", 'freeserif', $List_Head_Size, '');
putText($mpdf, 127.3, 137, $partNo . "-" . $partHi, 'freeserif', $List_Val_Size, 'B');

putText($mpdf, 65, 144.4, "Part No. and Name :", 'helvetica', $List_Head_Size, '');
putText($mpdf, 127.3, 144.4, $partNo . "-" . $partEn, 'helvetica', $List_Val_Size, 'B');

putText($mpdf, 64.9, 151.3, "मतदान केंद्र का पता :", 'freeserif', $List_Head_Size, '');
putText($mpdf, 127.3, 151.3, $psHi, 'freeserif', $List_Val_Size, 'B');

putText($mpdf, 65.2, 157.8, "Polling Station Address :", 'helvetica', $List_Head_Size, '');
putText($mpdf, 127.3, 157.8, $psEn, 'helvetica', $List_Val_Size, 'B');

// 🟢 BIG QR
putImage($mpdf, $BigQR_X, $BigQR_Y, $BigQR_W, $BigQR_H, $qrCodeUrl);

// BOTTOM DATE
putText($mpdf, 12.5, 171.5, "Download Date: " . $downloadDate, 'helvetica', 8, 'B');

// OUTPUT
$mpdf->Output('voter_FINAL_' . time() . '.pdf', 'I');

// Clean
if(!empty($photoFile) && strpos($photoFile, 'temp/') !== false && file_exists($photoFile)) { @unlink($photoFile); }
if(!empty($photoFileBW) && strpos($photoFileBW, 'temp/') !== false && file_exists($photoFileBW)) { @unlink($photoFileBW); }
?>