<?php
// classes/Cart.php - Shopping Cart entity model

require_once __DIR__ . '/Database.php';

class Cart {
    private $db;

    public function __construct() {
        $this->db = Database::getInstance()->getConnection();
    }

    public function add($userId, $productId, $quantity = 1, $size = 'Free Size') {
        // Validate stock
        $stmt = $this->db->prepare("SELECT stock FROM products WHERE id = ?");
        $stmt->execute([$productId]);
        $prod = $stmt->fetch();
        if (!$prod) return false;

        $stmt = $this->db->prepare("
            INSERT INTO cart_items (user_id, product_id, size, quantity)
            VALUES (?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE quantity = quantity + VALUES(quantity)
        ");
        return $stmt->execute([$userId, $productId, $size, $quantity]);
    }

    public function remove($userId, $productId, $size = 'Free Size') {
        $stmt = $this->db->prepare("DELETE FROM cart_items WHERE user_id = ? AND product_id = ? AND size = ?");
        return $stmt->execute([$userId, $productId, $size]);
    }

    public function updateQuantity($userId, $productId, $quantity, $size = 'Free Size') {
        if ($quantity <= 0) {
            return $this->remove($userId, $productId, $size);
        }
        $stmt = $this->db->prepare("UPDATE cart_items SET quantity = ? WHERE user_id = ? AND product_id = ? AND size = ?");
        return $stmt->execute([$quantity, $userId, $productId, $size]);
    }

    public function getDetails($userId) {
        $stmt = $this->db->prepare("SELECT * FROM v_cart_details WHERE user_id = ?");
        $stmt->execute([$userId]);
        return $stmt->fetchAll();
    }

    public function getTotals($userId) {
        $stmt = $this->db->prepare("SELECT * FROM v_cart_totals WHERE user_id = ?");
        $stmt->execute([$userId]);
        $totals = $stmt->fetch();
        return $totals ? $totals : ['total_items' => 0, 'total_amount' => 0.00];
    }
}
