<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Cart_m extends MY_Model {

    protected $table = 'cart';
    protected $primary_key = 'cartId';

    public function __construct() {
        parent::__construct();
    }

    /**
     * Get cart items with product details for a user
     * Override parent method with compatible signature
     */
    public function getFilter($where, $order_by = null, $order = 'DESC', $limit = null) {
        return $this->getCartItems($where, $order_by, $order, $limit);
    }

    public function getCartItems($where, $order_by = null, $order = 'DESC', $limit = null) {
        $this->db->select('cart.*, products.name, products.image, products.slug, products.productUnique, 
                          products.amount, products.discountUnique, discounts.discount_percentage, 
                          colors.colorName, sizes.size');
        $this->db->from('cart');
        $this->db->join('products', 'products.productUnique = cart.productUnique', 'left');
        $this->db->join('discounts', 'discounts.discountUnique = products.discountUnique', 'left');
        $this->db->join('colors', 'colors.colorUnique = cart.color', 'left');
        $this->db->join('sizes', 'sizes.sizeUnique = cart.size', 'left');
        $this->db->where($where);
        
        if ($order_by) {
            $this->db->order_by($order_by, $order);
        }
        if ($limit) {
            $this->db->limit($limit);
        }
        
        return $this->db->get()->result();
    }

    /**
     * Get user's cart count
     */
    public function getCartCount($userUnique) {
        return $this->db->where(['userUnique' => $userUnique, 'status' => 0])->count_all_results($this->table);
    }

    /**
     * Check if product already in cart
     */
    public function isInCart($userUnique, $productUnique, $color = null, $size = null) {
        $where = [
            'userUnique' => $userUnique,
            'productUnique' => $productUnique,
            'status' => 0
        ];
        
        if ($color) {
            $where['color'] = $color;
        }
        if ($size) {
            $where['size'] = $size;
        }
        
        return $this->db->where($where)->get($this->table)->row();
    }

    /**
     * Update cart quantity
     */
    public function updateQuantity($cartId, $quantity) {
        return $this->db->where('cartId', $cartId)->update($this->table, ['quantity' => $quantity]);
    }

    /**
     * Remove item from cart
     */
    public function removeFromCart($cartId) {
        return $this->db->where('cartId', $cartId)->delete($this->table);
    }

    /**
     * Clear user's cart
     */
    public function clearCart($userUnique) {
        return $this->db->where(['userUnique' => $userUnique, 'status' => 0])->delete($this->table);
    }
}

