<?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);
}

if (isset($_SESSION["sess_adminname"]) and $_SESSION["sess_adminname"] != "") {
	$adminname = $_SESSION["sess_adminname"];
} else {
	header("Location:login.php");
	exit;
}

$adminCurrency = GetAdminCurrency();

$gift_coupon_flag = 0;
$product_download_flag = 0;

if (isset($_GET['payment_id']) != '') {

	$orderid = $_GET['payment_id'];

	$update_payment_status = "UPDATE " . $tableprefix . "orders SET vpayment_status = 'D' WHERE order_id = " . $_GET['payment_id'];
	mysql_query($update_payment_status) or die(mysql_error());

	$download_link = "";

	$select_download_details = "SELECT ods.product_name,ods.product_quantity,digital.vdigital_product_code,digital.ndownload_try,
		digital.ndownload_expiry,usr.user_name,usr.email,digital.ndigital_productid
		FROM " . $tableprefix . "order_details ods," . $tableprefix . "digital_product digital," . $tableprefix . "users usr,
		" . $tableprefix . "orders ord
		WHERE digital.ndigital_orderid = ods.order_id
		AND  digital.ndigital_productid = ods.product_id
		AND  usr.user_id = ord.user_id
		AND  ord.order_id = " . $_GET['payment_id'] .
		" AND ord.order_id = ods.order_id";



	$result_download_details = mysql_query($select_download_details) or die(mysql_error());

	if (mysql_num_rows($result_download_details) > 0) {

		$product_download_flag = 1;

		while ($download_row = mysql_fetch_array($result_download_details)) {



			$digital_product_id = $download_row["ndigital_productid"];

			$productname = $download_row['product_name'];
			$quantity = $download_row['product_quantity'];
			$product_download_try = $download_row['ndownload_try'];
			$download_expiry_date = $download_row['ndownload_expiry'];
			$digital_product_code = $download_row['vdigital_product_code'];
			$user_name = $download_row['user_name'];
			$txtEmailDownload = $download_row['email'];
			$download_link .= "Download Link - " . SITE_URL . "/digital_product_download.php?download_code=$digital_product_code\r\n";

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




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

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

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

		$product_download_details = "Product Download Details\r\n";
		$product_download_details .= "-----------------------\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_details .= "User Name - $user_name\r\n\n";


		$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";

		$mailcontent_digital_product = readEmailTemplate('digital_product', '', $txtEmailDownload);

		$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);
	}


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


	$select_gift_details = "SELECT usrs.email,ods.product_id
				FROM " . $tableprefix . "users usrs," . $tableprefix . "order_details ods," . $tableprefix . "orders ord
				WHERE ord.user_id = usrs.user_id
				AND  ord.order_id = " . $_GET['payment_id'] .
				" AND ord.order_id = ods.order_id";


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



	while ($gift_row = mysql_fetch_array($result_gift_details)) {

		$select_gift_code = "SELECT vgift_coupon_code,ngift_coupon_amount
				FROM " . $tableprefix . "giftcoupon_master WHERE ngift_order_id = " . $_GET['payment_id'];
		$result_gift_code = mysql_query($select_gift_code) or die(mysql_error());

		if (mysql_num_rows($result_gift_code) > 0) {


			while ($gift_code_row = mysql_fetch_array($result_gift_code)) {


				$select_product_price = "SELECT product_price,product_artist_id FROM " . $tableprefix . "products
				WHERE product_id = " . $gift_row['product_id'];
				$result_product_price = mysql_query($select_product_price) or die(mysql_error());

				if (mysql_num_rows($result_product_price) > 0) {
					$product_price_row = mysql_fetch_assoc($result_product_price);

					$certificate_amount = $product_price_row['product_price'];
					$artistid = $product_price_row['product_artist_id'];
				}


				$txtEmail = $gift_row['email'];
				$gift_coupon_flag = 1;
				$gift_coupon_product_id = $gift_row['product_id'];

				$gift_coupon_link .= "Coupon Code :- " . $gift_code_row['vgift_coupon_code'] . "\r\n";
				$gift_coupon_link .= "Coupon Amount :- " . $certificate_amount . "\r\n\n";

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

				$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------------ */
			}

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

	if ($gift_coupon_flag == 1) {

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

		$mailcontent = readEmailTemplate('gift_coupon', '', $txtEmail);
		$mailcontent = str_replace('[coupon_code]', $gift_code_row['vgift_coupon_code'], $mailcontent);
		$mailcontent = str_replace('[coupon_amount]', $certificate_amount, $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);
	}


	/* --------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 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;

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



if (isset($_GET["txtSearch"]) and $_GET["txtSearch"] != "") {
	$txtSearch = $_GET["txtSearch"];
	$cmbSearchType = $_GET["cmbSearchType"];
} else if (isset($_POST["txtSearch"]) and $_POST["txtSearch"] != "") {
	$txtSearch = $_POST["txtSearch"];
	$cmbSearchType = $_POST["cmbSearchType"];
}


if (isset($_GET["msg"]) and $_GET["msg"] != "") {
	$msg = $_GET["msg"];
	switch ($msg) {
		case "deleted": $message = FEEDBACK_DEL_SUCC."!";
		break;
		default:
			;
	} // switch
}

if (isset($_POST['gotoPage'])) {

	header("Location:" . $_SERVER['PHP_SELF'] . "?page=" . $_POST['gotoPage']);
}


$qryopt = "";
$txtSearch = trim($txtSearch);

$qryopt.="WHERE o.vpayment_status = 'C' ";
if ($txtSearch != "") {
	if ($cmbSearchType == "username") {
		$qryopt .= "  AND  u.user_name like '" . addslashes($txtSearch) . "%'";
	} else if ($cmbSearchType == "dateordered") {
		$dt = $txtSearch;
		$arrdt = explode("/", $dt);
		$day = $arrdt[1];
		$month = $arrdt[0];
		$year = $arrdt[2];
		$dt = $year . "-" . $month . "-" . $day;
		$qryopt .= "  AND  o.order_date like '" . addslashes($dt) . "%'";
	} else if ($cmbSearchType == "email") {
		$qryopt .= "  AND  u.email like '" . addslashes($txtSearch) . "%'";
	} else if ($cmbSearchType == "orderid") {
		$qryopt .= "  AND  o.order_id = '" . addslashes($txtSearch) . "'";
	}
}

/* if($qryopt == "")
 {

$qryopt = " WHERE o.vorder_currency = cm.vcurrency_code";

}
else
{

$qryopt .= " AND o.vorder_currency = cm.vcurrency_code";

} */

/* $sql=" SELECT o.*, u.user_name, u.email,cm.nexchange_price,
 CASE WHEN o.vpayment_status = 'P' THEN 'Pending'
ELSE 'Done'
END AS payment_status
FROM ".$tableprefix."currency_master cm,".$tableprefix."orders o
INNER JOIN ".$tableprefix."users u ON o.user_id = u.user_id
" . $qryopt . "  ORDER BY o.order_id DESC "; */

/*
 $sql=" SELECT o.*, u.user_name, u.email,cm.nexchange_price,
CASE WHEN o.vpayment_status = 'P' THEN 'Pending'
ELSE 'Done'
END AS payment_status
FROM  ".$tableprefix."orders o
INNER JOIN ".$tableprefix."users u ON o.user_id = u.user_id
INNER JOIN ".$tableprefix."currency_master cm  ON cm.vcurrency_code = o.vorder_currency
" . $qryopt . "  ORDER BY o.order_id DESC ";
*/
$sql = " SELECT o.*, u.user_name, u.email,
				CASE WHEN o.vpayment_status = 'P' THEN 'Pending'
				ELSE 'Done'
				END AS payment_status
				FROM  " . $tableprefix . "orders o
			INNER JOIN " . $tableprefix . "users u ON o.user_id = u.user_id
				" . $qryopt . "  ORDER BY o.order_id DESC ";


if (!(isset($pagenum))) {
    $pagenum = 1;
}

$limit = getSettingsValue('npagination_limit');

$page = isset($_GET['page']) ? trim($_GET['page']) : 1;


if (empty($page)) {
    $page = 1;
}

$result = mysql_query($sql) or die(mysql_error());

$totalrows = mysql_num_rows($result);

$limitvalue = ($page - 1) * $limit;

$query_string = " LIMIT $limitvalue, $limit";

$sql = $sql . $query_string;
#echo $sql;
$rs = mysql_query($sql) or die(mysql_error());

$numofpages = ceil($totalrows / $limit);

include "../includes/htmltop.php";
?>
<script language="JavaScript" type="text/JavaScript">
    function clickSearch()
    {
        document.frmFeedbacks.submit();
    }
    function changeStatus(id){
        var frm = document.frmFeedbacks;
        if(Confirm("<?php echo ARE_YOU_SURE;?>?")){
            document.frmFeedbacks.submit();
        }
    }
    function confirmPayment()
    {
	
        return confirm("<?php echo CONFIRM_PAYMENT;?>?");
	
    }
</script>

<body>

	<center>

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




			<!--header area start -->
			<?php
			include_once("../includes/topheader_admin.php")
			?>

			<!--header area end -->




			<div align="right" class="main_body">
				<!--main body start -->



				<?php
				include_once("../includes/admintopmenu.php")
				?>


				<div align="right" class="content_area">

					<!--content area start -->

					<div align="left" class="page_title">
						<?php echo ORDERS;?>
					</div>
					<div align="center" class="text_information grey_tr">
						<?php echo $message ?>
					</div>
					<br>

					<div align="right">

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

							<table width="100%" border="0" cellpadding="0" cellspacing="0"
								class="manage_top">
								<tr>
									<td width="100%" align="left" valign="midddle"
										class=''><?php echo SEARCH;?> &nbsp; <select
										name="cmbSearchType" class="textarea">
											<option value="orderid"
											<?php
											if ($cmbSearchType == "orderid" || $cmbSearchType == "") {
                echo("selected");
            }
            ?>>
												<?php echo ORDER_ID;?>
											</option>
											<option value="username"
											<?php
											if ($cmbSearchType == "username" || $cmbSearchType == "") {
                                                    echo("selected");
                                                }
                                                ?>>
												<?php echo USER_NAME;?>
											</option>
											<option value="email"
											<?php
											if ($cmbSearchType == "email") {
                                                    echo("selected");
                                                }
                                                ?>>
												<?php echo EMAIL;?>
											</option>
											<option value="dateordered"
											<?php
											if ($cmbSearchType == "dateordered") {
                                                    echo("selected");
                                                }
                                                ?>>
												<?php echo ORDER_DATE;?>
												(
												<?php echo MM."/".DD."/".YYYY;?>
												)
											</option>
											<!--<option value="orderid"  <?php
                                                if ($cmbSearchType == "orderid") {
                                                    echo("selected");
                                                }
            ?>>Order ID</option>-->
									</select> <input type="text" name="txtSearch" size="20"
										maxlength="50"
										value="<?php echo(htmlentities(stripslashes($txtSearch))); ?>"
										class="textarea"> &nbsp;&nbsp;<a
										href="javascript:clickSearch();" class="search_button"><?php echo BTN_SEARCH; ?> </a>
									</td>
								</tr>
							</table>

						</form>

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

							<table width="100%" border="0" cellpadding="0" cellspacing="0"
								class="manage_table">

								<tr>
									<td height="21" colspan="8"><b>* <?php echo REQUEST_REFUND;?>.
									</b> <br>
									</td>
								</tr>

								<tr align="left" class="form_header">
									<th align="right">#</th>
									<th align="right"><?php echo ORDER_ID;?></th>
									<th align="right"><?php echo USER_NAME;?></th>
									<th align="right"><?php echo EMAIL;?></th>
									<th align="right"><?php echo DATE_ADDED;?>(<?php echo MM."/".DD."/".YYYY;?>)</th>
									<th align="right"><?php echo ORDER_TOTAL;?></th>
									<th align="right"><?php echo PAYMENT_STATUS;?></th>
									<th width="13%" align="right"><?php echo ORDER_STATUS;?></th>
								</tr>
								<?php
								if (mysql_num_rows($result) > 0) {

                                if ($page == 1) {
                                    $i = 1;
                                } else {
                                    $i = (($page - 1) * $limit) + 1;
                                }
                                while ($row = mysql_fetch_array($rs)) {
                                    $link = "<a href='vieworder.php?orderid=" . $row["order_id"] . "' class='links'>";

                                    $item_order_id = $row["order_id"];
                                    $item_payment_status = $row['vpayment_status'];
                                    $pay_status = $row['payment_status'];
                                    $currencycode = getSellerCurrencySybol($artistid);
                                    $taxrate = $row["taxrate"];
                                    $orderTotal = $row["order_total_price"];

                                    if ($taxrate != 0) {
                                        $orderTotal = $orderTotal + $taxrate;
                                    }
                                    switch ($pay_status){
                                    	case 'Pending':$st3=PENDING;
                                    	break;
                                    	case 'Done' :$st3=DONE;
                                    	break;

                                    }
                                    if ($row['vpayment_status'] == 'P') {
                                        $confirm_link = "<a onclick='return confirmPayment();' class='links' href='orders.php?payment_id=$item_order_id'><span class='text_information'>$st3</span></a>";
                                    } else {
                                        $confirm_link = "<b>$st3</b>";
                                    }
                                    switch (getOrderStatus($row["order_id"])){
                                    	case 'Pending':$st=PENDING;
                                    	break;
                                    	case 'Cancelled' :$st=CANCELLED;
                                    	break;
                                    	case 'Shipped':$st=SHIPPED;
                                    	break;
                                    	case 'Delivered':$st=DELIVERED;
                                    	break;
                                    	}

                                    	?>
								<tr>
								<td align="center"><?php echo $i; ?></td>
								<td align="center"><?php echo $link . htmlentities($row["order_id"]) . "</a>"; ?>
									</td>
										<td align="center"><?php echo $link . htmlentities($row["user_name"]) . "</a>"; ?>
									</td>
									<td align="center"><?php echo $link . htmlentities($row["email"]) . "</a>"; ?>
									</td>
									<td align="center"><?php echo $link . dateFormat($row["order_date"], "Y-m-d", "m/d/Y") . "</a>"; ?>
									</td>
									<td align="center"><?php echo $adminCurrency['currency_symbol']; ?>
										<?php echo $link . htmlentities(number_format($orderTotal, 2, ".", "")) . "</a>"; ?>
									</td>
									<td align="center"><?php echo $confirm_link ?></td>								
									<td align="center"><?php echo $link . $st . "</a>"; ?></td>	
								</tr>
								<?php
								$i++;
                                }
                            } else {
                                ?>
								<tr>
									<td align="center" valign="middle" colspan="8"
										class="text_information"><?php echo NO_RECORDS_FOUND;?>!!</td>
								</tr>
								<?php
                            }
                            if ($page > 1) {
                                $pageprev = $page - 1;

                                $previous_page = "<a href=" . $_SERVER['PHP_SELF'] . "?page=$pageprev alt='Previous' border='0' class='small_gray_button'>prev</a>";
                            }


                            if ($page < $numofpages) {
                                $pagenext = ($page + 1);

                                $next = "<a href=" . $_SERVER['PHP_SELF'] . "?page=$pagenext alt='Next' border='0' class='small_gray_button'>next</a>";
                            }
                            ?>


								<tr>
									<td class="page_nos" align="center" colspan="8">&nbsp;</td>
								</tr>
								<?php
								if ($page < $numofpages || $page > 1) {
                                ?>
								<tr>
									<td colspan="8" align="right" valign="top">
									
									<table width="100%" border="0" cellspacing="10" cellpadding="0">
										<tr align="left" valign="middle">
											<td width="21%" align="right"><?php echo $previous_page ?></td>
											<td width="23%" align="right">
												<?php echo PAGE."(".S.")";?> <?php echo $page ?>/<?php echo $numofpages ?>&nbsp;&nbsp;
												<?php echo GO_TO;?>
											</td>
											<td width="8%" align="right">
												<select class="textarea2" name="gotoPage" style="padding:4px 5px; margin-bottom:1px; ">
													<?php
													for ($i = 1; $i <= $numofpages; $i++) {
													
													
													if ($i == $_GET['page']) {
													$page_selected = "selected";
													} else {
													$page_selected = "";
													}
													?>
													<option value="<?php echo $i ?>" <?php echo $page_selected ?>>
													<?php echo $i ?>
													</option>
													
													<?php
													}
													?>
												</select>					
											</td>
											<td width="7%">
												<a onClick="Javascript:document.frmFeedbacks1.submit();" class="go_button_2">Go</a>
											</td>
											<td width="41%" align="center"><?php echo $next ?></td>
										</tr>
									</table>
									</td>
								</tr>
								<?php }
								?>
							</table>

						</form>



					</div>


					<!--content area end-->

				</div>


				<div align="right" class="clear_float">
					<img src="<?php echo $imagefolder; ?>/clear.gif" alt="" width="1"
						height="1" />
				</div>
				<!--main body end -->
			</div>


			<?php
			include "../includes/footer.php";
			?>