<?php
/**
 * Drivers API Endpoint
 * GET - Get list of available drivers or single driver details
 */



header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Content-Type');

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

require_once 'bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        $pdo = getDBConnection();
        
        $driver_id = $_GET['id'] ?? null;
        
        // Get single driver details
        if ($driver_id) {
            $stmt = $pdo->prepare("
                SELECT d.*, 
                       (SELECT COUNT(*) FROM bookings WHERE driver_id = d.id AND booking_status = 'completed') as total_trips
                FROM drivers d 
                WHERE d.id = ?
            ");
            $stmt->execute([$driver_id]);
            $driver = $stmt->fetch();
            
            if (!$driver) {
                http_response_code(404);
                echo json_encode(['success' => false, 'error' => 'Driver not found']);
                exit;
            }
            
            // Get driver reviews
            $stmt = $pdo->prepare("
                SELECT r.*, u.first_name, u.last_name, u.profile_image,
                       v.make, v.model
                FROM reviews r
                LEFT JOIN users u ON r.user_id = u.id
                LEFT JOIN vehicles v ON r.vehicle_id = v.id
                WHERE r.driver_id = ? AND r.status = 'published'
                ORDER BY r.created_at DESC
            ");
            $stmt->execute([$driver_id]);
            $reviews = $stmt->fetchAll();
            
            echo json_encode([
                'success' => true,
                'data' => [
                    'driver' => $driver,
                    'reviews' => $reviews
                ]
            ]);
            exit;
        }
        
        // Get list of available drivers
        $pickup_date = $_GET['pickup_date'] ?? null;
        $dropoff_date = $_GET['dropoff_date'] ?? null;
        
        $query = "SELECT id, first_name, last_name, phone, employee_id, experience_years, rating, total_reviews, status FROM drivers WHERE status = 'active'";
        $params = [];
        
        if ($pickup_date && $dropoff_date) {
            // Filter out drivers who are already booked for the given period
            $query .= " AND id NOT IN (
                SELECT DISTINCT driver_id FROM bookings 
                WHERE driver_id IS NOT NULL 
                AND booking_status IN ('pending', 'confirmed', 'active')
                AND NOT (dropoff_date < ? OR pickup_date > ?)
            )";
            $params[] = $pickup_date;
            $params[] = $dropoff_date;
        }
        
        $stmt = $pdo->prepare($query);
        $stmt->execute($params);
        $drivers = $stmt->fetchAll();
        
        echo json_encode([
            'success' => true,
            'data' => $drivers
        ]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'error' => 'Database error occurred',
            'message' => $e->getMessage()
        ]);
    }
} else {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
}
