<?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";
include "../classes/cls_order.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_artistid"]) and $_SESSION["sess_artistid"] != "") {
    $artistid = $_SESSION["sess_artistid"];
} else {
    header("Location:login.php");
    exit;
}

if(checkArtistExpired($artistid)){
    header("Location:seller_plan_upgrade.php?sellerid=".$artistid);
    exit;
}


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 = MSG_FEED_DEL_SUC;
            break;
        default:
            ;
    } // switch
}

$chkorders = $_POST["chkorders"];



if ($_POST["btnRequestForPayment"]) {
    $message = "";
    if (!isNotNull($chkorders)) {
        $message .= MSG_SEL_ORDER;
    }

    if ($message != "") {
        $message = VAL_MSG_PLS_CORRECT . $message;
    } else {
        $orderlist = implode(",", $chkorders);
        $sql = "UPDATE " . $tableprefix . "order_details SET artist_payment_status = '1' WHERE order_id IN (" . addslashes($orderlist) . ") 
		AND artist_id = '" . addslashes($artistid) . "'  ";
        //echo $sql;
        mysql_query($sql) or die(mysql_error());
        $message = MSG_PAYMENT_SUC;
        $to = SITE_EMAIL;
        /*         * ************* Get Seller name ***************************** */

        $art_sql = "select first_name,last_name from " . $tableprefix . "artists where artist_id=$artistid";
        $art_rs = mysql_query($art_sql) or die(mysql_error());
        $art_rw = mysql_fetch_array($art_rs);
        $seller_name = $art_rw["first_name"] . " " . $art_rw["last_name"];

        /*         * ************* End get seller name ***************************** */
          $adminCurrency = GetAdminCurrency();


        foreach ($chkorders as $rp) {
            /*             * ******************* [START]Send requesy payment to the administrator ********************* */

            $subject = MAIL_RP_TEXT_REQUESTED_PAYMENT_PLACED_1." " . stripslashes(SITE_NAME) . " ".MAIL_RP_TEXT_REQUESTED_PAYMENT_PLACED_2;

            $b_sql = "select billing_first_name,billing_last_name,order_total_price,vorder_currency from " . $tableprefix . "orders where order_id=$rp";
            $b_rs = mysql_query($b_sql) or die(mysql_error());
            $b_rw = mysql_fetch_array($b_rs);
            $bfname = $b_rw["billing_first_name"];
            $blname = $b_rw["billing_last_name"];

               $p_sql = "SELECT sum((od.product_price-(od.product_price*od.product_discount/100)) *od.product_quantity) as total,sum(od.product_commission_amount)as adminamount,sum(od.product_tax) as taxtotal FROM " . $tableprefix . "order_details od
		            WHERE od.artist_id = '" . $artistid . "' AND od.artist_payment_status = '1' 
					and od.order_id IN (" . addslashes($rp) . ")";
               
            $p_rs = mysql_query($p_sql);
            $p_rw = mysql_fetch_array($p_rs);
                                   
             $ordertotalamt = $p_rw["total"] + $p_rw['taxtotal'];
             
               $select_shipping_cost = "SELECT  sd.nshipping_cost,sd.nshp_productname
                                        FROM ".$tableprefix."shipping_details sd
                                            INNER JOIN ".$tableprefix."order_details  od ON (od.product_id=sd.nshp_productid AND od.product_option_id=sd.nproduct_option_id AND od.order_id=sd.norder_id)
                                                WHERE sd.norder_id = ".$rp." AND od.artist_id = '".addslashes($artistid)."' AND  sd.nshp_status = 'C' order by sd.nshp_productname";
          
                                    
                                    $result_shipping_cost = mysql_query($select_shipping_cost);
                                    $totalshippingcost = 0;
                                    $ordertotal = $row["total"];
                                    if (mysql_num_rows($result_shipping_cost) > 0) {

                                        while ($shipping_row = mysql_fetch_array($result_shipping_cost)) {
                                            $totalshippingcost+=$shipping_row['nshipping_cost'];
                                        }
                                    }
                                    $ordertotalamt+=$totalshippingcost;
                                    
                                    
                                    $amountRecevable    = $ordertotalamt - $p_rw['adminamount'];

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

            $mailcontent = readEmailTemplate('request_payment_seller');
                
            
            $mailcontent = str_replace('[seller_name]', $seller_name, $mailcontent);

            $orderdetails = "<p>".MAIL_RP_TEXT_ORDER_ID_ANNOTATED." $rp</p>";
            $orderdetails .= "<p>".MAIL_RP_TEXT_BUYER_NAME." " . $bfname . " " . $blname . "</p>";
            $orderdetails .= "<p>".MAIL_RP_TEXT_TOTAL_PURCHASE." " . $adminCurrency["currency_symbol"] . "  " . number_format($ordertotalamt, 2, '.', '') . "</p>";

            $orderdetails .= "<p>".MAIL_RP_TEXT_AMOUNT_RECEIVABLE." " . $adminCurrency["currency_symbol"] . "  " . number_format($amountRecevable, 2, '.', '') . "</p>";
            
            $mailcontent = str_replace('[order_details]', $orderdetails, $mailcontent);


            $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";
            $headers .= "Reply-To: " . SITE_NAME . "<" . SITE_EMAIL . ">" . "\r\n";
            $headers .= "Return-Path: " . SITE_NAME . "<noreply@" . SITE_EMAIL . ">" . "\r\n";

            $mailcontent = nl2br($mailcontent);

             $mail_send_details = '<html>
		<head>
		   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		   <title >'.SITE_NAME.'</title>
		  <link href="./themes/' . $active_template[4] . ' rel="stylesheet" type="text/css">
		</head>
		<body>
		
		<table width="103%" cellspacing="10" cellpadding="0" bgcolor="#EAEAEA">
		   <tr>
			 <td align="center" valign="top">
				 
				 <table width="600" border="0" cellpadding="0" cellspacing="0" bordercolor="#EAEAEA" bgcolor="#FFFFFF" class="manage_table">
					<tr>
					   <td align="right" >
					  </td>
					</tr>
					<tr>
					   <td valign="middle" align="left"><table width="100%"  border="0" cellspacing="0" cellpadding="0">
						 <tr>
						   <td  bgcolor="#EAEAEA" > <img src=' . SITE_URL . '/banners/' . getSettingsValue('site_logo') . ' width="125" height="60"/></td>
						 </tr>
					   </table></td>
					</tr>
					<tr>
					  <td align="center" valign="top"><table width="100%"  border="0" cellspacing="0" cellpadding="10">
						<tr>
						  <td align="left"><p>' . $mailcontent . '</p>
						  </td>
						</tr>
					  </table></td>
					</tr>
					<tr>
					   <td align="center" bgcolor="#EAEAEA" class="footer">
						  <p>&nbsp;</p>
					  </td>
					</tr>
			   </table>
		
			 </td>
		   </tr>
		</table>
		
		
		</body>
		</html>';

            $mailsent = mail($to, $subject, $mail_send_details, $headers);
            
          

            /*             * ******************* [END]Send requesy payment to the administrator ********************* */
        }
    }
}

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

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


