<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | PHP version 4/5                                                      |
// +----------------------------------------------------------------------+
// | This source file is a part of iScripts Multicart                     |
// +----------------------------------------------------------------------+
// | Authors: Santhosh Thomas Alexander<santhosh.thomas@armiasystems.com> |
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems, Inc and iScripts.com  2005                |
// | All rights reserved                                                  |
// +----------------------------------------------------------------------+
// | This script may not be distributed, sold, given away for free to     |
// | third party, or used as a part of any internet services such as      |
// | webdesign etc.                                                       |
// +----------------------------------------------------------------------+
?>
<?php
include "includes/config.php";
include "includes/session.php";
include "includes/functions.php";

if (get_magic_quotes_gpc()) {
    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
}
if (isset($_SESSION["sess_userid"]) and $_SESSION["sess_userid"] != "") {
    $userid = $_SESSION["sess_userid"];
}


if (checkGiftProductsExistsinCart($userid)) {
    cartClearDigital($userid);
}



$_SESSION["sess_addresses_collected"] = false;

if (isset($_GET["msg"]) and ($_GET["msg"] != "")) {
    $msg = $_GET["msg"];
    switch ($msg) {
        case "updateqty": $message = UPDATE_QUANTITY_ERROR_MSG."<br>";
            break;
        case "cart_error_nondigital": $message = CART_ERROR_NONDIGITAL_MSG."<br>";
            break;
        case "cart_error_digital": $message = CART_ERROR_DIGITAL_MSG."<br>";
            break;
        case "cart_stock_less": $message = CART_STOCK_LESS_MSG."<br>";
            break;
        default:
            ;
    } // switch
}


if (isset($_GET['action']) && $_GET['action'] == 'checkout') {

    header("Location:checkout.php");
    exit;
}

if (isset($_POST["btnDeleteSelected"])) {
    $items = $_POST["chkitems"];
    if (!isNotNull($items)) {
        $message = NO_ITEMS_SELECTED_MSG."<br>";
    }
    if ($message != "") { // error
        $message = "<br>".CORRECT_ERRORS_TEXT."<br>" . $message;
    } else {
        $items = implode(",", $items);
        $sql = "DELETE FROM " . $tableprefix . "cart WHERE cart_id IN (" . addslashes($items) . ") ";
        mysql_query($sql);
        $message = DELETE_SUCESSFUL_MSG;
    }
} else if (isset($_POST["btnUpdateQuantities"])) {
    $cartitems = $_POST["cartitems"];
    $allnotupdated = false;
    $arrcartitems = explode(",", $cartitems);
    $sql = "SELECT * FROM " . $tableprefix . "cart WHERE cart_id IN (" . addslashes($cartitems) . ") ";
    $result = mysql_query($sql);
    $parr = array();
    $poarr = array();
    if (mysql_num_rows($result) != 0) {
        while ($row = mysql_fetch_array($result)) {
            $cid = $row["cart_id"];
            $parr[$cid] = $row["product_id"];
            $poarr[$cid] = $row["product_option_id"];
        }
    }
    $qtyadjusted = false;
    for ($i = 0; $i < count($arrcartitems); $i++) {
        $var = "txtQuantity_" . $arrcartitems[$i];
        $cartid = $arrcartitems[$i];
        $value = intval($_POST["$var"]);
        if ($value > 0) {
            $product_id = $parr[$cartid];
            $product_option_id = $poarr[$cartid];
            $qtyavailable = getProductStock($product_option_id);
            if ($value > $qtyavailable) {
                $value = $qtyavailable;
                $qtyadjusted = true;
            }
            $sql = "UPDATE " . $tableprefix . "cart SET quantity = '" . addslashes($value) . "' WHERE cart_id='" . addslashes($cartid) . "' ";
            mysql_query($sql);
        } else {
            $allnotupdated = true;
        }
    }

    if ($allnotupdated) { // error
        $message .= "<br>".ALL_NOT_UPDATED_MSG;
    }
    if ($qtyadjusted) { // error
        $message .= "<br>".QUANTITIES_ADJUSTED_MSG;
    }
    if ($message == "") { // all done
        $message = UPDATE_SUCESSFUL_MSG;
    }
} else if (isset($_POST["btnCheckout"])) {

    $row_paypal = mysql_fetch_assoc(mysql_query("SELECT enable_buyerToseller FROM " . $tableprefix . "settings "));

    if (!isset($_SESSION["sess_userid"]) and $_SESSION["sess_userid"] == "") {

        $cartitems = $_POST["cartitems"];
        $arrcartitems = explode(",", $cartitems);

        for ($i = 0; $i < count($arrcartitems); $i++) {

            $var = "txtQuantity_" . $arrcartitems[$i];
            $insert_cart_temp = "INSERT INTO " . $tableprefix . "cart_temp(ncart_id,ncart_quantity)VALUES(
								" . $arrcartitems[$i] . ","
                    . $_POST["$var"] . ")";
            mysql_query($insert_cart_temp) or die(mysql_error());
        }
    }


    if ($row_paypal["enable_buyerToseller"] == "Y") {
        if (isset($_POST['sellerid'])) {

            $sellerid = $_POST['sellerid'];

            $sellercount = count(array_unique($sellerid));
            //exit;

            if ($sellercount > 5) {

                header("Location:viewcart.php?msg=duplicate");

                exit;
                //echo "You have to select Only One Sellers Products ";
            }
        }
    }


    header("Location:checkout.php");
    exit;
}



