<?php
// api/routes/rc_final.php
error_reporting(0);
ini_set('display_errors', 0);
ini_set('pcre.backtrack_limit', '10000000');

// 1. mPDF Loading logic
if (!class_exists('\Mpdf\Mpdf')) {
    $autoloadPath = __DIR__ . '/../../libs/vendor/autoload.php';
    if (file_exists($autoloadPath)) {
        require_once $autoloadPath;
    } else {
        $autoloadPath2 = __DIR__ . '/../../vendor/autoload.php';
        if (file_exists($autoloadPath2)) {
            require_once $autoloadPath2;
        } else {
            die("Error: mPDF autoload not found.");
        }
    }
}

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

// 3. 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',
    'AN' => 'ANDAMAN AND NICOBAR ISLANDS', 'CH' => 'CHANDIGARH', 'DN' => 'DADRA AND NAGAR HAVELI AND DAMAN AND DIU',
    'DL' => 'DELHI', 'JK' => 'JAMMU AND KASHMIR', 'LA' => 'LADAKH', 'LD' => 'LAKSHADWEEP', 'PY' => 'PUDUCHERRY'
];

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

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

if (empty($fullStateName)) {
    $fullStateName = strtoupper($data['state'] ?? 'INDIA');
    $stateCode = $detectedCode;
}

$authority   = $data['regAuthority'] ?? $data['state'] ?? '';
$regnDt      = $data['regDate'] ?? '';
$validity    = $data['rcExpiryDate'] ?? '';
$ownerSerial = $data['ownerCount'] ?? '';
$chassis     = $data['chassis'] ?? '';
$engine      = $data['engine'] ?? '';
$ownerName   = $data['owner'] ?? '';
$fatherName  = $data['ownerFatherName'] ?? ''; 
$ownership   = $data['ownership_type'] ?? "INDIVIDUAL"; 
$address     = $data['presentAddress'] ?? '';
$fuel        = $data['fuel_descr'] ?? $data['type'] ?? '';
$emission    = $data['normsType'] ?? 'NA';
$vehClass    = $data['vehicleClass'] ?? $data['class'] ?? '';
$maker       = $data['vehicleManufacturerName'] ?? '';
$model       = $data['model'] ?? '';
$color       = $data['vehicleColour'] ?? 'NA';
$bodyType    = $data['bodyType'] ?? 'NA';
$seating     = $data['vehicleSeatCapacity'] ?? '2';
$unladen     = $data['unladenWeight'] ?? '0';
$laden       = $data['grossVehicleWeight'] ?? '0';
$cylinders   = $data['vehicleCylindersNo'] ?? '0';
$cubic       = $data['vehicleCubicCapacity'] ?? '0';
$hp          = $data['horsepower'] ?? '0';
$wheelBase   = $data['wheelbase'] ?? '0';
$mfgDate     = $data['monthYearmfg'] ?? '';
$financier   = $data['rcFinancer'] ?? '';
$issueDate   = $data['header_details']['card_issued_date'] ?? date('d-m-Y');

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

