<?php
/**
 * calc_shipping.php
 *
 * Home delivery  → flat zone rate (from shipping_zones.rate)
 * Pickup         → per-location weight-tier price
 *                  (price_5kg / price_10kg / price_15kg / price_20kg)
 *                  fallback to global shipping_rules if tiers not set
 */
require_once 'config/db.php';
header('Content-Type: application/json');

$input     = json_decode(file_get_contents('php://input'), true) ?? [];
$method    = $input['method']    ?? 'home';
$zone_id   = $input['zone_id']   ?? null;
$pickup_id = $input['pickup_id'] ?? null;
$cart      = $input['cart']      ?? [];

// ── 1. HOME DELIVERY — flat zone rate ────────────────────────────────────────
if ($method === 'home') {
    $rate = 0;
    if ($zone_id) {
        $stmt = $pdo->prepare("SELECT rate FROM shipping_zones WHERE id = ? LIMIT 1");
        $stmt->execute([$zone_id]);
        $rate = floatval($stmt->fetchColumn() ?: 0);
    }
    echo json_encode([
        'success'       => true,
        'shipping_cost' => $rate,
        'total_weight'  => 0,
        'method'        => 'home',
    ]);
    exit;
}

// ── 2. PICKUP — weight-based per-location pricing ────────────────────────────

// 2a. Calculate total cart weight (kg)
$total_weight = 0;
if (!empty($cart)) {
    $ids = array_filter(array_column($cart, 'id'));
    if ($ids) {
        $ph   = implode(',', array_fill(0, count($ids), '?'));
        $stmt = $pdo->prepare("SELECT id, weight FROM products WHERE id IN ($ph)");
        $stmt->execute(array_values($ids));
        $weights = $stmt->fetchAll(PDO::FETCH_KEY_PAIR); // [id => weight]
        foreach ($cart as $item) {
            $w             = floatval($weights[$item['id']] ?? 0.5); // 0.5 kg default
            $total_weight += $w * max(1, intval($item['quantity'] ?? 1));
        }
    }
}

$shipping_cost = 0;

// 2b. Fetch the pickup location's own weight-tier prices
if ($pickup_id) {
    $stmt = $pdo->prepare("SELECT price, price_5kg, price_10kg, price_15kg, price_20kg
                           FROM pickup_locations WHERE id = ? LIMIT 1");
    $stmt->execute([$pickup_id]);
    $loc = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($loc) {
        $p5  = floatval($loc['price_5kg']  ?? $loc['price'] ?? 0);
        $p10 = floatval($loc['price_10kg'] ?? $loc['price'] ?? 0);
        $p15 = floatval($loc['price_15kg'] ?? $loc['price'] ?? 0);
        $p20 = floatval($loc['price_20kg'] ?? $loc['price'] ?? 0);

        // If all tiers are set (non-zero), use them
        if ($p5 > 0 || $p10 > 0 || $p15 > 0 || $p20 > 0) {
            if ($total_weight <= 5)       $shipping_cost = $p5;
            elseif ($total_weight <= 10)  $shipping_cost = $p10;
            elseif ($total_weight <= 15)  $shipping_cost = $p15;
            else                          $shipping_cost = $p20; // 15 kg+ → top tier
        } else {
            // Tier prices not set — fall back to global shipping_rules by weight
            $shipping_cost = getGlobalRuleCost($pdo, $total_weight);
        }
    } else {
        $shipping_cost = getGlobalRuleCost($pdo, $total_weight);
    }
} else {
    $shipping_cost = getGlobalRuleCost($pdo, $total_weight);
}

echo json_encode([
    'success'       => true,
    'shipping_cost' => $shipping_cost,
    'total_weight'  => round($total_weight, 2),
    'method'        => 'pickup',
]);

// ── Helper ────────────────────────────────────────────────────────────────────
function getGlobalRuleCost(PDO $pdo, float $weight): float {
    // Find matching weight bracket
    $stmt = $pdo->prepare("SELECT cost FROM shipping_rules
                           WHERE min_weight <= ? AND max_weight >= ?
                           ORDER BY min_weight ASC LIMIT 1");
    $stmt->execute([$weight, $weight]);
    $cost = $stmt->fetchColumn();
    if ($cost !== false) return floatval($cost);

    // Past all brackets → use highest-weight rule
    $stmt = $pdo->query("SELECT cost FROM shipping_rules ORDER BY max_weight DESC LIMIT 1");
    return floatval($stmt->fetchColumn() ?: 0);
}
