<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | PHP version 4/5                                                      |
// +----------------------------------------------------------------------+
// | This source file is a part of iScripts Multicart                     |
// +----------------------------------------------------------------------+
// | Authors: Programmer<programmer@armia.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);
    $_SESSION = array_map('stripslashes_deep', $_SESSION);
}
if (isset($_SESSION["sess_userid"]) and $_SESSION["sess_userid"] != "") {
    $userid = $_SESSION["sess_userid"];
}

if (isCartEmpty($userid)) {
    header("Location:viewcart.php");
    exit;
}
$txtCCNumber = $_POST["txtCCNumber"];
$txtCVV2 = $_POST["txtCVV2"];
$txtMM = $_POST["txtMM"];
$txtYY = $_POST["txtYY"];

$txtFirstName = $_SESSION["sessBillingFirstName"];
$txtLastName = $_SESSION["sessBillingLastName"];
$txtAddress = $_SESSION["sessBillingAddress1"];
$txtCity = $_SESSION["sessBillingCity"];
$txtState = $_SESSION["sessBillingState"];
$txtZIP = $_SESSION["sessBillingZIP"];
$txtEmail = $_SESSION["sessBillingEmail"];
$ddlCountry = $_SESSION["sessBillingCountry"];
$txtPhone = $_SESSION["sessBillingPhone"];

$gift_coupon_flag = 0;

/* payment calculation based on currency type */

$currency_attributes = displayCurrencyType();
//$totaltopay = number_format((getCartTotal($userid)),2,".","");


if (isset($_SESSION['couponCode_det'])) {
    $totaltopay = number_format((getCartTotalcouponCode($userid, $_SESSION['couponCode_det'])), 2, ".", "");
} else {
    $totaltopay = number_format((getCartTotal($userid)), 2, ".", "");
}


//$totaltopay = getCartTotal($userid);

$paymentMethod = "CC";

//getting payment info
$sql = "SELECT * FROM " . $tableprefix . "settings ";
$res = mysql_query($sql);
$row = mysql_fetch_array($res);

$txtYourpayStoreId = $row["vyourpay_storeid"];
$pemfolder = $row["vyourpay_certificate_file"];

$txtUrPayDemo = $row["vyourpay_mode"];

$txtCurrency = $currency_attributes[2];

/* $txtAuthorizeEmail = $row["authorize_email"];
  $txtAuthorizeTestMode = $row["authorize_test_mode"];
  if($txtAuthorizeTestMode == "Y"){
  $txtAuthorizeTestMode = "on";
  }else{
  $txtAuthorizeTestMode = "off";
  }

 */

/* -------function call to check whether cart contains digital or gift coupon products so as to hide shipping--- */

$hide_shipping_division = hideShipping();

/* -------function call to check whether cart contains digital or gift coupon products so as to hide shipping------ */

$check_shipping_enable = checkShippingEnable();

