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

$passenger_id = filterRequest("passenger_id");
$driver_id = filterRequest("driver_id");

try {
    // Step 1: Count rides for passenger or driver
    $baseSql = "SELECT COUNT(*) AS total_rows FROM `ride`";
    $params = [];

    if (!empty($passenger_id)) {
        $baseSql .= " WHERE passenger_id = :passenger_id";
        $params[':passenger_id'] = $passenger_id;
    } elseif (!empty($driver_id)) {
        $baseSql .= " WHERE driver_id = :driver_id";
        $params[':driver_id'] = $driver_id;
    }

    $stmt = $con->prepare($baseSql);
    $stmt->execute($params);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $total_rows = $row['total_rows'] ?? 0;

    if ($total_rows > 0) {
        // Step 2: Fetch the latest 10 ride records
        $rideSql = "SELECT * FROM `ride`";
        if (!empty($passenger_id)) {
            $rideSql .= " WHERE passenger_id = :passenger_id ORDER BY created_at DESC LIMIT 10";
        } elseif (!empty($driver_id)) {
            $rideSql .= " WHERE driver_id = :driver_id ORDER BY created_at DESC LIMIT 10";
        }

        $rideStmt = $con->prepare($rideSql);
        $rideStmt->execute($params);
        $rides = $rideStmt->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode([
            "status" => "success",
            "data" => $rides
        ]);
    } else {
        jsonSuccess([], "No rides found");
    }
} catch (PDOException $e) {
    jsonError("Database error: " . $e->getMessage());
}
?>