/* display the active template */

$active_template = displayTemplate();


include "includes/htmltop.php";

/* Top File Name */

include_once ("includes/" . $active_template[0]);
?>
<script>
    //window.location = "./viewcart.php";
		
    function checkOutCart()
    {
        var cntt = document.getElementById("cntt").value;
        var c = 0;
        for(i=1;i<=cntt;i++)
        {
            var textval = document.getElementById("txtQuantity_"+i).value;
            var hidval  = document.getElementById("hdQty_"+i).value;
            if(textval == hidval)
            {
                c=c+0;
            }
            else
            {
                c=c+1;
            }
        }
        if(c>0)
        {
            alert("<?php echo UPDATE_ALERT_TEXT; ?>");
            return false;
        }
        else
        {
            return true;
        }
    }
																																			
</script>	

<div align="left" class="main_body">
    <!--mainbody area start -->

    <!--center content area start-->		

    <form name="frmCart" action="<?php echo $_SERVER["PHP_SELF"] ?>" method="POST">


        <div align="left" id="item_details">


            <!--items display area start -->

            <div align="left" id="items_top_area">
                <div align="left" id="items_top_area_ttl"><?php echo SHOPPING_CART_TEXT; ?></div>
            </div>

<?php
if ($_GET['msg'] == 'duplicate') {
    ?>
                <div class="text_information" align="center"><?php echo IF_DUPLICATE_TEXT_INFO; ?></div>
<?php } ?>
            <div class="text_information" align="center"><?php echo $message ?></div>


            <div>



<?php
$total = 0;
$cartitems = "";


if (isset($_SESSION["sess_userid"]) and $_SESSION["sess_userid"] != "") {
    $sql_cart = "SELECT c.*, p.product_name,(p.product_price+po.additional_price) AS product_price,po.discount,p.vdigital_product,p.product_id,p.product_artist_id,
								ctry.gift_certificate_flag
						 FROM " . $tableprefix . "cart c
                                                 INNER JOIN " . $tableprefix . "product_options po ON po.product_option_id = c.product_option_id
                                                 INNER JOIN " . $tableprefix . "products p ON p.product_id = po.product_id
                                                 INNER JOIN " . $tableprefix . "categories ctry ON ctry.category_id = p.product_category
                                                 WHERE c.user_id = '" . addslashes($_SESSION["sess_userid"]) . "'";
} else {
    $sql_cart = "SELECT c.*, p.product_name,(p.product_price+po.additional_price) AS product_price,po.discount,p.product_artist_id
						FROM " . $tableprefix . "cart c 
                                                INNER JOIN " . $tableprefix . "product_options po ON po.product_option_id = c.product_option_id
                                                INNER JOIN " . $tableprefix . "products p ON p.product_id = po.product_id
                                                WHERE  c.visitor_cart_id = '" . addslashes(session_id()) . "' ";
}



$res_cart = mysql_query($sql_cart);