if ($_POST["btnCompleteOrder"] == "Complete Order") {
    $message = "";

    $paymentsuccessful = false;
    $paymenterror = "";
    $referrer = $_SERVER["HTTP_REFERER"];
    $qry1 = "select max(order_id)+1 as ordid from " . $tableprefix . "orders";
    $excqry1 = mysql_query($qry1);
    $row1 = mysql_fetch_array($excqry1);
    $Inv_id = $row1['ordid'];


    $Cust_id = $_SESSION["sess_userid"];
    $Cust_ip = getClientIP();
    $Company = "-NA-";
    $Phone = $txtPhone;
    if ($txtLastName == "")
        $txtLastName = "-NA-";

    require "yourpay.php"; //process the card and return result. Comment this line and uncomment the two lines below to make payment test mode
    //$paymentsuccessful = true;
    // = "TEST1234444";
    if ($paymentsuccessful) {//payment successful, so update database
        //echo "Payment Successful<br>";
        //exit;
        $sql = "INSERT INTO  " . $tableprefix . "orders (
				user_id,
				billing_first_name,
				billing_last_name,
				billing_address1,
				billing_address2,
				billing_city,
				billing_state,
				billing_country,
				billing_zip,
				billing_fax,
				billing_email,
				billing_phone,
				shipping_first_name,
				shipping_last_name,
				shipping_address1,
				shipping_address2,
				shipping_city,
				shipping_state,
				shipping_country,
				shipping_zip,
				shipping_fax,
				shipping_email,
				shipping_phone,
				prefered_shippin_method,
				order_date,
				order_total_price,
				order_status,
				vorder_currency
				) VALUES(
				'" . addslashes($_SESSION["sess_userid"]) . "',
				'" . addslashes($_SESSION["sessBillingFirstName"]) . "',
				'" . addslashes($_SESSION["sessBillingLastName"]) . "',
				'" . addslashes($_SESSION["sessBillingAddress1"]) . "',
				'" . addslashes($_SESSION["sessBillingAddress2"]) . "',
				'" . addslashes($_SESSION["sessBillingCity"]) . "',
				'" . addslashes($_SESSION["sessBillingState"]) . "',
				'" . addslashes($_SESSION["sessBillingCountry"]) . "',
				'" . addslashes($_SESSION["sessBillingZIP"]) . "',
				'" . addslashes($_SESSION["sessBillingFAX"]) . "',
				'" . addslashes($_SESSION["sessBillingEmail"]) . "',
				'" . addslashes($_SESSION["sessBillingPhone"]) . "',
				'" . addslashes($_SESSION["sessShippingFirstName"]) . "',
				'" . addslashes($_SESSION["sessShippingLastName"]) . "',
				'" . addslashes($_SESSION["sessShippingAddress1"]) . "',
				'" . addslashes($_SESSION["sessShippingAddress2"]) . "',
				'" . addslashes($_SESSION["sessShippingCity"]) . "',
				'" . addslashes($_SESSION["sessShippingState"]) . "',
				'" . addslashes($_SESSION["sessShippingCountry"]) . "',
				'" . addslashes($_SESSION["sessShippingZIP"]) . "',
				'" . addslashes($_SESSION["sessShippingFAX"]) . "',
				'" . addslashes($_SESSION["sessShippingEmail"]) . "',
				'" . addslashes($_SESSION["sessShippingPhone"]) . "',
				'" . addslashes($_SESSION["sessShippingMethod"]) . "',
				now(),
				'" . addslashes($_POST['cart_total']) . "',
				'1',
				'USD'
				)";
        mysql_query($sql);
        $orderid = mysql_insert_id();


        if ($check_shipping_enable == "Y" && $hide_shipping_division == 1) {

            /* ---------------update the shipping details---------------- */


            $select_cart_products = "SELECT product_id FROM " . $tableprefix . "cart
							 		 WHERE user_id = " . $_SESSION["sess_userid"];

            $result_cart_products = mysql_query($select_cart_products) or die(mysql_error());

            if (mysql_num_rows($result_cart_products) > 0) {

                while ($cart_row = mysql_fetch_array($result_cart_products)) {


                    $update_shipping = "UPDATE " . $tableprefix . "shipping_details
										SET norder_id = " . $orderid . ",
											vshipping_currency = 'USD',
											dshipped_date = now(),
											nshp_status = 'C'
										WHERE nshp_productid = " . $cart_row['product_id'] . "
										 AND nshp_status = 'P'";

                    mysql_query($update_shipping) or die(mysql_error());
                } // end while
            } // end if
        } // end of shipping if



        /*         * ************************ Affilate payment block******************************************** */

        $sql = "select * from  " . $tableprefix . "users where user_id='" . addslashes($_SESSION["sess_userid"]) . "'";
        $result = mysql_query($sql);
        $row = mysql_fetch_array($result);
        if ($row["affiliate_id"] != "" && $row["affiliate_id"] != "0" && $row["vaff_type"] != "paid") {
            $aid = $row['affiliate_id'];
            $userid = $row['user_id'];
            $txtUserName = $row['user_name'];
            $txtFirstName = $row['first_name'];
            $txtEmail = $row['email'];
            $txtorderdamount = $_POST['cart_total'];
            $sql1 = "SELECT * FROM " . $tableprefix . "settings ";
            $result1 = mysql_query($sql1);
            if (mysql_num_rows($result1) != 0) {
                $row1 = mysql_fetch_array($result1);

                $txtReferralCharge = $row1["referral_charge"];
            }
            $var_aff_comm = ($txtorderdamount * $txtReferralCharge / 100);

            $sql2 = "INSERT INTO " . $tableprefix . "affiliate_registrations (
											affiliate_id,
											user_id,
											user_name ,
											user_first_name,
											user_last_name,
											user_email,
											referral_charge,
											registration_date,
											user_totalpurchasedamount
											) VALUES (
											'" . addslashes($aid) . "',
											'" . addslashes($userid) . "',
											'" . addslashes($txtUserName) . "',
											'" . addslashes($txtFirstName) . "',
											'" . addslashes($txtLastName) . "',
											'" . addslashes($txtEmail) . "',
											'" . addslashes($var_aff_comm) . "',
											now()," . $_POST['cart_total'] . "
											)";
            mysql_query($sql2);

            $sql3 = " update " . $tableprefix . "users set vaff_type='paid' where user_id='" . addslashes($_SESSION["sess_userid"]) . "'";
            $result3 = mysql_query($sql3);
        }

        /*         * ************************ Affilate payment block******************************************** */

        $product_download_details = "Product Download Details\r\n";
        $product_download_details .= "-----------------------\r\n";
        $product_download_flag = 0;
        $download_link = "";

        //$orderid = mysql_insert_id();
        $sql = "SELECT c.*,p.product_price,p.product_name,p.product_code,p.product_artist_id,p.discount,
					   p.vdigital_product 
				FROM " . $tableprefix . "cart c INNER JOIN " . $tableprefix . "products p ON c.product_id = p.product_id
				WHERE c.user_id = '" . addslashes($_SESSION["sess_userid"]) . "' ";
        $res = mysql_query($sql);
        $artists = array();
        if (mysql_num_rows($res) != 0) {
            $i = 0;
            while ($row = mysql_fetch_array($res)) {
                $productid = $row["product_id"];
                $quantity = $row["quantity"];

                /* product price is calculated based on currency type */

                //$productprice = number_format(($currency_attributes[1] * $row["product_price"]),2,".","");

                $productprice = $row["product_price"];

                $productname = $row["product_name"];
                $productcode = $row["product_code"];
                $productdiscount = $row["discount"];
                $artistid = $row["product_artist_id"];


                /* -------------------mail sending gift coupon code starts---------------------- */



                /* $select_gift_details = "SELECT usrs.email,crt.product_id
                  FROM ".$tableprefix."users usrs,".$tableprefix."cart crt
                  WHERE crt.user_id = usrs.user_id
                  AND crt.user_id = ".$_SESSION["sess_userid"];

                  $result_gift_details = mysql_query($select_gift_details) or die(mysql_error());

                  while($gift_row = mysql_fetch_array($result_gift_details))
                  { */ // start of while loop

                $select_gift_code = "SELECT vgift_coupon_code,ngift_coupon_amount
								 FROM " . $tableprefix . "giftcoupon_master
								 WHERE ngift_product_id = " . $productid;

                $result_gift_code = mysql_query($select_gift_code) or die(mysql_error());

                if (mysql_num_rows($result_gift_code) > 0) { // start of first if
                    $gift_coupon_product_id = $productid;

                    while ($gift_code_row = mysql_fetch_array($result_gift_code)) { // start of while 2

                        /* --------------------creating random gift coupon code and updating the database----------------------- */

                        $gift_coupon_code = "GC" . randomGiftCouponKey();


                        if ($gift_code_row['vgift_coupon_code'] == "") { // start of coupon code null checking


                            /* -----------updating the gift coupon code------------ */

                            $update_gift_coupon_code = "UPDATE " . $tableprefix . "giftcoupon_master
													SET vgift_coupon_code = '" . $gift_coupon_code . "',
													ngift_order_id  = " . $orderid . "
													WHERE ngift_product_id = " . $productid;

                            mysql_query($update_gift_coupon_code) or die(mysql_error());

                            $gift_coupon_link .= "Certificate Code :- " . $gift_coupon_code . "\r\n";
                            $gift_coupon_link .= "Certificate Amount :- " . $productprice . "\r\n\n";

                            $select_coupon_count = "SELECT ngift_id FROM " . $tableprefix . "giftcoupon_master WHERE ngift_order_id = " . $orderid;

                            $result_coupon_count = mysql_query($select_coupon_count) or die(mysql_error());

                            for ($i = 1; $i < $row["quantity"]; $i++) { // start of for loop
                                $gift_coupon_code = "GC" . randomGiftCouponKey();

                                $insert_coupon_code = "INSERT INTO " . $tableprefix . "giftcoupon_master(vgift_coupon_code,ngift_product_id,
															ngift_order_id,ngift_coupon_amount,vgift_currency)
															VALUES('" . $gift_coupon_code . "',
															" . $row["product_id"] . ",
															" . $orderid . ",
															" . $productprice . ",
															'USD')";

                                mysql_query($insert_coupon_code) or die(mysql_error());

                                $gift_coupon_link .= "Certificate Code :- " . $gift_coupon_code . "\r\n";
                                $gift_coupon_link .= "Certificate Amount :- " . $productprice . "\r\n\n";
                            } // end of for loop
                        } // end of coupon code null checking
                        else {
                            /* ----------if coupon code is not null-------------- */


                            $select_coupon_count = "SELECT ngift_id FROM " . $tableprefix . "giftcoupon_master WHERE ngift_order_id = " . $orderid;

                            $result_coupon_count = mysql_query($select_coupon_count) or die(mysql_error());


                            if (mysql_num_rows($result_coupon_count) < $row["quantity"]) {

                                $insert_coupon_code = "INSERT INTO " . $tableprefix . "giftcoupon_master(vgift_coupon_code,ngift_product_id,
														ngift_order_id,ngift_coupon_amount,vgift_currency)
														VALUES('" . $gift_coupon_code . "',
														" . $row["product_id"] . ",
														" . $orderid . ",
														" . $productprice . ",
														'USD')";

                                mysql_query($insert_coupon_code) or die(mysql_error());

                                $gift_coupon_link .= "Certificate Code :- " . $gift_coupon_code . "\r\n";
                                $gift_coupon_link .= "Certificate Amount :- " . $productprice . "\r\n\n";
                            }
                        }
                    } // end of while 2

                    $gift_coupon_flag = 1;
                } // end of first if
                //} // end of while loop




                if ($gift_coupon_flag == 1) { // start of if condition

                    /* -------Email Template Reading Fuction Call-------- */


                    $select_user_email = "SELECT email FROM " . $tableprefix . "users WHERE user_id = " . $_SESSION["sess_userid"];
                    $result_user_email = mysql_query($select_user_email) or die(mysql_error());

                    if (mysql_num_rows($result_user_email) > 0) {

                        $user_email_row = mysql_fetch_assoc($result_user_email);
                        $txtEmail = $user_email_row['email'];
                    }


                    $mailcontent = readEmailTemplate('gift_coupon');
                    $mailcontent = str_replace('[coupon_details]', $gift_coupon_link, $mailcontent);

                    $subject = "Gift Certificate Order placed at " . SITE_NAME;

                    $headers = "MIME-Version: 1.0" . "\r\n";
                    $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
                    $headers .= "From: " . SITE_EMAIL . "<" . SITE_EMAIL . ">" . "\r\n";

                    /* ------------Seller Store Url--------------------- */

// send the friendly url in mail based on config settings

                    if ($enable_seller_friendly == "Y") {

                        $select_seller_name = "SELECT artist_name FROM " . $tableprefix . "artists WHERE artist_id = " . $artistid;
                        $result_seller_name = mysql_query($select_seller_name) or die(mysql_error());

                        if (mysql_num_rows($result_seller_name) > 0) {

                            $seller_name_row = mysql_fetch_assoc($result_seller_name);
                            $txtSellerName = $seller_name_row['artist_name'];
                        }

                        $friendly_url = SITE_URL . "/store/" . $txtSellerName;
                    } else {


                        $friendly_url = SITE_URL . "/showportfolio.php?artistid=" . $artistid;
                    }

                    $mailcontent .= "\n\n*-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*\r\n";
                    $mailcontent .= "\r\n" . "<font color='#FF0000'>You can purchase products using this Gift Certificate from the seller store below</font>" . "\r\n\n";
                    $mailcontent .= "<b>" . $friendly_url . "</b>";

                    /* ------------Seller Store Url--------------------- */

                    $mailcontent = nl2br($mailcontent);

                    $mail_send_details = "<html><head><link href='" . SITE_URL . "/style/template1-admin.css' rel='stylesheet' type='text/css'></head><body><center><div align='left' id='layout'><div align='left' class='header'><div align='left' class='logo'><img src=" . $logofolder . "/" . $logoimage . " width='125' height='39'/></div></div><div>" . $mailcontent . "</div></div><div align='left' class='clear_float'><img src=" . $imagefolder . "/clear.gif width=1 height=1/></div></div></div></center></body></html>";

                    mail($txtEmail, $subject, $mail_send_details, $headers);
                }// end of if condition

                /* ----------------------mail sending gift coupon code ends------------------------ */


                /* ------------------Digital Product Download Starts------------- */

                if ($row['vdigital_product'] == "Y") {

                    $digital_product_id = $row["product_id"];

                    $select_product_digital_code = "SELECT vdigital_product_name,vdigital_product_code,ndownload_try,ndownload_expiry,ndownload_expiry_days
														FROM " . $tableprefix . "digital_product
														WHERE ndigital_productid = " . $row["product_id"];

                    $result_product_digital_code = mysql_query($select_product_digital_code);

                    if (mysql_num_rows($result_product_digital_code) > 0) {
                        while ($product_digital_code_row = mysql_fetch_array($result_product_digital_code)) {

                            /* creating random product download code and updating the database */

                            $digital_product_code = randomDigitalProduct();

                            if ($product_digital_code_row['vdigital_product_code'] == "") {

                                /* -------Calculating the download expiry days---------- */

                                /* $select_digital_product_expiry = "SELECT ndownload_expiry_days FROM ".$tableprefix."digital_product
                                  WHERE ndigital_productid = ".$row["product_id"];
                                  $result_digital_product_expiry = mysql_query($select_digital_product_expiry) or die(mysql_error());

                                  $digital_product_expiry_row = mysql_fetch_assoc($result_digital_product_expiry); */

                                $expiry_days = $product_digital_code_row['ndownload_expiry_days'];

                                $valid_date_upto = date("Y-m-d H:s:m", mktime(date("H"), date("i"), date("s"), date("m"), date("d") + $expiry_days, date("Y")));

                                /* -------Calculating the download expiry days---------- */

                                $update_product_digital_code = "UPDATE " . $tableprefix . "digital_product
																	SET vdigital_product_code = '" . $digital_product_code . "',
																	ndigital_orderid = " . $orderid . ",
																	ndownload_expiry = '" . $valid_date_upto . "'
																	WHERE ndigital_productid = " . $row["product_id"];

                                mysql_query($update_product_digital_code) or die(mysql_error());

                                /* ---------selecting the download try and download expiry date----------- */

                                $select_digital_product_details = "SELECT ndownload_try,ndownload_expiry
													   				   FROM " . $tableprefix . "digital_product WHERE ndigital_productid = " . $productid;
                                $result_digital_product_details = mysql_query($select_digital_product_details) or die(mysql_error());

                                $digital_product_details_row = mysql_fetch_assoc($result_digital_product_details);

                                $product_download_try = $digital_product_details_row["ndownload_try"];
                                $download_expiry_date = $digital_product_details_row["ndownload_expiry"];

                                /* ---------selecting the download try and download expiry date----------- */

                                $download_link .= "Download Link - " . SITE_URL . "/digital_product_download.php?download_code=$digital_product_code\r\n";

                                $select_digital_count = "SELECT ndigital_id FROM " . $tableprefix . "digital_product WHERE ndigital_orderid = " . $orderid;

                                $result_digital_count = mysql_query($select_digital_count) or die(mysql_error());



                                //echo "digital count = ".mysql_num_rows($result_digital_count)."\n";
                                //echo "order count = ".$row["quantity"];


                                for ($i = 1; $i < $row["quantity"]; $i++) {

                                //if(mysql_num_rows($result_digital_count) <= $row["quantity"])

                                    /* -------Calculating the download expiry days---------- */

                                    $expiry_days = $product_digital_code_row['ndownload_expiry_days'];

                                    $valid_date_upto = date("Y-m-d H:s:m", mktime(date("H"), date("i"), date("s"), date("m"), date("d") + $expiry_days, date("Y")));

                                    /* -------Calculating the download expiry days---------- */

                                    $digital_product_code = randomDigitalProduct();

                                    $insert_product_digital_code = "INSERT INTO " . $tableprefix . "digital_product(vdigital_product_name,ndigital_productid,
																		ndigital_orderid,vdigital_product_code,ndownload_try,ndownload_count,ndownload_expiry,ndownload_expiry_days,
																		ndownload_status)VALUES('" . $product_digital_code_row['vdigital_product_name'] . "',
																		" . $row["product_id"] . ",
																		" . $orderid . ",
																		'" . $digital_product_code . "',
																		" . $product_digital_code_row['ndownload_try'] . ",0,
																		'" . $valid_date_upto . "'," . $product_digital_code_row['ndownload_expiry_days'] . ",0)";

                                    mysql_query($insert_product_digital_code) or die(mysql_error());

                                    $download_link .= "Download Link - " . SITE_URL . "/digital_product_download.php?download_code=$digital_product_code\r\n";
                                }

                                //exit;
                            } else {

                                $select_digital_count = "SELECT ndigital_id FROM " . $tableprefix . "digital_product WHERE ndigital_orderid = " . $orderid;

                                $result_digital_count = mysql_query($select_digital_count) or die(mysql_error());


                                /* ---------selecting the download try and download expiry date----------- */

                                $select_digital_product_details = "SELECT ndownload_try,ndownload_expiry
													   				   FROM " . $tableprefix . "digital_product WHERE ndigital_productid = " . $productid;
                                $result_digital_product_details = mysql_query($select_digital_product_details) or die(mysql_error());

                                $digital_product_details_row = mysql_fetch_assoc($result_digital_product_details);

                                $product_download_try = $digital_product_details_row["ndownload_try"];
                                $download_expiry_date = $digital_product_details_row["ndownload_expiry"];

                                /* ---------selecting the download try and download expiry date----------- */


                                //for($i=1;$i<$row["quantity"];$i++)
                                if (mysql_num_rows($result_digital_count) < $row["quantity"]) {

                                    /* -------Calculating the download expiry days---------- */

                                    $expiry_days = $product_digital_code_row['ndownload_expiry_days'];

                                    $valid_date_upto = date("Y-m-d H:s:m", mktime(date("H"), date("i"), date("s"), date("m"), date("d") + $expiry_days, date("Y")));

                                    /* -------Calculating the download expiry days---------- */


                                    $insert_product_digital_code = "INSERT INTO " . $tableprefix . "digital_product(vdigital_product_name,ndigital_productid,
																		ndigital_orderid,vdigital_product_code,ndownload_try,ndownload_count,ndownload_expiry,ndownload_status) 
																		VALUES('" . $product_digital_code_row['vdigital_product_name'] . "',
																		" . $row["product_id"] . ",
																		" . $orderid . ",
																		'" . $digital_product_code . "',
																		" . $product_digital_code_row['ndownload_try'] . ",0,
																		'" . $valid_date_upto . "',0)";

                                    mysql_query($insert_product_digital_code) or die(mysql_error());

                                    $download_link .= "Download Link - " . SITE_URL . "/digital_product_download.php?download_code=$digital_product_code\r\n";
                                }
                            }
                        }
                    }

                    $product_download_details .= "Product Name - $productname\r\n";
                    $product_download_details .= "Quantity - $quantity\r\n";
                    $product_download_details .= "Product Download Try - $product_download_try Time(s)\r\n";
                    $product_download_details .= "Download Expiry Date - $download_expiry_date\r\n";
                    $product_download_details .= $download_link;
                    $product_download_flag = 1;
                }


                /* -----------------Digital Product Download Ends---------------- */


                $sql = "INSERT INTO  " . $tableprefix . "order_details (
				order_id,
				product_id,
				product_name,
				product_code,
				product_price,
				product_quantity,
				product_discount,
				artist_id,
				item_status,
				artist_payment_status
				)VALUES(
				'" . addslashes($orderid) . "',
				'" . addslashes($productid) . "',
				'" . addslashes($productname) . "',
				'" . addslashes($productcode) . "',
				'" . addslashes($productprice) . "',
				'" . addslashes($quantity) . "',
				'" . addslashes($productdiscount) . "',
				'" . addslashes($artistid) . "',
				'1',
				'0'
				)";
                mysql_query($sql);
                $artists[$i] = $artistid;
                $i++;
                $sql = "";


                /* --------Updating the order status to 'delivered' if the product purchased is gift coupon------------ */

                if ($gift_coupon_flag == 1) {

                    $update_order_details = "UPDATE " . $tableprefix . "order_details
											 SET item_status = 4 
											 WHERE order_id  = " . $orderid .
                            " AND product_id = " . $gift_coupon_product_id;

                    mysql_query($update_order_details) or die(mysql_error());
                }

                /* --------Updating the order status to 'delivered' if the product purchased is gift coupon------------ */


                /* --------Updating the order status to 'delivered' if the product purchased is digital product------------ */

                if ($product_download_flag == 1) {


                    $update_order_details = "UPDATE " . $tableprefix . "order_details
										 SET item_status = 4 
										 WHERE order_id  = " . $orderid .
                            " AND product_id = " . $digital_product_id." AND item_delivery_date=NOW()";

                    mysql_query($update_order_details) or die(mysql_error());
                }


                /* --------Updating the order status to 'delivered' if the product purchased is digital product------------ */
            }
        }






        /* -----------------Digital Product Mail Sending Starts---------------- */


        if ($product_download_flag == 1) {
             if (function_exists('session_unregister')) {
            (isset($_SESSION['SESS_digital_product'])) ? session_unregister('SESS_digital_product') : session_register('SESS_digital_product');
             }
             else{
                 unset($_SESSION['SESS_digital_product']);
             }
            $_SESSION['SESS_digital_product'] = 1;


            $select_user_email = "SELECT user_name,email FROM " . $tableprefix . "users WHERE user_id = " . $_SESSION["sess_userid"];
            $result_user_email = mysql_query($select_user_email) or die(mysql_error());
            $user_email_row = mysql_fetch_assoc($result_user_email);
            $user_name = $user_email_row['user_name'];

            $product_download_details .= "User Name - $user_name\r\n\n";

            $txtEmailDownload = $user_email_row['email'];
            $subjectDownload = "Digital Product Order placed at " . SITE_NAME;

            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
            $headers .= "From: " . SITE_EMAIL . "<" . SITE_EMAIL . ">" . "\r\n";

            /* -------Email Template reading function call------------ */

            $mailcontent_digital_product = readEmailTemplate('digital_product');

            $product_download_details .= "\n\n*-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*\r\n";
            $product_download_details .= "<font color='#FF0000'>Note: If you do not have pop-ups enabled on your browser, the product download many not work properly.So please enable pop-ups before downloading !!</font>";

            $mailcontent_digital_product = str_replace('[product_details]', $product_download_details, $mailcontent_digital_product);

            $mailcontent_digital_product = nl2br($mailcontent_digital_product);

            $mail_send_details = "<html><head><link href='" . SITE_URL . "/style/template1-admin.css' rel='stylesheet' type='text/css'></head><body><center><div align='left' id='layout'><div align='left' class='header'><div align='left' class='logo'><img src=" . $logofolder . "/" . $logoimage . " width='125' height='39'/></div></div><div>" . $mailcontent_digital_product . "</div></div><div align='left' class='clear_float'><img src=" . $imagefolder . "/clear.gif width=1 height=1/></div></div></div></center></body></html>";

            $mailsent = mail($txtEmailDownload, $subjectDownload, $mail_send_details, $headers);
        }


        /* -----------------Digital Product Mail Sending Ends---------------- */


        $artists = array_values(array_unique($artists));

        $billingaddress = "Billing Address:\n";
        $billingaddress .= "================\n";
        $billingaddress .= $_SESSION["sessBillingFirstName"] . " " . $_SESSION["sessBillingLastName"] . "\n";
        $billingaddress .= $_SESSION["sessBillingAddress1"] . ", " . $_SESSION["sessBillingAddress2"] . "\n";
        $billingaddress .= $_SESSION["sessBillingCity"] . "\n";
        $billingaddress .= $_SESSION["sessBillingState"] . "\n";
        $billingaddress .= $_SESSION["sessBillingCountry"] . "\n";
        $billingaddress .= $_SESSION["sessBillingZIP"] . "\n";
        $billingaddress .= "Phone: " . $_SESSION["sessBillingPhone"] . "\n";
        $billingaddress .= $_SESSION["sessBillingEmail"] . "\n\n";

        $shippingaddress = "Shipping Address:\n";
        $shippingaddress .= "=================\n";
        $shippingaddress .= $_SESSION["sessShippingFirstName"] . " " . $_SESSION["sessShippingLastName"] . "\n";
        $shippingaddress .= $_SESSION["sessShippingAddress1"] . ", " . $_SESSION["sessShippingAddress2"] . "\n";
        $shippingaddress .= $_SESSION["sessShippingCity"] . "\n";
        $shippingaddress .= $_SESSION["sessShippingState"] . "\n";
        $shippingaddress .= $_SESSION["sessShippingCountry"] . "\n";
        $shippingaddress .= $_SESSION["sessShippingZIP"] . "\n";
        $shippingaddress .= "Phone: " . $_SESSION["sessShippingPhone"] . "\n";
        $shippingaddress .= $_SESSION["sessShippingEmail"] . "\n\n";

        /* -------Email Template reading function call------------ */

        $mailcontent_seller = readEmailTemplate('order_notification_seller');

        /* $mailstart = "Dear ".SITE_NAME." seller,\n\n\n";
          $mailstart .= "A new order has been placed for you through the ".SITE_NAME." Site.\n";
          $mailstart .= "The details are as follows.\n\n"; */

        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
        $headers .= "From: " . SITE_EMAIL . "<" . SITE_EMAIL . ">" . "\r\n";


        /* $mailend = "With regards,\n";
          $mailend .= "Adminstrator,  ".SITE_NAME.""; */

        $ordersubject = "New Order placed at " . SITE_NAME . ".";



        for ($k = 0; $k < count($artists); $k++) {
            $sql = "SELECT c.*,p.product_price,p.product_name,p.product_code,p.product_artist_id,p.product_stock,p.reorder_level,p.discount,s.email FROM " . $tableprefix . "cart c INNER JOIN " . $tableprefix . "products p ON c.product_id = p.product_id
		 		INNER JOIN " . $tableprefix . "artists s ON s.artist_id = p.product_artist_id
				WHERE c.user_id = '" . addslashes($_SESSION["sess_userid"]) . "' AND  p.product_artist_id = '" . addslashes($artists[$k]) . "' ";
            $res = mysql_query($sql);
            if (mysql_num_rows($res) != 0) {
                $count = 1;
                $artistid = "";
                $productlist = "";
                $productlist_fillstock = "";
                while ($row = mysql_fetch_array($res)) {
                    $productid = $row["product_id"];
                    $quantity = $row["quantity"];

                    /* product price is calculated based on currency type */

                    //$productprice = number_format(($currency_attributes[1] * $row["product_price"]),2,".","");

                    $productprice = $row["product_price"];

                    $productname = $row["product_name"];
                    $productcode = $row["product_code"];
                    $artistid = $row["product_artist_id"];
                    $artistemail = $row["email"];
                    $discount = $row['discount'] . "%";
                    if ($productlist == "") {
                        $productlist .= "Products\n";
                        $productlist .= "========\n";
                    }
                    $productlist .= $count . "\n";
                    $productlist .= "Product Id: " . $productid . "\n";
                    $productlist .= "Product Code: " . $productcode . "\n";
                    $productlist .= "Product Name: " . $productname . "\n";
                    $productlist .= "Product Price: " . $productprice . "\n";
                    $productlist .= "Discount: " . $discount . "\n";
                    $productlist .= "Quantity: " . $quantity . "\n\n";
                    //send mail to seller when stock less than stock reorder level
                    $currentstock = $row["product_stock"];
                    if ($row["reorder_level"] > 0 and $currentstock <= $row["reorder_level"]) {
                        $mailcontent_fillstock = "Your stock has gone under the reorder level set by you";

                        $productlist_fillstock .= "Product Id: " . $productid . "\n";
                        $productlist_fillstock .= "Product Code: " . $productcode . "\n";
                        $productlist_fillstock .= "Product Name: " . $productname . "\n";
                        $productlist_fillstock .= "Product Price: " . $productprice . "\n";
                        $productlist_fillstock .= "Stock: " . $currentstock . "\n\n";
                    }
                    $count++;
                }
            }

            $mailcontent_details = $productlist;
            $mailcontent_details .= $billingaddress;

            /* ---------Shipping details not available if gift coupon/digital product is purchased--------- */

            if ($gift_coupon_flag != 1 && $product_download_flag != 1) {

                $mailcontent_details .= $shippingaddress;
            }

            $mailcontent_seller = str_replace('[order_details]', $mailcontent_details, $mailcontent_seller);

            $mailcontent_seller = nl2br($mailcontent_seller);

            $mail_send_details = " <html><head><link href='" . SITE_URL . "/style/template1-admin.css' rel='stylesheet' type='text/css'></head><body><center><div align='left' id='layout'><div align='left' class='header'><div align='left' class='logo'><img src=" . $logofolder . "/" . $logoimage . " width='125' height='39'/></div></div><div>" . $mailcontent_seller . "</div></div><div align='left' class='clear_float'><img src=" . $imagefolder . "/clear.gif width=1 height=1/></div></div><div align='center' class='copyright'>Powered by <a href='http://www.iscripts.com/multicart'  target='_blank'><font color='#F4700E'><b>iScripts Multicart</b></font></a>&nbsp;&nbsp;&copy; 2007 iScripts.com. All Rights Reserved </div><div align='left' class='clear_float'><img src='" . SITE_URL . "/images/clear_admin.gif' alt='' width='1' height='1' /></div></div></center></body></html>";

            $mailsent = mail($artistemail, $ordersubject, $mail_send_details, $headers);

            $mailcontent_reorder = "";

            if ($productlist_fillstock != "") {

                /* -------Email Template reading function call------------ */

                $mailcontent_reorder = readEmailTemplate('stock_reorder');
                $mailcontent_reorder = str_replace('[product_details]', $productlist_fillstock, $mailcontent_reorder);
                $mailcontent_reorder = nl2br($mailcontent_reorder);

                $mail_send_details_reorder = "<html><head><link href='" . SITE_URL . "/style/template1-admin.css' rel='stylesheet' type='text/css'></head><body><center><div align='left' id='layout'><div align='left' class='header'><div align='left' class='logo'><img src=" . $logofolder . "/" . $logoimage . " width='125' height='39'/></div></div><div>" . $mailcontent_reorder . "</div></div><div align='left' class='clear_float'><img src=" . $imagefolder . "/clear.gif width=1 height=1/></div></div></div></center></body></html>";

                $ordersubject_fillstock = "Stock Reorder at " . SITE_NAME;

                $mailsent = mail($artistemail, $ordersubject_fillstock, $mail_send_details_reorder, $headers);

                /* -------Email Template reading function call------------ */
            }
        }

        emptyCart($_SESSION["sess_userid"]);
        $_SESSION["sess_addresses_collected"] = false;
        $_SESSION["sess_stock_adjusted"] = false;
    }
}

