<?php
require_once 'db.php'; // Include database connection

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, PUT, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, access-control-allow-origin");
header("Content-Type: application/json; charset=UTF-8");

$response = array();

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    // CORS preflight request handling
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, PUT, OPTIONS');
    header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, access-control-allow-origin");
    exit(0);
}

try {
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        // Fetch all vehicle prices and capacities
        $stmt = $conn->prepare("SELECT * FROM vehicle_prices");
        $stmt->execute();
        $result = $stmt->get_result();
        $vehiclePrices = array();

        while ($row = $result->fetch_assoc()) {
            $vehiclePrices[] = $row;
        }

        $response = $vehiclePrices;
    } elseif ($_SERVER['REQUEST_METHOD'] === 'PUT') {
        // Update a vehicle's price and capacity
        $data = json_decode(file_get_contents("php://input"), true);
        $id = $data['id'];
        $price = $data['price'];
        $capacity = $data['capacity'];
        $minimum = $data['minimum'];

        $stmt = $conn->prepare("UPDATE vehicle_prices SET price = ?, capacity = ?, minimum = ? WHERE id = ?");
        $stmt->bind_param("didi", $price, $capacity, $minimum, $id);
        
        if ($stmt->execute()) {
            $response['success'] = true;
            $response['message'] = 'Vehicle price, capacity, and minimum updated successfully';
        } else {
            http_response_code(500); // Internal Server Error
            $response['success'] = false;
            $response['message'] = 'Error updating vehicle price, capacity, and minimum';
        }
    } else {
        http_response_code(405); // Method Not Allowed
        $response['error'] = 'Method not allowed';
    }
} catch (Exception $e) {
    http_response_code(500); // Internal Server Error
    $response['error'] = $e->getMessage();
}

echo json_encode($response);
$conn->close();
?>
