<?php
/**
 * Nabeh Integration — Get User Recent Rides
 *
 * Returns the most recent rides for a user (driver or passenger)
 * identified by phone number. Used by the complaint workflow to
 * let the user pick which trip they're complaining about.
 *
 * Auth: X-API-Key header → NABEH_API_KEY
 *
 * Input:
 *   phone (required) — User's phone number
 *   limit (opt)      — Max rides to return (default 5, max 20)
 *
 * Output:
 *   List of rides with id, date, time, price, locations, status, etc.
 */

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

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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

$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;
}

$raw = file_get_contents('php://input');
$input = json_decode($raw, true) ?: ($_SERVER['REQUEST_METHOD'] === 'GET' ? $_GET : []);
$phone = preg_replace('/\D+/', '', $input['phone'] ?? '');
$limit = min(max((int)($input['limit'] ?? 5), 1), 20);

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

$mainDb = Database::get('main');
$rideDb = Database::get('ride');
global $encryptionHelper;

// Resolve user
$encryptedPhone = $encryptionHelper->encryptData($phone);
$driver = $mainDb->prepare("SELECT id, 'driver' AS type FROM driver WHERE phone = :p LIMIT 1");
$driver->execute([':p' => $encryptedPhone]);
$user = $driver->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    $passenger = $mainDb->prepare("SELECT id, 'passenger' AS type FROM passengers WHERE phone = :p LIMIT 1");
    $passenger->execute([':p' => $encryptedPhone]);
    $user = $passenger->fetch(PDO::FETCH_ASSOC);
}

if (!$user) {
    http_response_code(404);
    echo json_encode(['status' => 'failure', 'message' => 'User not found']);
    exit;
}

$col = $user['type'] === 'driver' ? 'driver_id' : 'passenger_id';
$stmt = $rideDb->prepare("
    SELECT id, start_location, end_location, date, time, endtime,
           price, price_for_driver, price_for_passenger,
           status, paymentMethod, carType, distance, created_at
    FROM ride
    WHERE $col = :uid
    ORDER BY created_at DESC
    LIMIT :lim
");
$stmt->bindValue(':uid', $user['id'], PDO::PARAM_STR);
$stmt->bindValue(':lim', $limit, PDO::PARAM_INT);
$stmt->execute();
$rides = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode([
    'status' => 'success',
    'user'   => [
        'id'   => $user['id'],
        'type' => $user['type'],
    ],
    'rides' => $rides,
], JSON_UNESCAPED_UNICODE);