if ($_POST["btnCancelOrder"] == "Cancel Order") {
    $message = "";
    adjustStock($_SESSION["sess_userid"], "+");
    emptyCart($_SESSION["sess_userid"]);
    $_SESSION["sess_addresses_collected"] = false;
    $_SESSION["sess_stock_adjusted"] = false;
    $redirecturl = SITE_URL . "/categorydetail.php";
    header("Location:$redirecturl");
    exit;
}

/* display the active template */

$active_template = displayTemplate();


include "includes/htmltop.php";

/* Top File Name */

include_once ("includes/" . $active_template[0]);
?>
<script language="javascript" src="includes/function.js"></script>
<script language="javascript" >
    function validateForm(){
        var frm = window.document.frmPayment;
        if (frm.txtCCNumber.value.length == 0 ) {
            alert('Please enter a valid credit card number!');
            return false;
        }else if (frm.txtMM.value.length == 0 || frm.txtYY.value.length == 0 || frm.txtYY.value < 06 || frm.txtMM.value > 12 ) {
            alert('Please enter a valid credit card expiry date!');
            return false;
        }else{
            return true;
        }
    }


    function onlyNumeric(){
        if (event.keyCode<48||event.keyCode>57)
            return false;
    }

    function checkNumber(t) {
        if(t.value.length == 0 ||  isNaN(t.value) || t.value.substr(0,1) == " " || parseInt(t.value) < 0) {
            t.value="";
        }
    }