$qryopt = "";
if ($txtSearch != "") {
    if ($cmbSearchType == "username") {
        $qryopt .= "  AND  u.user_name like '" . addslashes($txtSearch) . "%'";
    } else if ($cmbSearchType == "orderid") {
        $qryopt .= "  AND  o.order_id = '" . addslashes($txtSearch) . "'";
    }
}
$sql = "SELECT o.*, u.user_name, u.email, od.product_discount,sum(((od.product_price-(od.product_price*product_discount/100)) * od.product_quantity)) as total ,sum(od.product_commission_amount)as adminamount,sum(od.product_tax) as taxtotal
        FROM " . $tableprefix . "orders o 
		INNER JOIN " . $tableprefix . "users u ON o.user_id = u.user_id 
		INNER JOIN " . $tableprefix . "order_details od ON o.order_id = od.order_id 
                
		WHERE od.artist_id = '" . addslashes($artistid) . "' 
		AND od.item_status = '4'
		AND od.artist_payment_status = '0' 
		" . $qryopt . " GROUP BY o.order_id 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;

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

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

include "../includes/htmltop.php";


$adminCurrency = GetAdminCurrency();
?>


<script language="JavaScript" type="text/JavaScript">
    function clickSearch()
    {
        document.frmFeedbacks.submit();
    }
    function changeStatus(id){
        var frm = document.frmFeedbacks;
        if(Confirm("<?php echo QTN_CHNG_ST;?>")){
            document.frmFeedbacks.submit();
        }
    }
</script>

<body>

