<?php
session_start();
require_once __DIR__ . "/config/db.php";
require_once __DIR__ . "/config/price.php";

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['product_id'])) {
    $product_id = (int) $_POST['product_id'];
    $quantity   = (int) ($_POST['quantity'] ?? 1);

    // جلب بيانات المنتج
    $stmt = db()->prepare("SELECT * FROM products WHERE id=? LIMIT 1");
    $stmt->execute([$product_id]);
    $p = $stmt->fetch();

    if ($p) {
        $prices = getPrices();
        $key = (isset($p['karat']) && in_array($p['karat'], [24,21,18])) ? "gold_" . $p['karat'] : "silver";
        $unitPrice = $prices[$key] * $p['weight'];

        if (!isset($_SESSION['cart']) || !is_array($_SESSION['cart'])) {
            $_SESSION['cart'] = [];
        }

        // إذا المنتج موجود مسبقًا كمصفوفة
        if (isset($_SESSION['cart'][$product_id]) && is_array($_SESSION['cart'][$product_id])) {
            $_SESSION['cart'][$product_id]['qty'] += $quantity;
        } else {
            // تعيين كـ مصفوفة جديدة
            $_SESSION['cart'][$product_id] = [
                "qty"   => $quantity,
                "price" => $unitPrice
            ];
        }
    }

    header("Location: cart.php");
    exit;
} else {
    echo "❌ وصول غير صحيح";
}
