<?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";
include_once "classes/cls_cart.php";
include_once "classes/cls_products.php";
include_once "classes/cls_user.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;
         case "no_permission": $message = NO_PERMISSION_PURCHASE_PRODUCT."<br>";
            break;
        default:
            ;
    } // switch
}


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

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

$sql = "SELECT enable_free_shipping,min_order_amount  FROM ".$tableprefix."settings ";
$res = mysql_query($sql);

if(mysql_num_rows($res)>0)
{
    $row = mysql_fetch_array($res);
    $freeShipEnable = $row['enable_free_shipping'];
    $freeShipOrderAmt = $row['min_order_amount'];
    
}

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"]);        
        $noFloat = ($value==$_POST["$var"])?1:0;      
      
        if ($value > 0 && $noFloat==1) {
            $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;
}

$active_template = displayTemplate();


include "includes/htmltop.php";

/* Top File Name */

include_once ("includes/" . $active_template[0]);


//****************************************************Multicart3.0 Modifications*****************************
 if($_SESSION["sess_userid"]!='')  {
                            //Check the product is logged users product
                            $sellerAccObj   =    User::is_seller_account_activated($_SESSION["sess_userid"]);
                                  //echopre($sellerAccObj);
                                if($sellerAccObj->status==SUCCESS)
                                    {
                                            $sellerAccObjVal            =   $sellerAccObj->data;
                                            $seller_activated_status    =   $sellerAccObjVal->is_seller;
                                            $activated_seller_id        =   $sellerAccObjVal->seller_id;

                                    }
          // Check logged sellers product exist in cart // if single account enabled for buyer and seller

            $sellerCartObj      =    Cart::getCartCountBySellerId($_SESSION["sess_userid"],$visitorId,$activated_seller_id);
       //     echopre($sellerCartObj);
            if($sellerCartObj->status==SUCCESS)
                    {
                         $sellerCartObjVal      =   $sellerCartObj->data;

                         $samesellerItemCount   =   $sellerCartObjVal->selleritemCount;
                    }
                    
            //Hide showing same message multiple times        
                 if(($samesellerItemCount>0) && ($_REQUEST['msg']=='no_permission'))
                 {
                     $message = '';
                 }

            }

//**********************************************Multicart3.0  Modifications**********************************
?>
<script>
    //window.location = "./viewcart.php";
		
    function checkOutCart()
    {
        var sameSellerItemCount     =   '<?php echo $samesellerItemCount;?>';
        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 if(sameSellerItemCount>0) {
            alert("<?php echo NO_PERMISSION_PURCHAPRODUCT_TAG_TEXTSE_MARKED_PRODUCT;?>");
            return false;
        }
        else
        {
            return true;
        }
    }
</script>	
<!--mainbody area start -->
<div class="main_body">
	<div class="container">
		<div class="row">
    	<!--center content area start-->		
		<section class="sec_marg">
		<div class="col-sm-12 col-lg-12 col-md-12 ">
			<h3><?php echo SHOPPING_CART_TEXT; ?></h3>
		</div>
		</section>
		<div class="clear"></div>
		<div class="col-sm-12 col-lg-12 col-md-12 ">
    	<form name="frmCart" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, 'UTF-8') ?>" method="POST">
        <div align="left" id="item_details">
            <!--items display area start -->

