<?php

require_once 'cart_functions.php';
//add item to cart
if (isset($_POST['pid']) && isset($_POST['qty'])) {
    $pid = $_POST['pid'];
    $qty = $_POST['qty'];
    if (isset($_POST['slct'])) {
        $selection = $_POST['slct'];
    } else {
        $selection = false;
    }
}
if (isset($pid)) {
    $item_id = check_product_in_cart($pid, false, $selection);
    if ($item_id) {
        update_cart($item_id, $qty);
    } else {
        add_to_cart($pid, $selection);
    }
    //adds one to the cart
}
$count = count_items();
echo json_encode(array("count" => "{$count}"));
@($qnty = $_POST['qty']);
if ((isset($pID) || isset($cID)) && isset($_POST['qty'])) {
    if (isset($_POST['visible'])) {
        // this is used to change the visibility of the update(quantity) button.
        $visible = $_POST['visible'];
        //$_POST['visible'] is an array sent from the ajax call already
        $visible[$cID] = "no";
        // this simply turns the update button with the product id of where it came from to "no"
    }
    if (isset($_POST['quantArr'])) {
        // if user has tried to change two quantities at once, after they've updated one the other will remain where they left it until they update that one.
        $quantarr = $_POST['quantArr'];
        //this is an array of all of the quantities in the cart sent by the form
    }
    if (isset($pID)) {
        $cID = check_product_in_cart($pID);
    }
    if ($cID && $qnty != 0) {
        update_cart($cID, $qnty);
        //$qnty is how many to add on to what is already in the cart
    } else {
        if ($qnty != 0 && isset($pID)) {
            add_to_cart($pID);
            //adds one to the cart
        } else {
            if ($qnty == 0 && $cID) {
                update_cart($cID, $qnty);
            }
        }
    }
}