<?php
if (!defined('IN_CONTEXT')) die('access violation error!');

class ShoppingCart {
    public static function addProduct($p_id, $p_num = 1) {
        setcookie('prds['.$p_id.']', $p_id, time()+3600*24*30, '/');
        
        if (!isset($_COOKIE['n_prds'])) {
            setcookie('n_prds', $p_num, time()+3600*24*30, '/');
            setcookie('n_prd['.$p_id.']', $p_num, time()+3600*24*30, '/');
            return $p_num;
        } else {
            setcookie('n_prds', intval($_COOKIE['n_prds']) + $p_num, time()+3600*24*30, '/');
            if (!isset($_COOKIE['prds'][$p_id])) {
                setcookie('n_prd['.$p_id.']', $p_num, time()+3600*24*30, '/');
            } else {
                setcookie('n_prd['.$p_id.']', intval($_COOKIE['prds'][$p_id]) + $p_num, time()+3600*24*30, '/');
            }
            return intval($_COOKIE['n_prds']) + $p_num;
        }
    }
    
    public static function updateProductNum($p_id, $num) {
        if (intval($num) <= 0) {
            return self::removeProduct($p_id);
        } else {
            if (isset($_COOKIE['prds'][$p_id])) {
                setcookie('n_prd['.$p_id.']', $num, time()+3600*24*30, '/');
                setcookie('n_prds', intval($_COOKIE['n_prds']) - intval($_COOKIE['n_prd'][$p_id]) + $num, time()+3600*24*30, '/');
                return intval($_COOKIE['n_prds']) - intval($_COOKIE['n_prd'][$p_id]) + $num;
            } else {
                return intval($_COOKIE['n_prds']);
            }
        }
    }
    
    public static function discardProductNum() {
        setcookie('n_prds', '', time()-3600*24*30, '/');
    }
    
    public static function removeProduct($p_id) {
        if (isset($_COOKIE['prds'][$p_id])) {
            setcookie('prds['.$p_id.']', '', time()-3600*24*30, '/');
            setcookie('n_prd['.$p_id.']', '', time()-3600*24*30, '/');
            setcookie('n_prds', intval($_COOKIE['n_prds']) - intval($_COOKIE['n_prd'][$p_id]), time()+3600*24*30, '/');
            return intval($_COOKIE['n_prds']) - intval($_COOKIE['n_prd'][$p_id]);
        } else {
            return intval($_COOKIE['n_prds']);
        }
    }
}
?>
