<?php
/**
 * ============================================================
 * CART SERVICE
 * ============================================================
 * Handles all cart operations (session-based, links to user when logged in)
 */

class CartService {
    private string $sessionId;
    private ?int $userId;
    private ?int $cartId = null;
    
    public function __construct() {
        $this->sessionId = getCartSessionId();
        $this->userId = getUserId();
        $this->initCart();
    }
    
    /**
     * Initialize or get existing cart
     */
    private function initCart(): void {
        // Try to find existing cart
        $cart = Database::fetchOne(
            "SELECT id FROM carts WHERE session_id = ?",
            [$this->sessionId]
        );
        
        if ($cart) {
            $this->cartId = (int)$cart['id'];
            
            // Link to user if logged in and not already linked
            if ($this->userId) {
                Database::execute(
                    "UPDATE carts SET user_id = ? WHERE id = ? AND user_id IS NULL",
                    [$this->userId, $this->cartId]
                );
            }
        }
    }
    
    /**
     * Create cart if not exists
     * @return int Cart ID
     */
    private function ensureCart(): int {
        if ($this->cartId) {
            return $this->cartId;
        }
        
        $this->cartId = Database::insert(
            "INSERT INTO carts (session_id, user_id) VALUES (?, ?)",
            [$this->sessionId, $this->userId]
        );
        
        return $this->cartId;
    }
    
    /**
     * Add product to cart
     * @param int $productId
     * @param int $qty
     * @return array Result with success status
     */
    public function addItem(int $productId, int $qty = 1): array {
        // Validate product
        $product = Database::fetchOne(
            "SELECT id, name, price, sale_price, stock_qty, is_active 
             FROM products WHERE id = ? AND is_active = 1",
            [$productId]
        );
        
        if (!$product) {
            return ['success' => false, 'message' => 'পণ্যটি পাওয়া যায়নি'];
        }
        
        if ($product['stock_qty'] < 1) {
            return ['success' => false, 'message' => 'পণ্যটি স্টকে নেই'];
        }
        
        $cartId = $this->ensureCart();
        $unitPrice = $product['sale_price'] ?? $product['price'];
        
        // Check if product already in cart
        $existing = Database::fetchOne(
            "SELECT id, qty FROM cart_items WHERE cart_id = ? AND product_id = ?",
            [$cartId, $productId]
        );
        
        if ($existing) {
            $newQty = $existing['qty'] + $qty;
            
            // Check stock
            if ($newQty > $product['stock_qty']) {
                return [
                    'success' => false, 
                    'message' => "সর্বোচ্চ {$product['stock_qty']}টি অর্ডার করা যাবে"
                ];
            }
            
            Database::execute(
                "UPDATE cart_items SET qty = ?, unit_price = ? WHERE id = ?",
                [$newQty, $unitPrice, $existing['id']]
            );
        } else {
            if ($qty > $product['stock_qty']) {
                return [
                    'success' => false, 
                    'message' => "সর্বোচ্চ {$product['stock_qty']}টি অর্ডার করা যাবে"
                ];
            }
            
            Database::insert(
                "INSERT INTO cart_items (cart_id, product_id, qty, unit_price) VALUES (?, ?, ?, ?)",
                [$cartId, $productId, $qty, $unitPrice]
            );
        }
        
        return [
            'success' => true, 
            'message' => 'কার্টে যোগ করা হয়েছে',
            'cart_count' => $this->getItemCount()
        ];
    }
    
    /**
     * Update item quantity
     * @param int $productId
     * @param int $qty
     * @return array
     */
    public function updateQty(int $productId, int $qty): array {
        if (!$this->cartId) {
            return ['success' => false, 'message' => 'কার্ট খালি'];
        }
        
        if ($qty < 1) {
            return $this->removeItem($productId);
        }
        
        // Check stock
        $product = Database::fetchOne(
            "SELECT stock_qty FROM products WHERE id = ?",
            [$productId]
        );
        
        if (!$product) {
            return ['success' => false, 'message' => 'পণ্যটি পাওয়া যায়নি'];
        }
        
        if ($qty > $product['stock_qty']) {
            return [
                'success' => false, 
                'message' => "সর্বোচ্চ {$product['stock_qty']}টি অর্ডার করা যাবে"
            ];
        }
        
        Database::execute(
            "UPDATE cart_items SET qty = ? WHERE cart_id = ? AND product_id = ?",
            [$qty, $this->cartId, $productId]
        );
        
        return [
            'success' => true,
            'message' => 'পরিমাণ আপডেট হয়েছে',
            'cart_count' => $this->getItemCount(),
            'totals' => $this->getTotals()
        ];
    }
    
    /**
     * Remove item from cart
     * @param int $productId
     * @return array
     */
    public function removeItem(int $productId): array {
        if (!$this->cartId) {
            return ['success' => false, 'message' => 'কার্ট খালি'];
        }
        
        Database::execute(
            "DELETE FROM cart_items WHERE cart_id = ? AND product_id = ?",
            [$this->cartId, $productId]
        );
        
        return [
            'success' => true,
            'message' => 'পণ্য সরানো হয়েছে',
            'cart_count' => $this->getItemCount(),
            'totals' => $this->getTotals()
        ];
    }
    
    /**
     * Get all cart items with product details
     * @return array
     */
    public function getItems(): array {
        if (!$this->cartId) {
            return [];
        }
        
        return Database::fetchAll(
            "SELECT ci.*, p.name, p.slug, p.price, p.sale_price, p.stock_qty,
                    (SELECT file_path FROM product_images 
                     WHERE product_id = p.id AND is_primary = 1 LIMIT 1) as image
             FROM cart_items ci
             JOIN products p ON ci.product_id = p.id
             WHERE ci.cart_id = ?
             ORDER BY ci.created_at DESC",
            [$this->cartId]
        );
    }
    
    /**
     * Get cart item count
     * @return int
     */
    public function getItemCount(): int {
        if (!$this->cartId) {
            return 0;
        }
        
        return (int)Database::fetchColumn(
            "SELECT COALESCE(SUM(qty), 0) FROM cart_items WHERE cart_id = ?",
            [$this->cartId]
        );
    }
    
    /**
     * Get cart totals
     * @param float $discountAmount
     * @return array
     */
    public function getTotals(float $discountAmount = 0): array {
        $items = $this->getItems();
        return calculateCartTotals($items, $discountAmount);
    }
    
    /**
     * Clear cart
     */
    public function clear(): void {
        if ($this->cartId) {
            Database::execute("DELETE FROM cart_items WHERE cart_id = ?", [$this->cartId]);
        }
    }
    
    /**
     * Check if cart is empty
     * @return bool
     */
    public function isEmpty(): bool {
        return $this->getItemCount() === 0;
    }
    
    /**
     * Get cart ID
     * @return int|null
     */
    public function getCartId(): ?int {
        return $this->cartId;
    }
}
