<?php
/**
 * کلاس سبد خرید با پشتیبانی از Session و Cookie
 */
if (!defined('ABSPATH')) exit;

class Dima_Cart {
    
    private static $instance = null;
    private $cart = array();
    private $coupon_code = null;
    private $coupon_discount = 0;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        // بارگذاری از session
        if (isset($_SESSION['dima_cart'])) {
            $this->cart = $_SESSION['dima_cart'];
        }
        if (isset($_SESSION['dima_coupon'])) {
            $this->coupon_code = $_SESSION['dima_coupon']['code'];
            $this->coupon_discount = $_SESSION['dima_coupon']['discount'];
        }
        
        // Fallback به cookie اگر session نبود
        if (empty($this->cart) && isset($_COOKIE['dima_cart'])) {
            $this->cart = json_decode(stripslashes($_COOKIE['dima_cart']), true) ?: array();
        }
    }
    
    /**
     * افزودن محصول به سبد
     */
    public function add_item($product_id, $quantity = 1) {
        $product_id = absint($product_id);
        $quantity = max(1, absint($quantity));
        
        if ($product_id <= 0) return false;
        
        // بررسی موجودی
        $stock = Dima_Product::get_stock($product_id);
        if ($stock !== '' && intval($stock) < $quantity) {
            return false;
        }
        
        if (isset($this->cart[$product_id])) {
            $this->cart[$product_id] += $quantity;
        } else {
            $this->cart[$product_id] = $quantity;
        }
        
        $this->save();
        return true;
    }
    
    /**
     * بروزرسانی تعداد
     */
    public function update_item($product_id, $quantity) {
        $product_id = absint($product_id);
        $quantity = absint($quantity);
        
        if ($quantity <= 0) {
            $this->remove_item($product_id);
        } else {
            $this->cart[$product_id] = $quantity;
            $this->save();
        }
    }
    
    /**
     * حذف محصول
     */
    public function remove_item($product_id) {
        unset($this->cart[absint($product_id)]);
        $this->save();
    }
    
    /**
     * دریافت آیتم‌ها
     */
    public function get_items() {
        $items = array();
        foreach ($this->cart as $product_id => $quantity) {
            $product = get_post($product_id);
            if (!$product || $product->post_status !== 'publish') continue;
            
            $price = Dima_Product::get_price($product_id);
            
            // بررسی flash sale
            $flash = Dima_Flash_Sale::get_instance()->get_flash_price($product_id);
            if ($flash) {
                $price = $flash->sale_price;
            }
            
            $items[] = array(
                'product_id' => $product_id,
                'quantity' => $quantity,
                'title' => get_the_title($product_id),
                'price' => $price,
                'original_price' => Dima_Product::get_price($product_id),
                'subtotal' => $price * $quantity,
                'image' => get_the_post_thumbnail_url($product_id, 'thumbnail'),
                'url' => get_permalink($product_id)
            );
        }
        return $items;
    }
    
    /**
     * تعداد کل آیتم‌ها
     */
    public function get_item_count() {
        return array_sum($this->cart);
    }
    
    /**
     * جمع کل
     */
    public function get_total() {
        $total = 0;
        foreach ($this->cart as $product_id => $quantity) {
            $price = Dima_Product::get_price($product_id);
            $flash = Dima_Flash_Sale::get_instance()->get_flash_price($product_id);
            if ($flash) $price = $flash->sale_price;
            $total += $price * $quantity;
        }
        return $total;
    }
    
    /**
     * تنظیم کوپن
     */
    public function set_coupon($code, $discount) {
        $this->coupon_code = sanitize_text_field($code);
        $this->coupon_discount = floatval($discount);
        $_SESSION['dima_coupon'] = array(
            'code' => $this->coupon_code,
            'discount' => $this->coupon_discount
        );
    }
    
    public function get_coupon_code() { return $this->coupon_code; }
    public function get_coupon_discount() { return $this->coupon_discount; }
    
    public function remove_coupon() {
        $this->coupon_code = null;
        $this->coupon_discount = 0;
        unset($_SESSION['dima_coupon']);
    }
    
    /**
     * پاک کردن سبد
     */
    public function clear() {
        $this->cart = array();
        $this->coupon_code = null;
        $this->coupon_discount = 0;
        unset($_SESSION['dima_cart']);
        unset($_SESSION['dima_coupon']);
        setcookie('dima_cart', '', time() - 3600, '/');
    }
    
    /**
     * ذخیره در session و cookie
     */
    private function save() {
        if (!empty($this->cart)) {
            $_SESSION['dima_cart'] = $this->cart;
            setcookie('dima_cart', json_encode($this->cart), time() + (86400 * 30), '/');
        } else {
            unset($_SESSION['dima_cart']);
            setcookie('dima_cart', '', time() - 3600, '/');
        }
    }
    
    /**
     * بررسی خالی بودن
     */
    public function is_empty() {
        return empty($this->cart);
    }
}