<?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
						 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_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['gift_product_flag']=='Y' ) {
               
                $delObj     =    Cart::clearNonGiftItemsinCart($_SESSION["sess_userid"],session_id());
              
            }
        }
        $_SESSION['gift_certificate_flag'] = $rw_cart['gift_product_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);
//***********************Multicart3.0 Addition***********************************************

//check digital products count in cart
 if($_SESSION["sess_userid"]!='') 
     {
         $visitorId     =  '';
     }else{
         $visitorId     = generalMethods::sessionid();
     }

 $objDigitalCart                        =     Cart::getDigitalItemsCartCount($_SESSION["sess_userid"],$visitorId);
 if($objDigitalCart->status==SUCCESS)
 {
        $cartDigitalObjVal         =    $objDigitalCart->data;
        $cartDigitalCount          =    $cartDigitalObjVal->digitalcount;  
 }

//***********************Multicart3.0 Addition****************************************************                


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

                <div class="shopcart_list" style="padding-bottom: 0px;">
                            <table width="100%"  border="0" cellspacing="1" cellpadding="6" class="responsive">	
                                <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>

                                <?php if($samesellerItemCount>0) { ?>
                                 <tr>
                                     <td colspan="5" class="warning"> <?php echo NO_PERMISSION_PURCHAPRODUCT_TAG_TEXTSE_MARKED_PRODUCT;?></td>
                                    
                                </tr>
                                <?php } ?>
                             <?php if($cartDigitalCount>0)   { ?> 
                                <tr>
                                    <td></td>
                                    <td width="30%"><img src="<?php echo SITE_URL?>/images/digital_icon.png" alt="<?php echo DIGITAL_PRODUCT_FLAG;?>" title="<?php echo DIGITAL_PRODUCT_FLAG;?>"> &nbsp;&nbsp; <?php echo DIGITAL_PRODUCT_MARK_TEXT;?></td>
                                    <td colspan="3"><!--<img src="<?php echo SITE_URL?>/images/subscription_icon.jpg" alt="<?php echo SUBSCRIPTION_PRODUCT_FLAG;?>" title="<?php echo SUBSCRIPTION_PRODUCT_FLAG;?>"> &nbsp;&nbsp; <?php echo SUBSCRIPTION_PRODUCT_MARK_TEXT;?>--></td>
                                </tr>
                             <?php } ?>
                                
                                <tr>
                                    <td colspan="5"></td>
                                </tr>


                    <?php
                    $cntt = 0;
                    $currency_attributes = displayCurrencyType();
                    $flag_single_account_flag   =   '';
                    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 qty_txtbox'> ";

                        /* ------------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>".strtolower(MAIL_ORDER_TEXT_DISCOUNT)."(" . $rw["discount"] . "%)";
                        }
                        $optionVal = getProductOptionsName($product_option_id);
                        if ($optionVal != "") {
                            $optionsStr = "<br>" . $optionVal;
                        }

                        $total += $price;
                        
                        
                        //*************Multicart3.0 Additions Check cart item is digital product or not 
                        
                        $objRow     =   Cart::isDigitalIteminCart($rw['cart_id']);
                      
                        if($objRow->status==SUCCESS)
                        {
                            $digitalFlag  = $objRow->data; 
                        }
                        //*************Multicart3.0 Additions Check cart item is subscription product or not 
                        
                        $objSubRow     =   Cart::isSubscriptionIteminCart($rw['cart_id']);
                      
                        if($objSubRow->status==SUCCESS)
                        {
                            $subscriptionFlag  = $objSubRow->data; 
                        }  
                     
                        // Free ship text display 
                        
                        $freeship_flag_text    =   Products::check_free_ship_product_text($rw["product_id"]);
                                               
                        // Mark same seller items in cart to remove // Applicable if single account for seller and buyer

                            if($activated_seller_id==$rw['seller_id'])
                            {
                                 $flag_single_account_flag_class   =   'tr_bg_warning';
                            }
                            else{
                                $flag_single_account_flag_class   =   '';
                            }
                        
                        ?>				
                                    <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 class="<?php echo $flag_single_account_flag_class;?>">
                                        <td width='4%' ><?php echo $check ?></td>
                                        <td align='left'><?php if($digitalFlag=='Y') { ?><img src="<?php echo SITE_URL?>/images/digital_icon.png" alt="<?php echo DIGITAL_PRODUCT_FLAG;?>" title="<?php echo DIGITAL_PRODUCT_FLAG;?>"> &nbsp;<?php } ?>
                                                   <!--<?php  /*elseif($subscriptionFlag == 'Y'){*/ ?><img src="<?php echo SITE_URL?>/images/subscription_icon.jpg" alt="<?php echo SUBSCRIPTION_PRODUCT_FLAG;?>" title="<?php echo SUBSCRIPTION_PRODUCT_FLAG;?>"> &nbsp;<?php //} ?> -->
                                                     <?php echo stripslashes($productname) . $discountstr . $optionsStr ; ?> <span class="freeship_text"> <?php echo $freeship_flag_text;?> </span></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);
                                
                              
                                if($freeShipEnable=="Y"){
                                    $freeshipAmt = round($freeShipOrderAmt);
                                    if(round($total)>=$freeshipAmt){
                                       $freeShipOrderMSg = ORDER_QUALIFIES_FREE_SHIPPING;
                                        
                                    }else{
                                        $freeShipOrderMSg = ORDER_FREE_SHIPPING_AVAILABLE.' '.$currency_attributes[0].''.$freeShipOrderAmt;
                                    }
                                }
                                
                                ?>			
                                <input type="hidden" value="<?php echo $cntt ?>" id="cntt" name="cntt">
                                <tr>
                                    <td  colspan='4' align='right' class="total_td_left"><?php echo TOTAL_TEXT;?>&nbsp;</td>
                                    <td align='left' class="total_td_right"><?php echo $currency_attributes[0] . "&nbsp;" . number_format($total, 2, ".", "") ?></td>
                                </tr>
                                <?php if($freeShipOrderMSg!=''){ ?>
                                <tr>
                                    <td align="center" class="total_td_left" colspan="5" style=" background: #f0f0f0 none repeat scroll 0 0;
                                        font-size: 11px;
                                        font-weight: bold;
                                        padding: 2px;
                                        text-align: center;"><?php echo $freeShipOrderMSg; ?> 
                                    </td>
                                </tr>
                                <?php } ?>

                                       
                        </table>
                        <div class="clear"></div>
                    </div>
						<div class="cart_view_btm">
							<div class="row">
            					<div class="col-xs-12 col-sm-12 col-lg-6 col-md-6 ">
							     <input type='hidden' value='<?php echo $cartitems ?>' name='cartitems'>
                                                         <input type='submit' value='<?php echo DELETE_SELECTED_BUTTON; ?>' name='btnDeleteSelected' class='cart_dltbtn'>
                                        <!----Multicart 2.0 starts---->	
                                        <input type='submit' value='<?php echo UPDATE_QUANTITIES_BUTTON; ?>' name='btnUpdateQuantities' class='cart_updtbtn'>
                                        <!----Multicart 2.0 ends---->	
                                </div>
								<div class="col-xs-12 col-sm-12 col-lg-6 col-md-6 ">
									<?php echo "<input type='submit' value='".CHECKOUT_BUTTON."' name='btnCheckout'  id='btnCheckout' class='button checkoutbtn' onClick='return checkOutCart()'>"; ?>
									<input type='button' class='cart_contshopbtn'  value='<?php echo CONTINUE_SHOPPING_BUTTON;?>' onClick='window.location.href="categorydetail.php?catid="<?php echo $redirect;?>'>
								</div>
							</div>
								<?php
                            } else {

                                echo "<table class=\"emptycart\" width=\"100%\"  border=\"0\" cellspacing=\"1\" cellpadding=\"0\">";
                                echo "<tr class=\"text_information\"><td width='100%' align='center'><h4>".CART_EMPTY_MSG."</h4></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>";
                            }
                            ?>
						</div>
            </div>	
            <!--items display area end -->
    </form>
	</div>
    <!--center content area end-->	
    <div align="left" class="clear"></div>	
		
	</div>
	</div>
</div>
<!--mainbody area end -->
<div align="left" class="clear"></div>
<?php
include "includes/" . $active_template[2]; /* Bottom File Name */
?>
