<?php
/**
 * Nabeh Integration — Driver Status Check
 *
 * Called by Nabeh AI platform to check driver registration/activation status.
 */

require_once __DIR__ . '/../core/bootstrap.php';

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-API-Key');

$apiKey = $_SERVER['HTTP_X_API_KEY'] ?? '';
$expectedKey = getenv('NABEH_API_KEY') ?: '';

if (empty($apiKey) || $apiKey !== $expectedKey) {
    http_response_code(401);
    echo json_encode(['status' => 'failure', 'message' => 'Unauthorized']);
    exit;
}

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

if (empty($phone)) {
    http_response_code(400);
    echo json_encode(['status' => 'failure', 'message' => 'Phone parameter required']);
    exit;
}

try {
    $db = Database::get('main');
    global $encryptionHelper;

    $encryptedPhone = $encryptionHelper->encryptData($phone);

    $stmt = $db->prepare("
        SELECT d.id, d.phone, d.first_name, d.last_name, d.status, d.created_at,
               cr.id as car_id, cr.make, cr.model, cr.year, cr.car_plate, cr.status as car_status
        FROM driver d
        LEFT JOIN CarRegistration cr ON cr.driverID = d.id
        WHERE d.phone = :phone
        LIMIT 1
    ");
    $stmt->execute([
        ':phone' => $encryptedPhone,
    ]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$result) {
        echo json_encode([
            'status' => 'success',
            'data' => null,
            'message' => 'Driver not found'
        ]);
        exit;
    }

    $decryptedPhone = $encryptionHelper->decryptData($result['phone']);
    $decryptedFirstName = $encryptionHelper->decryptData($result['first_name']);
    $decryptedLastName = $encryptionHelper->decryptData($result['last_name']);

    $docStmt = $db->prepare("SELECT doc_type, link FROM driver_documents WHERE driverID = :driverID");
    $docStmt->execute([':driverID' => $result['id']]);
    $documents = $docStmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'status' => 'success',
        'data' => [
            'driver_id' => $result['id'],
            'phone' => $decryptedPhone,
            'name' => trim($decryptedFirstName . ' ' . $decryptedLastName),
            'status' => $result['status'],
            'registered_at' => $result['created_at'],
            'car' => [
                'id' => $result['car_id'],
                'make' => $result['make'],
                'model' => $result['model'],
                'year' => $result['year'],
                'plate' => $result['car_plate'],
                'status' => $result['car_status'],
            ],
            'documents' => $documents,
        ]
    ], JSON_UNESCAPED_UNICODE);

} catch (\Exception $e) {
    error_log("[Nabeh Status Error] " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['status' => 'failure', 'message' => 'Internal server error']);
}