if (mysql_num_rows($res_cart) > 0) {
    while ($rw_cart = mysql_fetch_array($res_cart)) {
        if (isset($_SESSION["sess_userid"]) and $_SESSION["sess_userid"] != "") {

            if ($rw_cart['vdigital_product'] == 'Y' || $rw_cart['gift_certificate_flag'] == 'Y') {
                /* ---------Checking if shipping is enable----------- */

                //$check_shipping_enable = checkShippingEnable();						
                //if($check_shipping_enable == "Y")
                //{
                cartClearDigital($_SESSION["sess_userid"]);
                //}	
                /* ---------Checking if shipping is enable----------- */
            }
        }
        $_SESSION['gift_certificate_flag'] = $rw_cart['gift_certificate_flag'];
    }
}


if (isset($_SESSION["sess_userid"]) and $_SESSION["sess_userid"] != "") {
    $sql = "SELECT c.*, p.product_name,(p.product_price+po.additional_price) AS product_price,po.discount,p.product_artist_id
					FROM " . $tableprefix . "cart c
                                        INNER JOIN " . $tableprefix . "product_options po ON po.product_option_id = c.product_option_id
                                        INNER JOIN " . $tableprefix . "products p ON p.product_id = po.product_id
					WHERE c.user_id = '" . addslashes($_SESSION["sess_userid"]) . "'";
} else {
    $sql = "SELECT c.*, p.product_name,(p.product_price+po.additional_price) AS product_price,po.discount,p.product_artist_id
					FROM " . $tableprefix . "cart c
                                        INNER JOIN " . $tableprefix . "product_options po ON po.product_option_id = c.product_option_id
                                        INNER JOIN " . $tableprefix . "products p ON p.product_id = po.product_id
                                        WHERE c.visitor_cart_id = '" . addslashes(session_id()) . "' ";
}



$res = mysql_query($sql);