<center>

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




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

        <!--header area end -->




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



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


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

                <!--content area start -->

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

                <div align="left">		

                    <form action="" method="post" name="frmFeedbacks">

                        <table width="100%" border="0" cellpadding="0" cellspacing="0" class="manage_top">
                            <tr>
                                <td width="90%" align=left valign="baseline"  class="toplinksCopy"><?php echo TEXT_SEARCH;?>
                                    <select name="cmbSearchType" class="textarea">
                                        <option value="username"  <?php
            if ($cmbSearchType == "username" || $cmbSearchType == "") {
                echo("selected");
            }
            ?>><?php echo TEXT_USER_NAME;?></option>
                                        <option value="orderid"  <?php
                                                if ($cmbSearchType == "orderid") {
                                                    echo("selected");
                                                }
            ?>><?php echo TEXT_ORDER_ID;?></option>
                                        
                                    </select> &nbsp;
                                    <input type="text" name="txtSearch" size="20" maxlength="50" value="<?php echo(htmlentities($txtSearch)); ?>"  onKeyPress="if(window.event.keyCode == '13'){ return false; }" class="textarea">
                                    <a href="javascript:clickSearch();" class="go_button"><?php echo BTN_SEARCH; ?></a>
                                </td>
                            </tr>
                        </table>

                    </form>

                </div>

                <div align="left">					
                    <table border="0" width="100%" cellpadding="0" cellspacing="0" class="manage_table">
                        <form action="" method="post" name="frmFeedbacks1">
                            
                            <tr><td colspan="11" class="specialmessage"> <?php echo TEXT_ORDER_NOTE ;?> </td></tr>
                            
                            <tr><td colspan="11" class="specialmessage"> <?php echo TEXT_ORDER_TOTAL_NOTE ;?> </td></tr>
                            
                            <tr><td colspan="11" class="specialmessage"> <?php echo TEXT_ORDER_NOTE_ADMIN_AMOUNT ;?> </td></tr>
                            
                            <tr><td colspan="11" class="specialmessage"> <?php echo TEXT_ORDER_NOTE_AMOUNT_RECEIVABLE ;?> </td></tr>
                            <tr><td colspan="11" > &nbsp;</td></tr>
                            <tr class="form_header">
                                                                                       
                                <th width="4%" align="left">#</th>
                                <th width="7%"   align="left"><?php echo TEXT_ORDER_ID;?></th>
                                <th width="10%" align="left"><?php echo TEXT_USER_NAME;?></th>
                                <th width="12%" align="left"><?php echo TEXT_PRODUCT_TOTAL;?> </th>
                                <th width="10%" align="left"><?php echo TEXT_DISCOUNT_AMOUNT;?> </th>
                                <th width="10%" align="left"><?php echo TEXT_SHIPPING_TOTAL;?> </th>
                                <th width="10%" align="left"><?php echo ORDER_TEXT_TAX_TOTAL;?> </th>
                                <th width="10%" align="left"><?php echo TEXT_ORDER_TOTAL;?></th>
                                <th width="20%" align="left"><?php echo TEXT_ADMIN_COMMISION_AMOUNT;?> </th>
                                <th width="24%" align="left"><?php echo TEXT_AMOUNT_RECEIVABLE;?> </th>
                                <th align="left"><?php echo TEXT_STATUS;?></th>
                                
                            </tr>
                            <?php
                            if (mysql_num_rows($result) > 0) {
                                $i = 1;
                                $amountRecevable    =   0;
                                $itemTotal          =   0;
                                
                                $totalDiscountAmount =  0;
                                
                                $taxtotal           =   0;
                                $totalshippingcost  =   0;
                                while ($row = mysql_fetch_array($rs)) {
                                    $link = "<a class='links' href='vieworder.php?orderid=" . $row["order_id"] . "'>";
                                    $check = "<input class='checkbox' type='checkbox' name='chkorders[]' value='" . $row["order_id"] . "' > ";
                                    
                                   
                                    $totalshippingcost = 0;
                                    
                                    
                                    $totalshippingcost      =    Order::orderShippingCost($row["order_id"],$artistid);
                                    $taxtotal               =    Order::getorderTaxTotal($row["order_id"],$artistid);
                                    $itemTotal              =    $row["total"];
                                    
                                    if($row['vgiftcertificate_code']!='' && $row['nused_gift_amount']!=0 ){
                                                                    
                                          $giftCertificateAmount        =   $row['nused_gift_amount'];  
                                          
                                          //$itemTotal                    =   $itemTotal - $row['nused_gift_amount'];
                                          
                                    }  
                                    
                                     if(($artistid==$row['couponCodeSeller_Id']) && ($row['couponCodeDiscount']>0))
                                        {
                                            $couponCodeDiscountAmount       =   $row['couponCodeDiscount'];
                                            
                                            //$itemTotal                      = $itemTotal - $couponCodeDiscountAmount;
                                        } 
                                        
                                        
                                        $totalDiscountAmount                =   $giftCertificateAmount + $couponCodeDiscountAmount;
                                        
                                        if($totalDiscountAmount>0)
                                        {
                                            $newTotal   =   $itemTotal -  $totalDiscountAmount; 
                                        }else{
                                            $newTotal   =   $itemTotal;
                                        }
                                    $ordertotal = $newTotal + $taxtotal + $totalshippingcost ;
                                    $amountRecevable    = $ordertotal - $row['adminamount'];
                                    
                                    
                                    ?>
                                     <tr>
                                        <td><?php echo $check ?></td>
                                        <td><?php echo $row["order_id"]; ?></td>
                                        <td><?php echo $link . $row["user_name"] . "</a>"; ?></td>
                                        <td><?php echo $link . $adminCurrency["currency_symbol"] . " " . htmlentities(number_format($row['total'], 2, '.', '')) . "</a>"; ?></td>
                                         <td><?php echo $link . $adminCurrency["currency_symbol"] . " " . htmlentities(number_format($totalDiscountAmount, 2, '.', '')) . "</a>"; ?></td>

                                        <td><?php echo $link . $adminCurrency["currency_symbol"] . " " . htmlentities(number_format($totalshippingcost, 2, '.', '')) . "</a>"; ?></td>

                                        <td><?php echo $link . $adminCurrency["currency_symbol"] . " " . htmlentities(number_format($taxtotal, 2, '.', '')) . "</a>"; ?></td>

                                        <td><?php echo $link . $adminCurrency["currency_symbol"] . " " . htmlentities(number_format($ordertotal, 2, '.', '')) . "</a>"; ?></td>
                                        <td><?php echo $link . $adminCurrency["currency_symbol"] . " " . htmlentities(number_format($row['adminamount'], 2, '.', '')) . "</a>"; ?></td>
                                        <td><?php echo $link . $adminCurrency["currency_symbol"] . " " . htmlentities(number_format($amountRecevable, 2, '.', '')) . "</a>"; ?></td>

                                        <td><?php echo $link . htmlentities(getArtistOrderStatus($row["order_id"], $artistid)) . "</a>"; ?></td>
                                    </tr>
                                    <?php
                                    $i++;
                                }
                                ?>
                                <?php
                                if (isNotNull($check)) {
                                    ?>
                                    <tr>
                                        <td colspan="10" align="center"><input type="submit" name="btnRequestForPayment" value="<?php echo TEXT_REQ_PAY;?>" class="button">
                                        </td>
                                    </tr>
                                    <?php
                                }
                                ?>
                                <?php
                            } else {
                                ?>
                                <tr>
                                    <td align="center" valign="middle" colspan="11"  class="text_information"><?php echo TEXT_NO_RECORD;?></td>
                                </tr>
                                <?php
                            }
                            ?>
                        </form>
                        <?php
                        if ($page > 1) {
                            $pageprev = $page - 1;

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


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

                            $next = "<a href=" . $_SERVER['PHP_SELF'] . "?page=$pagenext alt='Next' border='0' class='small_gray_button'>".TEXT_PAGES_NEXT."</a>";
                        }
                        ?>
                        <form action="" method="post" name="frmFeedbacks1">
                            <?php
                            if ($page < $numofpages || $page > 1) {
                                ?>
                                <tr>
                                    <td align="center" colspan="10">
										<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 TEXT_PAGES; ?> <?php echo $page ?>/<?php echo $numofpages ?>&nbsp;&nbsp;<?php echo TEXT_GOTO; ?>
												</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"><?php echo BTN_GO; ?></a>
												</td>
												<td width="41%" align="center"><?php echo $next ?></td>
											</tr>
										</table>                                      
                                  </td>
                                </tr>
                                <?php
                            }
                            ?>
                        </form>
                    </table>
                </div>


                <!--content area end-->

            </div>


            <div align="left" 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";
        ?>					
