<?php
// loginFromGoogle.php
require_once __DIR__ . '/../../connect.php';

try {
    /* ────────────────────────────────
       1) استخدام ID من التوكن (JWT)
    ───────────────────────────────── */
    $driverID = $user_id;

    error_log("[Debug] DriverID from JWT: $driverID");

    /* ────────────────────────────────
       3) إعداد الاستعلام الموحَّد
    ───────────────────────────────── */
    $sql = "
      SELECT
        driver.id, driver.phone, driver.email, driver.gender, driver.birthdate,
        driver.site, driver.first_name, driver.last_name, driver.bankCode,
        driver.accountBank, driver.employmentType,driver.status, driver.maritalStatus,
        driver.created_at, driver.updated_at,
        phone_verification.is_verified,
        CarRegistration.make, CarRegistration.model, CarRegistration.year,
        df.is_claimed, inv.isInstall, inv.isGiftToken
      FROM driver
      LEFT JOIN phone_verification ON phone_verification.phone_number = driver.phone
      LEFT JOIN driver_gifts        df  ON df.driver_id  = driver.id
      LEFT JOIN CarRegistration         ON CarRegistration.driverID = driver.id
      LEFT JOIN invites             inv ON inv.driverId   = driver.id
      WHERE 
        driver.id    = :id
      --  AND phone_verification.is_verified = '1'
      LIMIT 1
    ";

  // error_log("[Debug] queryString:\n$sql");

    $stmt = $con->prepare($sql);

    // باراميترات الربط
    $params = [
        ':id'    => $driverID,
    ];
    foreach ($params as $k => $v) {
        $stmt->bindValue($k, $v);
    }

    /* ───────── dumpParams (اختياري) ───────── */
    ob_start();
    $stmt->debugDumpParams();
    error_log("[Debug] dumpParams:\n" . ob_get_clean());

    /* ────────────────────────────────
       4) تنفيذ الاستعلام
    ───────────────────────────────── */
    $stmt->execute();
    error_log("[Debug] stmt->rowCount(): " . $stmt->rowCount());

    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  // error_log("[Debug] Raw fetched JSON: " . json_encode($rows, JSON_UNESCAPED_UNICODE));

    if (!$rows) {
        jsonError("User does not exist or phone not verified.");
        exit;
    }

    /* ────────────────────────────────
       5) فك التشفير للحقول الحسّاسة
    ───────────────────────────────── */
    $data = &$rows[0];   // مرجع لتوفير الذاكرة

    $decryptIfNotNull = function($field) use (&$data, $encryptionHelper) {
        if (isset($data[$field]) && $data[$field] !== null) {
            $data[$field] = $encryptionHelper->decryptData($data[$field]);
        }
    };

    foreach ([
        'phone', 'email', 'gender', 'birthdate', 'site',
        'first_name', 'last_name'
    ] as $field) {
        $decryptIfNotNull($field);
    }
error_log("[Debug] Raw fetched JSON: " . json_encode($rows, JSON_UNESCAPED_UNICODE));

    echo json_encode([
        "status" => "success",
        "count"  => 1,
        "data"   => $rows        // نتيجة واحدة فقط
    ], JSON_UNESCAPED_UNICODE);
} catch (PDOException $e) {
    error_log("[PDO ERROR] " . $e->getMessage());
    jsonError("Database error: ".$e->getCode());
} catch (Exception $e) {
    error_log("[GENERAL ERROR] " . $e->getMessage());
    jsonError("Error occurred.");
} finally {
    $stmt = null;
    $con  = null;
}
?>