if (mysql_num_rows($res) > 0) {
    ?>		

                    <fieldset>
                        <div class="shopcart_list">
                            <table width="100%"  border="0" cellspacing="1" cellpadding="6">	
                                <tr class="shopcart_heads">
                                    <td width='4%'>&nbsp;</td>
                                    <td width='39%'><b><?php echo PRODUCTS_TEXT; ?></b></td>
                                    <td width='19%'><b><?php echo QUANTITY_TEXT; ?></b></td>
                                    <td width='22%'><b><?php echo RATE_TEXT; ?></b></td>
                                    <td width='16%'><b><?php echo PRICE_TEXT; ?></b></td>
                                </tr>
                                <tr>
                                    <td colspan="5"></td>
                                </tr>


                    <?php
                    $cntt = 0;
                    $currency_attributes = displayCurrencyType();
                    while ($rw = mysql_fetch_array($res)) {
                        $cntt++;

                        $productname = $rw["product_name"];
                        $product_option_id = $rw["product_option_id"];
                        $check = "<input type='checkbox' class='checkbox' name='chkitems[]' value='" . $rw["cart_id"] . "' > ";

                        $qtytextbox = "<input  type='text' id='txtQuantity_" . $cntt . "' name='txtQuantity_" . $rw["cart_id"] . "' value='" . $rw["quantity"] . "' size='1' maxlength='3' class='textbox' style=\"width:20px\" > ";

                        /* ------------Multicart 2.0 Upgradation------------ */

                        // Currency Conversion 

                        $conversionRate = ConvertedCurrencyRate($currency_attributes[2]);
                        $converted_price = $rw['product_price'] * $conversionRate;

                        $rate = $converted_price;
                        // End currency Conversion
                        /* ------------Multicart 2.0 Upgradation------------ */

                        $qty = $rw["quantity"];
                        $price = $qty * $rate;
                        $discountstr = "";
                        $discountprice = 0;
                        if ($rw["discount"] != "0") {
                            $price = number_format($price, 2, ".", "");
                            $discountprice = $rate - ($rate * $rw["discount"]) / 100;
                            $discountprice = number_format($discountprice, 2, ".", "");
                            $discountrate = ($discountprice * $qty);
                            $price = $discountrate;
                            $discountstr = "<br>discount(" . $rw["discount"] . "%)";
                        }
                        $optionVal = getProductOptionsName($product_option_id);
                        if ($optionVal != "") {
                            $optionsStr = "<br>" . $optionVal;
                        }

                        $total += $price;
                        ?>				
                                    <input type="hidden" value="" name="txtQty_<?php echo $cntt; ?>" id="txtQty_<?php echo $cntt; ?>" />
                                    <input type="hidden" value="<?php echo $rw["quantity"]; ?>" name="hdQty_<?php echo $cntt; ?>" id="hdQty_<?php echo $cntt; ?>" />
                                    <tr>
                                        <td width='4%' ><?php echo $check ?></td>
                                        <td align='left'><?php echo stripslashes($productname) . $discountstr . $optionsStr; ?></td>
                                        <td align='left'><?php echo $qtytextbox ?></td>
                                        <td align='left'>
                                    <?php if ($rw["discount"] != "0") {
                                        ?>
                                        <?php echo $currency_attributes[0] . "&nbsp;" . $discountprice; ?>
                                                &nbsp;
                                                ( <strike><?php echo $currency_attributes[0] . "&nbsp;" . number_format($rate, 2, ".", ""); ?></strike>)

                                        <?php
                                    } else {
                                        ?>
                                        <?php echo $currency_attributes[0] . "&nbsp;" . number_format($rate, 2, ".", ""); ?>
                                    <?php } ?>
                                    </td>
                                    <td align='left'>
                                    <?php echo $currency_attributes[0] . "&nbsp;" . number_format($price, 2, ".", ""); ?></td>
                                    <input type='hidden' value='<?php echo $rw["product_artist_id"] ?>' name='sellerid[]'>
                                    </tr>

                                    <?php
                                    $cartitems .= "," . $rw["cart_id"];
                                    //if click continue shopping its redirect to corresponding category
                                    //store last added product category
                                    if (trim($redirect) == '') {
                                        $redirect = $rw["product_category"];
                                    }//end if
                                }
                                $cartitems = substr($cartitems, 1);
                                ?>			
                                <input type="hidden" value="<?php echo $cntt ?>" id="cntt" name="cntt">
                                <tr>
                                    <td  colspan='4' align='right'><b><?php echo TOTAL_TEXT;?></b>&nbsp;</td>
                                    <td align='left'><b><?php echo $currency_attributes[0] . "&nbsp;" . number_format($total, 2, ".", "") ?></b></td>
                                </tr>

                                <tr>
                                    <td colspan='6' align='center'>
                                        <input type='hidden' value='<?php echo $cartitems ?>' name='cartitems'>&nbsp;&nbsp;
                                        &nbsp;&nbsp;
                                        <input type='submit' value='<?php echo DELETE_SELECTED_BUTTON; ?>' name='btnDeleteSelected' class='button'>&nbsp;&nbsp;
                                        <!----Multicart 2.0 starts---->	
                                        <input type='submit' value='<?php echo UPDATE_QUANTITIES_BUTTON; ?>' name='btnUpdateQuantities' class='button'>&nbsp;&nbsp;
                                        <!----Multicart 2.0 ends---->	
                                <?php
                                echo "<input type='submit' value='".CHECKOUT_BUTTON."' name='btnCheckout'  id='btnCheckout' class='button' onClick='return checkOutCart()'>&nbsp;&nbsp;
			<input type='button' class='button'  value='".CONTINUE_SHOPPING_BUTTON."' onClick='window.location.href=\"categorydetail.php?catid=" . $redirect . "\"'>
			&nbsp;&nbsp;
			</td></tr></table>
				</fieldset>";
                            } else {

                                echo "<table width=\"100%\"  border=\"0\" cellspacing=\"1\" cellpadding=\"6\">";
                                echo "<tr class=\"text_information\"><td width='100%' align='center'><h2>".CART_EMPTY_MSG."</h2></td></tr>";
                                echo "<tr class=\"whitebg\"><td width='100%' >&nbsp;</td></tr>";
                                echo "<tr class=\"whitebg\"><td width='100%' align='center'><input type='button' class='button'  value='".CONTINUE_SHOPPING_BUTTON."' onClick='window.location.href=\"index.php\"'></td></tr></table>";
                            }
                            ?>
                        </table>
                        <div class="clear"></div>
                    </div>
            </div>	
            <div align="left" class="float_clear1"></div>
            <!--items display area end -->
        </div>
    </form>
    <!--center content area end-->	
    <div align="left" class="clear"></div>		
    <!--mainbody area end -->
</div>
<div align="left" class="clear"></div>
<?php
include "includes/" . $active_template[2]; /* Bottom File Name */
?>