</script>


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

    <div align="left" id="body_left_area">
        <!--body left area start -->



        <!--categories area start -->

<?php
include_once("includes/categorylist.php");
?>			

        <!--categories area end -->

        <!--body left area end -->
    </div>



    <!--center content area start-->

    <form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post" name="frmPayment" >
        <input type="hidden" name="userid" value="<?php echo $userid ?>">
        <input type="hidden" name="totaltopay" value="<?php echo $totaltopay ?>">
        <input type="hidden" name="paymentMethod" value="<?php echo $paymentMethod ?>">

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


            <!--items display area start -->

            <div align="left" id="items_top_area">
                <img src="<?php echo $active_template[3] ?>/top_title_left.gif" alt="" class="items_top_area_img" />
                <div align="left" id="items_top_area_ttl">Your Pay Payment</div>
                <img src="<?php echo $active_template[3] ?>/top_title_right.gif" alt="" class="items_top_area_img" />
            </div>
            <br>

            <div class="text_information" align="center"><?php echo $paymenterror ?></div>

            <div>

                <fieldset>
                    <table width="100%" border="0" cellspacing="2" cellpadding="2">

<?php
if (!$paymentsuccessful) {
?>

                            <tr>
                                <td class=maintext align="left">
    					 Total to Pay
                                </td>
                                <td align="left" class='maintext'>
<?php
//   $display_total = number_format(getCartTotal($_SESSION["sess_userid"]),2,".","");

    if (isset($_SESSION['couponCode_det'])) {
        $display_total = number_format(getCartTotalcouponCode($_SESSION["sess_userid"], $_SESSION['couponCode_det']), 2, ".", "");
    } else {
        $display_total = number_format(getCartTotal($_SESSION["sess_userid"]), 2, ".", "");
    }

    echo "&#36;";
    echo "&nbsp;";
    echo $display_total;
?>
                                </td>
                            </tr>
<?php
    $check_shipping_enable = checkShippingEnable();
    if ($check_shipping_enable == "Y" && $hide_shipping_division == 1) {

        $shipping_cost = $_SESSION['SESS_upscost'];
?>		
                                <tr>
                                    <td align="left"  class="maintext">Shipping Cost</td>
                                    <td align="left">
        <?php
        echo "&#36;";
        echo "&nbsp;";
        echo $shipping_cost
        ?>
                            </td>
                        </tr>
                        <tr>
                            <td align="left"  class="maintext">Grand Total</td>
                            <td width="69%" align="left"><input type="hidden" name="cart_total" value="<?php echo $display_total + $shipping_cost; ?>">
<?php
        echo "&#36;";
        echo "&nbsp;";
        echo $display_total + $shipping_cost;
    } else {
?> 

                                <input type="hidden" name="cart_total" value="<?php echo $display_total; ?>">

<?php
    }
?>


                        <tr>
                            <td class=maintext align="left" width="35%">
					 Card Number
                            </td>
                            <td align="left">
                                <input type=text name="txtCCNumber" maxlength=16 class=textbox value="<?php echo $txtCCNumber ?>" size="30">
                            </td>
                        </tr>
                        <tr>
                            <td class=maintext align="left">
					 Card Validation Code
                            </td>
                            <td align="left">
                                <input type=text name=txtCVV2 maxlength="10" class=textbox value="<?php echo $txtCVV2 ?>" size="15">&nbsp;
                                <a style="cursor:pointer" onClick="Javascript:window.open('credit_card_validation_image.php', 'CardValidationImage','menubar=0,resizable=0,width=300,height=220')"><img src="<?php echo SECURE_SITE_URL . "/images/question_mark.jpg" ?>" title="What's This?" height="25"></a>
                            </td>
                        </tr>
                        <tr>
                            <td class=maintext align="left">
					 Expiration Date :(MM/YY)
                            </td>
                            <td align="left">
                                <input type=text name="txtMM" class="textbox" id="txtMM" size=1 maxlength="2" onBlur="javascript:checkNumber(this);" value="<?php echo $txtMM ?>" style="width:30px"> /
                                <input type=text name="txtYY" class="textbox" id="txtYY" size=1 maxlength="2" onBlur="javascript:checkNumber(this);" value="<?php echo $txtYY ?>" style="width:30px">
                            </td>
                        </tr>

                        <tr>
                            <td colspan=2>&nbsp;</td>
                        </tr>
                        <tr>
                            <td colspan=2 align=center>
                                <input type="submit"  name="btnCompleteOrder" value="Complete Order" class="button" onclick="return validateForm();">&nbsp;&nbsp;
                                <input type="submit"  name="btnCancelOrder" value="Cancel Order" class="button" onclick="cancelOrder();">
                            </td>
                        </tr>
                                <?php
                            } else {

                                if ($check_shipping_enable == "Y") {
                                    if(function_exists('session_unregister')){
                                    session_unregister('SESS_upstype');
                                    session_unregister('SESS_upscost');
                                    session_unregister('SESS_upsweight');
                                    }else{
                                        unset($_SESSION['SESS_upstype']);
                                        unset($_SESSION['SHIPPING_TOTAL']);
                                        unset($_SESSION['SESS_upsweight']);
                                    }
                                }
                                ?>
                                <tr>
                                    <td class="text_information" colspan="2" align="center">
        					Your order has been successfully placed!
                                    </td>
                                </tr>
                        <?php
                                if (isset($_SESSION['SESS_digital_product'])) {
                        ?>
                                    <tr>
                                        <td colspan="3" align="center" class="text_information">
            					The Product Download Link is available in the Order Confirmation Mail
                                        </td>
                                    </tr>
                                <?php
                                }
                                ?>
                        <tr>
                            <td class=messages colspan="2" align="center">&nbsp;

                            </td>
                        </tr>
                        <tr>
                            <td class=messages colspan="2" align="center">
                                <input type='button' value='Home'  class='button' onClick="window.location.href='<?php echo SITE_URL ?>/index.php'">&nbsp;&nbsp;<input type='button' value='Continue Shopping'  class='button' onClick="window.location.href='<?php echo SITE_URL ?>/categorydetail.php'">
                            </td>
                        </tr>

                                <?php
                            }
                                ?>
                    </table>
                </fieldset>

            </div>


            <div align="left" class="float_clear1"></div>


            <!--items display area end -->
        </div>

    </form>
    <!--center content area end-->


    <div align="left" class="float_clear"><img src="images/clear.gif" alt="" width="1" height="1" /></div>
    <!--mainbody area end -->
</div>
<div align="left" class="float_clear"><img src="images/clear.gif" alt="" width="1" height="1" /></div>


<?php
                            include "includes/" . $active_template[2]; /* Bottom File Name */
?>	