<?php
/**
 * Reviews API Endpoint
 * GET - Get reviews for a vehicle
 * POST - Submit a new review
 */

require_once 'bootstrap.php';
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: Content-Type');

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

$pdo = getDBConnection();

// GET - Retrieve reviews or check eligibility
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        $action = $_GET['action'] ?? 'get_reviews';

        if ($action === 'check_eligibility') {
            $vehicle_id = $_GET['vehicle_id'] ?? null;
            $driver_id = $_GET['driver_id'] ?? null;
            $booking_id = $_GET['booking_id'] ?? null;
            $user_id = $_GET['user_id'] ?? $_SESSION['user_id'] ?? null;

            if (!$user_id) {
                echo json_encode(['success' => true, 'can_review' => false]);
                exit;
            }

            // Check eligibility for a specific booking
            if ($booking_id) {
                $stmt = $pdo->prepare("
                    SELECT b.id
                    FROM bookings b
                    LEFT JOIN reviews r ON b.id = r.booking_id
                    WHERE b.id = ? AND b.user_id = ? AND b.booking_status = 'completed' AND r.id IS NULL
                    LIMIT 1
                ");
                $stmt->execute([$booking_id, $user_id]);
                $booking = $stmt->fetch();

                echo json_encode([
                    'success' => true,
                    'can_review' => !!$booking,
                    'booking_id' => $booking ? $booking['id'] : null
                ]);
                exit;
            }

            // Check eligibility for vehicle reviews
            if ($vehicle_id) {
                // Find a completed booking for this vehicle by this user that doesn't have a review yet
                $stmt = $pdo->prepare("
                    SELECT b.id
                    FROM bookings b
                    LEFT JOIN reviews r ON b.id = r.booking_id
                    WHERE b.vehicle_id = ? AND b.user_id = ? AND b.booking_status = 'completed' AND r.id IS NULL
                    LIMIT 1
                ");
                $stmt->execute([$vehicle_id, $user_id]);
                $booking = $stmt->fetch();

                echo json_encode([
                    'success' => true,
                    'can_review' => !!$booking,
                    'booking_id' => $booking ? $booking['id'] : null
                ]);
                exit;
            }

            // Check eligibility for driver reviews
            if ($driver_id) {
                $stmt = $pdo->prepare("
                    SELECT b.id
                    FROM bookings b
                    LEFT JOIN reviews r ON b.id = r.booking_id
                    WHERE b.driver_id = ? AND b.user_id = ? AND b.booking_status = 'completed' AND r.id IS NULL
                    LIMIT 1
                ");
                $stmt->execute([$driver_id, $user_id]);
                $booking = $stmt->fetch();

                echo json_encode([
                    'success' => true,
                    'can_review' => !!$booking,
                    'booking_id' => $booking ? $booking['id'] : null
                ]);
                exit;
            }

            echo json_encode(['success' => true, 'can_review' => false]);
            exit;
        }

        $vehicle_id = $_GET['vehicle_id'] ?? null;
        $driver_id = $_GET['driver_id'] ?? null;
        $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;

        $query = "SELECT r.*, u.first_name, u.last_name, u.profile_image
                  FROM reviews r
                  LEFT JOIN users u ON r.user_id = u.id
                  WHERE r.status = 'published'";
        $params = [];

        if ($vehicle_id) {
            $query .= " AND r.vehicle_id = ?";
            $params[] = $vehicle_id;
        }

        if ($driver_id) {
            $query .= " AND r.driver_id = ?";
            $params[] = $driver_id;
        }

        $query .= " ORDER BY r.created_at DESC LIMIT " . (int)$limit;

        $stmt = $pdo->prepare($query);
        $stmt->execute($params);
        $reviews = $stmt->fetchAll();

        echo json_encode([
            'success' => true,
            'data' => $reviews
        ]);

    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

// POST - Submit review
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    $booking_id = $input['booking_id'] ?? null;
    $user_id = $input['user_id'] ?? null;

    $vehicle_rating = isset($input['vehicle_rating']) ? floatval($input['vehicle_rating']) : 5.0;
    $driver_rating_input = (isset($input['driver_rating']) && $input['driver_rating'] !== null) ? floatval($input['driver_rating']) : null;
    $service_rating = isset($input['service_rating']) ? floatval($input['service_rating']) : 5.0;

    $vehicle_comment = $input['vehicle_comment'] ?? '';
    $driver_comment = $input['driver_comment'] ?? '';
    $service_comment = $input['service_comment'] ?? '';
    
    if (!$booking_id || !$user_id) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Missing required fields']);
        exit;
    }
    
    // Check if review already exists for this booking
    $stmt = $pdo->prepare("SELECT id FROM reviews WHERE booking_id = ? AND user_id = ?");
    $stmt->execute([$booking_id, $user_id]);
    if ($stmt->fetch()) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'You have already submitted a review for this booking']);
        exit;
    }

    // Get booking details to get vehicle_id and driver_id
    $stmt = $pdo->prepare("SELECT vehicle_id, driver_id, booking_status, user_id as booking_user_id FROM bookings WHERE id = ?");
    $stmt->execute([$booking_id]);
    $booking = $stmt->fetch();
    
    if (!$booking) {
        http_response_code(404);
        echo json_encode(['success' => false, 'error' => 'Booking not found']);
        exit;
    }
    
    // Verify booking belongs to user
    if ($booking['booking_user_id'] != $user_id) {
        http_response_code(403);
        echo json_encode(['success' => false, 'error' => 'Unauthorized to review this booking']);
        exit;
    }
    
    // Verify booking is completed
    if ($booking['booking_status'] !== 'completed') {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Can only review completed bookings']);
        exit;
    }
    
    $vehicle_id = $booking['vehicle_id'];
    $driver_id = $booking['driver_id'];

    // Finalize driver rating and calculate overall rating
    $driver_rating = $driver_id ? ($driver_rating_input ?? 5.0) : 0.0;

    // Calculate overall rating if not provided
    if (isset($input['overall_rating'])) {
        $overall_rating = floatval($input['overall_rating']);
    } else {
        // If there's a driver, average across 3 components, otherwise 2
        if ($driver_id) {
            $overall_rating = ($vehicle_rating + $driver_rating + $service_rating) / 3;
        } else {
            $overall_rating = ($vehicle_rating + $service_rating) / 2;
        }
    }

    // Insert review
    $stmt = $pdo->prepare("
        INSERT INTO reviews (
            booking_id, user_id, vehicle_id, driver_id, 
            overall_rating, vehicle_rating, driver_rating, service_rating,
            vehicle_comment, driver_comment, service_comment,
            status, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'published', NOW())
    ");
    
    $stmt->execute([
        $booking_id,
        $user_id,
        $vehicle_id,
        $driver_id,
        $overall_rating,
        $vehicle_rating,
        $driver_rating,
        $service_rating,
        $vehicle_comment,
        $driver_comment,
        $service_comment
    ]);
    
    // Update Vehicle Stats
    if ($vehicle_id) {
        $stmt = $pdo->prepare("
            UPDATE vehicles
            SET rating = COALESCE((SELECT AVG(vehicle_rating) FROM reviews WHERE vehicle_id = ? AND status = 'published'), 0),
                total_reviews = (SELECT COUNT(*) FROM reviews WHERE vehicle_id = ? AND status = 'published')
            WHERE id = ?
        ");
        $stmt->execute([$vehicle_id, $vehicle_id, $vehicle_id]);
    }

    // Update Driver Stats
    if ($driver_id) {
        $stmt = $pdo->prepare("
            UPDATE drivers
            SET rating = COALESCE((SELECT AVG(driver_rating) FROM reviews WHERE driver_id = ? AND status = 'published'), 0),
                total_reviews = (SELECT COUNT(*) FROM reviews WHERE driver_id = ? AND status = 'published')
            WHERE id = ?
        ");
        $stmt->execute([$driver_id, $driver_id, $driver_id]);
    }

    echo json_encode([
        'success' => true,
        'message' => 'Review submitted successfully'
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Database error occurred',
        'message' => $e->getMessage()
    ]);
}
