<?php
// api/generate.php
ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL);

if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');
}

$autoloadPaths = [
    '../libs/vendor/autoload.php',
    __DIR__ . '/../libs/vendor/autoload.php',
    '../../libs/vendor/autoload.php',
    __DIR__ . '/../vendor/autoload.php'
];

$foundAutoload = false;
foreach ($autoloadPaths as $path) {
    if (file_exists($path)) {
        require_once $path;
        $foundAutoload = true;
        break;
    }
}

if (!$foundAutoload) {
    die("<h3 style='color:red'>Critical Error: mPDF Library nahi mili!</h3>");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = [];
    if (!empty($_POST) && !isset($_POST['printdata'])) {
        $data = $_POST;
    } 
    elseif (isset($_POST['printdata'])) {
        $inputData = $_POST['printdata'];
        $decodedJson = json_decode($inputData, true);
        if (json_last_error() === JSON_ERROR_NONE && is_array($decodedJson)) {
            $data = $decodedJson;
        } else {
            $decodedBase64 = base64_decode($inputData);
            if ($decodedBase64) {
                $data = json_decode($decodedBase64, true);
            }
        }
    }

    if (empty($data) || !is_array($data)) {
        die("<h3>Error: Data sahi format mein nahi mila.</h3>");
    }

    $serviceType = isset($data['service_type']) ? strtoupper($data['service_type']) : '';
    $routePath = '';

    switch ($serviceType) {
        case 'DL': // 🟢 DL Route Added
            $routePath = __DIR__ . '/routes/dl_final.php';
            break;
        case 'PAN':
            $routePath = __DIR__ . '/routes/pan_final.php';
            break;
        case 'RC_OLD':
            $routePath = __DIR__ . '/routes/old_rc_final.php';
            break;
        case 'RC':
        case 'RC_NEW':
            $routePath = __DIR__ . '/routes/rc_final.php';
            break;
        case 'VOTER':
            $routePath = __DIR__ . '/routes/voter_final.php';
            break;
        default:
            if (isset($data['dl_no'])) {
                $routePath = __DIR__ . '/routes/dl_final.php';
            } elseif (isset($data['pan_no'])) {
                $routePath = __DIR__ . '/routes/pan_final.php';
            } else {
                $routePath = __DIR__ . '/routes/voter_final.php';
            }
            break;
    }
    
    if (file_exists($routePath)) {
        try {
            include($routePath);
        } catch (Exception $e) {
            die("<h3>PDF Error: " . $e->getMessage() . "</h3>");
        }
    } else {
        die("<h3>Error: Route file nahi mili!</h3>");
    }
}
?>