<?php
/**
 * Bookings API Endpoint
 * GET - Get user's bookings
 * POST - Create new booking or Cancel booking
 */



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

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

require_once 'bootstrap.php';
require_once '../admin/includes/notification_helper.php';

// GET - Retrieve user's bookings
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        $user_id = $_GET['user_id'] ?? $_SESSION['user_id'] ?? null;
        $booking_id = $_GET['booking_id'] ?? null;
        
        if (!$user_id && !$booking_id) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'User ID or Booking ID is required']);
            exit;
        }
        
        $pdo = getDBConnection();
        
        if ($booking_id) {
            $stmt = $pdo->prepare("
                SELECT b.*, v.make, v.model, v.images, v.vehicle_type, v.plate_number, v.daily_rate,
                       v.transmission, v.fuel_type, v.seats,
                       p.status as payment_status, p.amount as payment_amount, p.payment_method, p.transaction_reference,
                       d.first_name as driver_first_name, d.last_name as driver_last_name, d.phone as driver_phone, d.employee_id as driver_employee_id, d.rating as driver_rating,
                       ds.service_name as delivery_service_name, ds.description as delivery_service_description
                FROM bookings b
                LEFT JOIN vehicles v ON b.vehicle_id = v.id
                LEFT JOIN payments p ON b.id = p.booking_id
                LEFT JOIN drivers d ON b.driver_id = d.id
                LEFT JOIN delivery_services ds ON b.delivery_service_id = ds.id
                WHERE b.id = ?
            ");
            $stmt->execute([$booking_id]);
            $booking = $stmt->fetch();

            if (!$booking) {
                http_response_code(404);
                echo json_encode(['success' => false, 'error' => 'Booking not found']);
                exit;
            }

            // Process booking data
            $images = json_decode($booking['images'] ?? '[]', true);
            $booking['vehicle_image'] = !empty($images) ? $images[0] : 'https://images.unsplash.com/photo-1533473359331-0135ef1b58bf?auto=format&fit=crop&q=80&w=400';
            $booking['vehicle_name'] = $booking['make'] . ' ' . $booking['model'];
            
            // Calculate rental days
            $pickup = new DateTime($booking['pickup_date']);
            $dropoff = new DateTime($booking['dropoff_date']);
            $booking['rental_days'] = max(1, $dropoff->diff($pickup)->days);
            
            unset($booking['images']);

            echo json_encode([
                'success' => true,
                'data' => $booking
            ]);
        } else {
            $stmt = $pdo->prepare("
                SELECT b.*, v.make, v.model, v.images, v.vehicle_type, v.plate_number, v.daily_rate,
                       p.status as payment_status, p.amount as payment_amount, p.payment_method,
                       ds.service_name as delivery_service_name,
                       d.first_name as driver_first_name, d.last_name as driver_last_name, d.phone as driver_phone
                FROM bookings b
                LEFT JOIN vehicles v ON b.vehicle_id = v.id
                LEFT JOIN payments p ON b.id = p.booking_id
                LEFT JOIN delivery_services ds ON b.delivery_service_id = ds.id
                LEFT JOIN drivers d ON b.driver_id = d.id
                WHERE b.user_id = ?
                ORDER BY b.created_at DESC
            ");
            $stmt->execute([$user_id]);
            $bookings = $stmt->fetchAll();

            // Process bookings data
            foreach ($bookings as &$booking) {
                // Combine driver name
                if ($booking['driver_first_name']) {
                    $booking['driver_name'] = trim($booking['driver_first_name'] . ' ' . ($booking['driver_last_name'] ?? ''));
                }

                $images = json_decode($booking['images'] ?? '[]', true);
                if (!is_array($images)) {
                    $images = [];
                }
                $booking['vehicle_image'] = !empty($images) ? $images[0] : 'https://images.unsplash.com/photo-1533473359331-0135ef1b58bf?auto=format&fit=crop&q=80&w=400';
                $booking['vehicle_name'] = $booking['make'] . ' ' . $booking['model'];
                
                // Calculate rental days
                $pickup = new DateTime($booking['pickup_date']);
                $dropoff = new DateTime($booking['dropoff_date']);
                $booking['rental_days'] = max(1, $dropoff->diff($pickup)->days);
                
                unset($booking['images']);
            }

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

// POST - Create or Cancel booking
elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $input = json_decode(file_get_contents('php://input'), true);
        if (!$input) {
            $input = $_POST;
        }
        
        $pdo = getDBConnection();

        // Handle Cancellation
        if (isset($input['action']) && $input['action'] === 'cancel') {
            $booking_id = $input['booking_id'] ?? null;
            $user_id = $_SESSION['user_id'] ?? $input['user_id'] ?? null;

            if (!$booking_id || !$user_id) {
                http_response_code(400);
                echo json_encode(['success' => false, 'error' => 'Booking ID and User ID are required']);
                exit;
            }

            $stmt = $pdo->prepare("SELECT id, vehicle_id FROM bookings WHERE id = ? AND user_id = ? AND booking_status IN ('pending', 'confirmed')");
            $stmt->execute([$booking_id, $user_id]);
            $booking = $stmt->fetch();

            if (!$booking) {
                http_response_code(404);
                echo json_encode(['success' => false, 'error' => 'Booking not found or cannot be cancelled']);
                exit;
            }

            $stmt = $pdo->prepare("UPDATE bookings SET booking_status = 'cancelled' WHERE id = ?");
            $stmt->execute([$booking_id]);

            $stmt = $pdo->prepare("UPDATE vehicles SET status = 'available' WHERE id = ?");
            $stmt->execute([$booking['vehicle_id']]);

            echo json_encode(['success' => true, 'message' => 'Booking cancelled successfully']);
            exit;
        }

        // Create new booking
        $user_id = $input['user_id'] ?? $_SESSION['user_id'] ?? null;
        $booking_type = $input['booking_type'] ?? 'rental';
        $vehicle_id = $input['vehicle_id'] ?? null;
        $delivery_service_id = $input['delivery_service_id'] ?? null;
        $driver_id = $input['driver_id'] ?? null;
        $pickup_date = $input['pickup_date'] ?? null;
        $dropoff_date = $input['dropoff_date'] ?? null;
        $pickup_location = $input['pickup_location'] ?? '';
        $pickup_description = $input['pickup_description'] ?? '';
        $pickup_latitude = $input['pickup_latitude'] ?? null;
        $pickup_longitude = $input['pickup_longitude'] ?? null;
        $dropoff_location = $input['dropoff_location'] ?? '';
        $dropoff_description = $input['dropoff_description'] ?? '';
        $dropoff_latitude = $input['dropoff_latitude'] ?? null;
        $dropoff_longitude = $input['dropoff_longitude'] ?? null;
        $with_carwash = isset($input['with_carwash']) ? (bool)$input['with_carwash'] : false;
        
        if (!$user_id || !$pickup_date || (!$vehicle_id && $booking_type === 'rental') || (!$delivery_service_id && $booking_type === 'delivery')) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'Missing required fields']);
            exit;
        }

        // Fetch System Settings for Fees
        $stmt = $pdo->query("SELECT key_name, key_value FROM settings WHERE key_name IN ('insurance_fee', 'insurance_fee_type', 'service_fee', 'service_fee_type', 'downpayment_percentage')");
        $settings = [];
        while ($row = $stmt->fetch()) {
            $settings[$row['key_name']] = $row['key_value'];
        }

        $total_amount = 0;
        $daily_rate = 0;
        $insurance = 0;
        $service_fee = 0;
        $carwash_amount = 0;

        if ($booking_type === 'rental') {
            $stmt = $pdo->prepare("SELECT * FROM vehicles WHERE id = ? AND status = 'available'");
            $stmt->execute([$vehicle_id]);
            $vehicle = $stmt->fetch();

            if (!$vehicle) {
                http_response_code(404);
                echo json_encode(['success' => false, 'error' => 'Vehicle not available']);
                exit;
            }

            $pickup = new DateTime($pickup_date);
            $dropoff = new DateTime($dropoff_date);
            $days = max(1, $dropoff->diff($pickup)->days);

            $daily_rate = floatval($vehicle['daily_rate']);
            $subtotal = $daily_rate * $days;

            // Calculate Insurance
            $ins_val = floatval($settings['insurance_fee'] ?? 7.5);
            $ins_type = $settings['insurance_fee_type'] ?? 'percentage';
            if ($ins_type === 'percentage') {
                $insurance = $subtotal * ($ins_val / 100);
            } else {
                $insurance = $ins_val * $days;
            }

            // Calculate Service Fee
            $ser_val = floatval($settings['service_fee'] ?? 2.0);
            $ser_type = $settings['service_fee_type'] ?? 'percentage';
            if ($ser_type === 'percentage') {
                $service_fee = $subtotal * ($ser_val / 100);
            } else {
                $service_fee = $ser_val;
            }

            // Cleaning fee is now mandatory for all rental bookings
            $with_carwash = true;
            $stmt = $pdo->prepare("SELECT cleaning_fee FROM pricing_settings WHERE setting_type = ?");
            $stmt->execute([$vehicle['vehicle_type']]);
            $carwash_amount = floatval($stmt->fetchColumn() ?: 250);

            $total_amount = $subtotal + $insurance + $service_fee + $carwash_amount;
        } else {
            // Delivery
            $stmt = $pdo->prepare("SELECT * FROM delivery_services WHERE id = ? AND is_active = 1");
            $stmt->execute([$delivery_service_id]);
            $service = $stmt->fetch();

            if (!$service) {
                http_response_code(404);
                echo json_encode(['success' => false, 'error' => 'Delivery service not available']);
                exit;
            }

            $total_amount = floatval($service['amount']);
            // Dropoff date is same as pickup for delivery
            $dropoff_date = $pickup_date;
        }

        $down_pct = floatval($settings['downpayment_percentage'] ?? 20) / 100;
        $downpayment = $total_amount * $down_pct;
        
        $reference_number = ($booking_type === 'delivery' ? 'DL-' : 'BK-') . strtoupper(bin2hex(random_bytes(4)));
        
        $stmt = $pdo->prepare("
            INSERT INTO bookings (
                reference_number, booking_type, user_id, vehicle_id, delivery_service_id, driver_id, pickup_date, dropoff_date,
                pickup_location, pickup_description, pickup_latitude, pickup_longitude,
                dropoff_location, dropoff_description, dropoff_latitude, dropoff_longitude,
                daily_rate, insurance_amount, service_fee, with_carwash, carwash_amount,
                total_amount, downpayment_amount, booking_status, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())
        ");
        
        $stmt->execute([
            $reference_number, $booking_type, $user_id, $vehicle_id, $delivery_service_id, $driver_id, $pickup_date, $dropoff_date,
            $pickup_location, $pickup_description, $pickup_latitude, $pickup_longitude,
            $dropoff_location, $dropoff_description, $dropoff_latitude, $dropoff_longitude,
            $daily_rate, $insurance, $service_fee, $with_carwash ? 1 : 0, $carwash_amount,
            $total_amount, $downpayment
        ]);
        
        $booking_id = $pdo->lastInsertId();

        // Handle Payment Integration
        $payment_method = $input['payment_method'] ?? null;
        if ($payment_method) {
            $payment_details = [];
            if (isset($input['payment_details'])) {
                $payment_details = is_string($input['payment_details']) ? json_decode($input['payment_details'], true) : $input['payment_details'];
            }

            $sender_name = ($payment_details['bank_name'] ?? '') . ' ' . ($payment_details['account_name'] ?? '');
            $sender_name = trim($sender_name);
            $sender_number = $payment_details['account_number'] ?? '';
            $transaction_ref = $payment_details['reference_number'] ?? '';

            // Handle proof of payment upload
            $proof_of_payment_url = null;
            if (isset($_FILES['proof_of_payment']) && $_FILES['proof_of_payment']['error'] === UPLOAD_ERR_OK) {
                $file = $_FILES['proof_of_payment'];
                $upload_dir = __DIR__ . '/../uploads/payments/';
                if (!file_exists($upload_dir)) {
                    mkdir($upload_dir, 0755, true);
                }

                $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                $filename = 'payment_' . bin2hex(random_bytes(8)) . '_' . time() . '.' . $extension;
                if (move_uploaded_file($file['tmp_name'], $upload_dir . $filename)) {
                    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http");
                    $host = $_SERVER['HTTP_HOST'];
                    $project_path = str_replace('\\', '/', dirname(dirname($_SERVER['SCRIPT_NAME'])));
                    $project_path = rtrim($project_path, '/');
                    $proof_of_payment_url = $protocol . "://" . $host . $project_path . '/uploads/payments/' . $filename;
                }
            }

            // Insert into payments table
            $payment_ref = 'PAY-' . strtoupper(bin2hex(random_bytes(4)));
            $stmt = $pdo->prepare("
                INSERT INTO payments (
                    reference_number, booking_id, amount, payment_method,
                    payment_type, proof_of_payment, transaction_reference,
                    sender_name, sender_number,
                    status, created_at
                ) VALUES (?, ?, ?, ?, 'downpayment', ?, ?, ?, ?, 'pending', NOW())
            ");

            $stmt->execute([
                $payment_ref,
                $booking_id,
                $downpayment,
                $payment_method,
                $proof_of_payment_url,
                $transaction_ref,
                $sender_name,
                $sender_number
            ]);

            // Notify Admin
            notifyAdmins(
                "New Booking & Payment",
                "New booking #$reference_number with " . ucfirst($payment_method) . " payment of ₱" . number_format($downpayment, 2),
                'payment',
                "payments.php"
            );
        }

        // IMPROVEMENT: Set vehicle status to 'reserved' to prevent double booking
        if ($vehicle_id) {
            $stmt = $pdo->prepare("UPDATE vehicles SET status = 'reserved' WHERE id = ?");
            $stmt->execute([$vehicle_id]);
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Booking created successfully',
            'data' => [
                'booking_id' => $booking_id,
                'reference_number' => $reference_number,
                'total_amount' => $total_amount,
                'downpayment_amount' => $downpayment
            ]
        ]);
        
    } 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']);
}