$css = '
    body { font-family: "arialn", sans-serif; color: #000; margin: 0; padding: 0; }
    .field { position: absolute; z-index: 10; font-family: "arialn"; overflow: visible; }
    .p-deep-bold { font-family: "arial"; font-weight: 900; text-shadow: 0.1pt 0.1pt 0.1pt #000; }
    .p-state-name { top: 9mm; left: 50.3mm; width: 60mm; font-size: 9px; text-align: left; }
    .st-code { width: 20mm; font-size: 8.5px; font-weight: bold; font-family: "arial"; }
    .st-front { top: 8.5mm; left: 84.4mm; }
    .st-back { top: 67.8mm; left: 9mm; }
    .p-regn { top: 19mm; left: 21mm; font-size: 8.2px; }
    .p-regn-dt { top: 19mm; left: 37.8mm; font-size: 8.2px; }
    .p-valid { top: 19mm; left: 54.5mm; font-size: 8.2px; }
    .p-serial { top: 17.5mm; left: 80.5mm; font-size: 8.5px; font-weight: bold; }
    .p-chassis { top: 24.5mm; left: 21mm; font-size: 7.5px; }
    .p-engine { top: 29.9mm; left: 21mm; font-size: 7.5px; }
    .p-owner { top: 34.5mm; left: 21mm; font-size: 7.5px; text-transform: uppercase; }
    .p-father { top: 40mm; left: 21mm; font-size: 7.5px; width: 80mm; white-space: nowrap !important; }
    .p-address { top: 50.5mm; left: 21mm; width: 60mm; line-height: 1.1; font-size: 7.5px; white-space: normal; }
    .p-ownership { top: 45mm; left: 21mm; font-size: 7.5px; }
    .p-fuel { top: 53mm; left: 2.5mm; font-size: 7.5px; width: 30mm; white-space: nowrap !important; }
    .p-emission { top: 58.5mm; left: 2.8mm; font-size: 7.5px; width: 30mm; white-space: nowrap !important; }
    .p-class { top: 67.4mm; left: 42mm; font-size: 8px; font-weight: bold; }
    .p-b-regn { top: 76.5mm; left: 2.5mm; font-size: 8.2px; }
    .p-maker { top: 76.5mm; left: 28.5mm; width: 80mm; font-size: 7.5px; }
    .p-model { top: 82.5mm; left: 28.5mm; width: 80mm; font-size: 7.5px; }
    
    /* 🔥 CORRECT WRAPPING FIX */
    /* width 26mm isse "PILLION" niche aa jayega, aur normal line-height rakha hai */
    .p-color { 
        top: 87.5mm; 
        left: 28.5mm; 
        font-size: 6.8px; 
        width: 26mm; 
        white-space: normal !important; 
        line-height: 1.0; 
        display: block;
    }
    
    /* Body type ko 68mm par shift kiya taaki 2-line colour se na takraye */
    .p-body { 
        top: 87.5mm; 
        left: 55mm; 
        font-size: 7.5px; 
        width: 35mm; 
        white-space: nowrap !important; 
    }

    .p-seat { top: 93mm; left: 28.5mm; font-size: 7.5px; width: 15mm; }
    .p-weight { top: 98.4mm; left: 28.5mm; font-size: 7.5px; width: 20mm; } 
    .p-laden { top: 98.4mm; left: 37.0mm; font-size: 7.5px; width: 20mm; } 
    .p-cubic { top: 103.8mm; left: 28.7mm; font-size: 7.5px; width: 20mm; }
    .p-hp { top: 103.8mm; left: 38.7mm; font-size: 7.5px; width: 20mm; }
    .p-wheelbase { top: 103.8mm; left: 62.2mm; font-size: 7.5px; width: 20mm; }
    .p-fin { top: 109mm; left: 28.5mm; width: 80mm; font-size: 7.5px; }
    .p-auth { top: 115mm; right: 205mm; text-align: right; width: 60mm; font-size: 7.5px; }
    .p-mfg { top: 107.8mm; left: 2.6mm; font-size: 7.5px; }
    .p-cyl { top: 111mm; left: 19mm; font-size: 7.5px; width: 15mm; }
';

$htmlBody = '<img src="' . $base64Image . '" style="position:absolute; top:0; left:0; width:100%; height:100%; z-index:-1;">';
$htmlBody .= '
    <div class="field p-state-name p-deep-bold">' . $fullStateName . '</div>
    <div class="field st-code st-front">' . $stateCode . '</div>
    <div class="field st-code st-back">' . $stateCode . '</div>
    <div class="field p-regn p-deep-bold">' . $regnNo . '</div>
    <div class="field p-regn-dt p-deep-bold">' . $regnDt . '</div>
    <div class="field p-valid p-deep-bold">' . $validity . '</div>
    <div class="field p-b-regn p-deep-bold">' . $regnNo . '</div>
    <div class="field p-serial">' . $ownerSerial . '</div>
    <div class="field p-chassis">' . $chassis . '</div>
    <div class="field p-engine">' . $engine . '</div>
    <div class="field p-owner">' . $ownerName . '</div>
    <div class="field p-father">' . $fatherName . '</div>
    <div class="field p-ownership">' . $ownership . '</div>
    <div class="field p-address">' . $address . '</div>
    <div class="field p-fuel">' . $fuel . '</div>
    <div class="field p-emission">' . $emission . '</div>
    <div style="position: absolute; left: 84.8mm; top: 2.0mm; z-index: 9999;">
        <svg width="10mm" height="40mm" viewBox="0 0 30 120">
            <text x="16" y="110" font-family="arial" font-weight="normal" font-size="6.1" fill="#000000" transform="rotate(-90 15,110)">' . $issueDate . '</text>
        </svg>
    </div>
    <div class="field p-class">' . $vehClass . '</div>
    <div class="field p-maker">' . $maker . '</div>
    <div class="field p-model">' . $model . '</div>
    <div class="field p-color">' . $color . '</div>
    <div class="field p-body">/ ' . $bodyType . '</div>
    <div class="field p-seat">' . $seating . '</div>
    <div class="field p-weight">' . $unladen . '</div>
    <div class="field p-laden">/ ' . $laden . '</div>
    <div class="field p-cubic">' . $cubic . '</div>
    <div class="field p-hp">/ ' . $hp . '</div>
    <div class="field p-wheelbase">/ ' . $wheelBase . '</div>
    <div class="field p-fin">' . $financier . '</div>
    <div class="field p-auth">' . $authority . '</div>
    <div class="field p-mfg">' . $mfgDate . '</div>
    <div class="field p-cyl">' . $cylinders . '</div>
';

$mpdf->WriteHTML($css, 1);
$mpdf->WriteHTML($htmlBody, 2);
$mpdf->Output('RC_' . $regnNo . '.pdf', 'I');