<?php
require_once '../config.php';
require_once '../../includes/Auth.php';
require_once '../../includes/Delivery.php';
require_once '../../includes/Database.php';

$auth = new Auth();
$user = $auth->requireAuth();
$delivery = new Delivery();
$db = new Database();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Fetch all relevant settings from the database
        $settings_stmt = $db->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('base_price_standard', 'price_per_km_standard', 'base_price_express', 'price_per_km_express', 'loyalty_delivery_threshold', 'loyalty_delivery_discount_percent')");
        $settings_raw = $settings_stmt->fetchAll(PDO::FETCH_KEY_PAIR);

        $delivery_mode = $_POST['delivery_mode'] ?? 'standard';

        // Use defaults if settings are not in the DB
        if ($delivery_mode === 'express') {
            $base_price = (float)($settings_raw['base_price_express'] ?? 10.00);
            $price_per_km = (float)($settings_raw['price_per_km_express'] ?? 0.75);
        } else {
            $base_price = (float)($settings_raw['base_price_standard'] ?? 5.00);
            $price_per_km = (float)($settings_raw['price_per_km_standard'] ?? 0.50);
        }
        $loyalty_threshold = (int)($settings_raw['loyalty_delivery_threshold'] ?? 10);
        $loyalty_discount_percent = (int)($settings_raw['loyalty_delivery_discount_percent'] ?? 50);

        // The calculatePrice method in Delivery.php can be simplified or this logic can be moved there.
        // For now, we calculate here.
        
        // Calculate distance if coordinates are provided
        $pickup_lat = $_POST['pickup_lat'] ?? null;
        $pickup_lng = $_POST['pickup_lng'] ?? null;
        $delivery_lat = $_POST['delivery_lat'] ?? null;
        $delivery_lng = $_POST['delivery_lng'] ?? null;

        if ($pickup_lat && $pickup_lng && $delivery_lat && $delivery_lng) {
            $distance = $delivery->calculateDistance($pickup_lat, $pickup_lng, $delivery_lat, $delivery_lng);
        } else {
            $distance = 10; // Fallback/Placeholder
        }

        $weight = floatval($_POST['package_weight'] ?? 1);
        $weight_fee = $weight > 1 ? ($weight - 1) * 2.00 : 0; // Example weight fee
        $distance_fee = $distance * $price_per_km;
        $total_price = $base_price + $distance_fee + $weight_fee;

        $pricing = [
            'base' => $base_price,
            'distance' => round($distance_fee, 2),
            'weight' => round($weight_fee, 2),
            'total' => round($total_price, 2)
        ];

        // Check for loyalty discount
        $completed_deliveries = $delivery->getCompletedDeliveryCount($user['id']);
        $is_eligible_for_discount = ($completed_deliveries > 0) && ($completed_deliveries % $loyalty_threshold === 0);
        
        if ($is_eligible_for_discount) {
            $discount_amount = $pricing['total'] * ($loyalty_discount_percent / 100);
            $pricing['total'] -= $discount_amount;
            $pricing['discount'] = round($discount_amount, 2);
            $pricing['is_discounted'] = true;
        }

        jsonResponse(['success' => true, 'pricing' => $pricing]);
    } catch (Exception $e) {
        jsonResponse(['success' => false, 'message' => $e->getMessage()], 500);
    }
} else {
    jsonResponse([
        'success' => false,
        'message' => 'Method not allowed'
    ], 405);
}
?>