<?php
// api/routes/old_rc_final.php
error_reporting(0);
ini_set('display_errors', 0);
ini_set('pcre.backtrack_limit', '10000000');
ini_set('memory_limit', '512M');

if (!class_exists('\Mpdf\Mpdf')) {
    $autoloadPath = __DIR__ . '/../../libs/vendor/autoload.php';
    if (file_exists($autoloadPath)) {
        require_once $autoloadPath;
    } else {
        require_once __DIR__ . '/../../vendor/autoload.php';
    }
}

// 1. IMAGE HANDLING
$serverRoot = '/home/directse1/print.directservices.in';
$imagePath = $serverRoot . '/assets/templates/oldrc.jpg'; 
$base64Image = file_exists($imagePath) ? 'data:image/jpg;base64,' . base64_encode(file_get_contents($imagePath)) : '';

// 2. DATA MAPPING
$regnNo      = $data['regNo'] ?? '';

// --- 🔥 ADVANCED STATE DETECTION LOGIC ---
$stateList = [
    'AP' => 'Andhra Pradesh', 'AR' => 'Arunachal Pradesh', 'AS' => 'Assam', 'BR' => 'Bihar',
    'CG' => 'Chhattisgarh', 'GA' => 'Goa', 'GJ' => 'Gujarat', 'HR' => 'Haryana',
    'HP' => 'Himachal Pradesh', 'JH' => 'Jharkhand', 'KA' => 'Karnataka', 'KL' => 'Kerala',
    'MP' => 'Madhya Pradesh', 'MH' => 'Maharashtra', 'MN' => 'Manipur', 'ML' => 'Meghalaya',
    'MZ' => 'Mizoram', 'NL' => 'Nagaland', 'OD' => 'Odisha', 'PB' => 'PUNJAB',
    'RJ' => 'Rajasthan', 'SK' => 'Sikkim', 'TN' => 'Tamil Nadu', 'TS' => 'Telangana',
    'TR' => 'Tripura', 'UP' => 'Uttar Pradesh', 'UK' => 'Uttarakhand', 'WB' => 'West Bengal',
    'DL' => 'Delhi', 'JK' => 'Jammu & Kashmir', 'PY' => 'Puducherry'
];

$detectedCode = strtoupper(substr(trim($regnNo), 0, 2));
$fullStateName = "";
$stateCode = $detectedCode;

if (array_key_exists($detectedCode, $stateList)) {
    $fullStateName = $stateList[$detectedCode];
} else {
    $searchString = strtoupper(($data['regAuthority'] ?? '') . ' ' . ($data['state'] ?? ''));
    foreach ($stateList as $code => $name) {
        if (strpos($searchString, strtoupper($name)) !== false) {
            $stateCode = $code;
            $fullStateName = $name;
            break;
        }
    }
}
if (empty($fullStateName)) { $fullStateName = $data['state'] ?? 'India'; }

// Leading zero formatting
$cylRaw      = $data['vehicleCylindersNo'] ?? '01';
$cylinders   = (strlen((string)$cylRaw) == 1) ? "0".$cylRaw : $cylRaw;

$osRaw       = $data['ownerCount'] ?? '01';
$ownerSerial = (strlen((string)$osRaw) == 1) ? "0".$osRaw : $osRaw;

$vehClass    = $data['vehicleClass'] ?? $data['class'] ?? '';
$mfgDate     = $data['monthYearmfg'] ?? $data['vehicleManufacturingMonthYear'] ?? '';
$fuel        = $data['fuel_descr'] ?? $data['type'] ?? '';
$finalAuth   = $data['regAuthority'] ?? '';

$f_size = "15px"; 
$f_bold = "font-weight: 900; text-shadow: 0.3pt 0.3pt 0.1pt #000;"; 

$mpdf = new \Mpdf\Mpdf([
    'fontDir' => array_merge((new \Mpdf\Config\ConfigVariables())->getDefaults()['fontDir'], [$serverRoot . '/assets/fonts']),
    'fontdata' => (new \Mpdf\Config\FontVariables())->getDefaults()['fontdata'] + ['arialn' => ['R' => 'ARIALN.TTF', 'B' => 'ARIALN.TTF']],
    'mode' => 'utf-8', 'format' => [210, 297], 'orientation' => 'P',
    'margin_left' => 0, 'margin_right' => 0, 'margin_top' => 0, 'margin_bottom' => 0,
    'default_font' => 'arialn'
]);

