<?php
header('Content-Type: application/json');

$aadhaar_number = $_GET['aadhaar_number'] ?? '';

if (empty($aadhaar_number) || !is_numeric($aadhaar_number) || strlen($aadhaar_number) != 12) {
    echo json_encode([
        'status' => 'failed',
        'message' => 'Invalid Aadhaar number provided.'
    ], JSON_PRETTY_PRINT);
    exit;
}

$api_url = 'https://sso.hp.gov.in/api/ahdRP';

$payload = json_encode([
    'aadhaarNumber' => $aadhaar_number,
    'signal' => (object)[]
]);

$headers = [
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36',
    'Accept: */*',
    'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8',
    'Accept-Encoding: gzip, deflate',
    'Content-Type: application/json',
    'Origin: https://sso.hp.gov.in',
    'Referer: https://sso.hp.gov.in/registration',
    'Cookie: i18next=en-GB',
    'Sec-Fetch-Dest: empty',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Site: same-origin',
    'Priority: u=1, i'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);

if ($curl_error) {
    echo json_encode([
        'status' => 'failed',
        'message' => 'API request failed: ' . $curl_error
    ], JSON_PRETTY_PRINT);
    exit;
}

if ($http_code === 200) {
    $cleaned_response = trim($response, '"');

    if (strpos($cleaned_response, 'PUID') === 0) {
        echo json_encode([
            'status' => 'success',
            'message' => 'Successfully generated One Time Password (OTP).',
            'txn_id' => $cleaned_response
        ], JSON_PRETTY_PRINT);
    } else {
        echo json_encode([
            'status' => 'failed',
            'message' => 'otp send faild',
            'raw_response' => $response
        ], JSON_PRETTY_PRINT);
    }
} else {
    echo json_encode([
        'status' => 'failed',
        'message' => 'Server returned HTTP code: ' . $http_code,
        'raw_response' => $response
    ], JSON_PRETTY_PRINT);
}
?>