$mpdf->WriteHTML('
    body { font-family: "arialn", sans-serif; text-transform: uppercase; margin:0; padding:0; } 
    .field { position: absolute; z-index: 10; white-space: nowrap !important; display: inline-block; overflow: visible; }
    .no-caps { text-transform: none !important; }
', 1);

$mpdf->WriteHTML('<img src="'.$base64Image.'" style="position:absolute; top:0; left:0; width:210mm; height:297mm; z-index:-1;">', 2);

$htmlFields = '
    <div class="field no-caps" style="top: 6mm; left: 70mm; font-size: 20px; '.$f_bold.' width:100mm;">'.$fullStateName.'</div>
    <div class="field" style="top: 10.2mm; left: 110.5mm; font-size: 16px; '.$f_bold.' width: 30mm;">'.$stateCode.'</div>
    
    <div class="field" style="top: 26.5mm; left: 38.5mm; font-size: 15px; '.$f_bold.' width:35mm;">'.$regnNo.'</div>
    <div class="field" style="top: 26.5mm; left: 72mm; font-size: '.$f_size.'; '.$f_bold.' width:25mm;">'.($data['regDate'] ?? '').'</div>
    <div class="field" style="top: 26.5mm; left: 97mm; font-size: '.$f_size.'; '.$f_bold.' width:25mm;">'.($data['rcExpiryDate'] ?? '').'</div>
    
    <div class="field" style="top: 34.6mm; left: 38.5mm; font-size: '.$f_size.'; '.$f_bold.' width:65mm;">'.($data['chassis'] ?? '').'</div>
    <div class="field" style="top: 44mm; left: 38.5mm; font-size: '.$f_size.'; '.$f_bold.' width:65mm;">'.($data['engine'] ?? '').'</div>
    
    <div class="field" style="top: 52.3mm; left: 38.5mm; font-size: '.$f_size.'; '.$f_bold.' width:70mm;">'.($data['owner'] ?? '').'</div>
    <div class="field" style="top: 34mm; left: 109mm; width: 25mm; font-size: 16px; '.$f_bold.'">'.$ownerSerial.'</div>
    
    <div class="field" style="top: 62mm; left: 6mm; font-size: 15px; '.$f_size.'; '.$f_bold.' width:25mm;">'.$fuel.'</div>
    <div class="field" style="top: 62mm; left: 38.5mm; font-size: '.$f_size.'; '.$f_bold.' width:70mm;">'.($data['ownerFatherName'] ?? '').'</div>
    
    <div class="field" style="top: 72mm; left: 38.5mm; width: 68mm; line-height: 1.1; font-size: 14px; '.$f_bold.' white-space: normal !important;">'.($data['presentAddress'] ?? '').'</div>

    <div class="field" style="top: 95mm; left: 7.3mm; font-size: 16px; '.$f_bold.' width: 20mm;">'.$stateCode.'</div>
    <div class="field" style="top: 98.5mm; left: 37mm; font-size: '.$f_size.'; '.$f_bold.' width:70mm;">'.$vehClass.'</div>
    
    <div class="field" style="top: 108mm; left: 7mm; font-size: 15px; '.$f_bold.' width:30mm;">'.$regnNo.'</div>
    <div class="field" style="top: 108mm; left: 37mm; font-size: 11px; '.$f_size.'; '.$f_bold.' width:70mm;">'.($data['vehicleManufacturerName'] ?? '').'</div>
    
    <div class="field" style="top: 117.5mm; left: 7mm; font-size: '.$f_size.'; '.$f_bold.' width:30mm;">'.$mfgDate.'</div>
    <div class="field" style="top: 117.5mm; left: 37mm; font-size: '.$f_size.'; '.$f_bold.' width:70mm;">'.($data['model'] ?? '').'</div>
    
    <div class="field" style="top: 126mm; left: 7mm; font-size: '.$f_size.'; '.$f_bold.' width:30mm;">'.($data['wheelbase'] ?? '').'</div>
    <div class="field" style="top: 126mm; left: 37mm; font-size: '.$f_size.'; '.$f_bold.' width:70mm;">'.($data['vehicleColour'] ?? '').'</div>
    
    <div class="field" style="top: 135mm; left: 7mm; font-size: '.$f_size.'; '.$f_bold.' width:25mm;">'.($data['vehicleCubicCapacity'] ?? '').'</div>
    <div class="field" style="top: 135mm; left: 37mm; font-size: '.$f_size.'; '.$f_bold.' width:70mm;">'.($data['vehicleCategory'] ?? '').'</div>
    
    <div class="field" style="top: 144mm; left: 7mm; width: 20mm; font-size: 14px; '.$f_bold.'">'.$cylinders.'</div>
    <div class="field" style="top: 144mm; left: 37mm; font-size: 13px; '.$f_bold.' width: 30mm;">'.($data['vehicleSeatCapacity'] ?? '').'</div>
    
    <div class="field" style="top: 153mm; left: 7mm; font-size: 14px; '.$f_size.'; '.$f_bold.' width:25mm;">'.($data['unladenWeight'] ?? '').'</div>
    <div class="field" style="top: 153mm; left: 37mm; font-size: '.$f_size.'; '.$f_bold.' width:30mm;">'.($data['vehicleTaxUpto'] ?? '00/00/0000').'</div>
    
    <div class="field" style="top: 169.8mm; left: 92mm; width: 120mm; text-align: left; font-size: 14px; '.$f_bold.'">'.$finalAuth.'</div>
';

$mpdf->WriteHTML($htmlFields, 2);
$mpdf->Output('Old_RC_'.$regnNo.'.pdf', 'I');