<?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(isset($_SESSION['membership'])) {
    $totaltopay=$_SESSION['membership']['plan_SubscriptionCharge'];
}else {
    header("location:chooseYourPlan.php");
    exit();
}

$currency_attributes=displayCurrencyType();

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_artistid"]) and $_SESSION["sess_artistid"]!= "") {
    $userid = $_SESSION["sess_artistid"];
}

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


if(isset($_SESSION['membership'])) {
    $totaltopay=$_SESSION['membership']['plan_SubscriptionCharge'];
}else {
    header("location:chooseYourPlan.php");
    exit();
}


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


$txtCCNumber = $_POST["txtCCNumber"];
$txtCVV2 = $_POST["txtCVV2"];
$txtMM = $_POST["txtMM"];
$txtYY = $_POST["txtYY"];

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

$currency_attributes = displayCurrencyType();

$adminCurrency	= GetAdminCurrency();
 


//$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();

$txtEnableAuthorize 	= getSettingsValue('vauthorize_enable');
$txtEnableBluepay       = getSettingsValue('vbluepay_enable');
$txtEnableFirstData	= getSettingsValue('vyourpay_enable');

$txtEnableStripe	= getSettingsValue('stripe_payment_enable');
if($txtEnableStripe=="Y"){
    $txtStripePublishKey = getSettingsValue('stripe_publish_key');
    $txtStripeSecretKey  = getSettingsValue('stripe_secretkey');
    $stripeMode          = getSettingsValue('stripe_payment_test_mode');
}


$paymentMethod = "CC";

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

$txtAuthorizeLoginId = $row["authorize_loginid"];
$txtAuthorizeTransKey = $row["authorize_transkey"];
$txtCurrency = "USD";
$txtAuthorizeEmail = $row["authorize_email"];
$txtAuthorizeTestMode = $row["authorize_test_mode"];
if($txtAuthorizeTestMode == "Y") {
    $txtAuthorizeTestMode = "on";
}else {
    $txtAuthorizeTestMode = "off";
}

$gift_coupon_flag = 0;
if (isset($_POST["totaltopay"])) {
    $message = "";
    $paymentsuccessful = false;

    if($txtEnableAuthorize == 'Y') {
        $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();

        foreach($_SESSION['SESS_insertQry'][2] as $key => $value) {
            $$key = $value;
        }
        $txtAddress = $txtAddress1;
        if(!$ddlCountry)
            $ddlCountry = $bill_country;
        if(!$txtState)
            $txtState = $bill_state;

        $Company = "-NA-";
        $Phone=$txtPhone;
        if($txtLastName=="")
            $txtLastName="-NA-";

        require "../authorize.php";//process the card and return result. Comment this line and uncomment the two lines below to make payment test mode

        //$paymentsuccessful = true;
        // = "TEST1234444";

    }
    elseif($txtEnableBluepay=='Y') {

        $txtBluepayAccountId = getSettingsValue('bluepay_accountid');
        $txtBluepaySecretKey = getSettingsValue('bluepay_secretkey');
        $mode  = getSettingsValue('bluepay_test_mode');


        $card_expiry    = $txtMM.substr($txtYY,-2);
        include "../includes/Bluepay.php";
        $bp = new Services_Bluepay();
        $bp->setValue("ACCOUNT_ID", $txtBluepayAccountId);
        $bp->setValue("SECRET_KEY", $txtBluepaySecretKey);
        $bp->setValue("TRANS_TYPE", 'SALE');
        $bp->setValue("MODE", $mode);		# Default is TEST --> Set to LIVE for live tx
        $bp->setValue("AMOUNT", $totaltopay);	# ODD returns Approved, EVEN returns Declined in TEST mode
        $bp->setValue("PAYMENT_ACCOUNT", $txtCCNumber);	# Card Number
        $bp->setValue("CARD_EXPIRE", $card_expiry);
        $bp->setValue("NAME1", $txtFirstName);
        $bp->setValue("NAME2", $txtLastName);
        $bp->setValue("PHONE", $txtPhone);
        $bp->setValue("EMAIL", $txtEmail);
        $bp->setValue("COMPANY_NAME", SITE_NAME);
        $tamperProofSeal=md5($txtBluepaySecretKey.$txtBluepayAccountId.$totaltopay.$mode);
        $bp->setValue("TAMPER_PROOF_SEAL", $tamperProofSeal);
        $bp->setValue("ADDR1", $txtAddress1);
        $bp->setValue("CITY", $txtCity);
        $bp->setValue("STATE", $txtState);
        $bp->setValue("ZIP", $txtZIP);
        $bp->setValue("COUNTRY", $ddlCountry);
        $bp->bp20post();
        $transactionid = $bp->getValue("TRANS_ID");
        $paymentsuccessful = false;
        if($transactionid != "" && $bp->getValue("MESSAGE")	== "Approved Sale" && $bp->getValue("STATUS")== "1") {
            $paymentsuccessful = true;
        }
        else {

            $paymenterror = MSG_TRANSACTION;
        }
    }elseif($txtEnableFirstData=='Y') {
        include_once "../includes/firstData.php";


        $mylphp=new firstData;



        if(getSettingsValue('vyourpay_mode')=='TEST') {
            //$myorder["host"]       = "208.72.248.102";   //secure.linkpt.net for Live
            $myorder["host"]       = "staging.linkpt.net";

            $myorder["result"]     = "LIVE";

        }
        else {
            $myorder["host"]       = "secure.linkpt.net";   //secure.linkpt.net for Live
            $myorder["result"]     = "LIVE";
        }
        $myorder["port"]       = "1129";

        //##Merchantinfo
        $myorder["keyfile"]    = "pem/".getSettingsValue('vyourpay_certificate_file'); # Change this to the name and location of your certificate file
        $myorder["configfile"] =trim(getSettingsValue('vyourpay_storeid')); # Change this to your store number
        //## Orderoptions

        $myorder["ordertype"]    = "SALE" ; //The type of transaction. The possible values are SALE,PREAUTH,VOID,POSTAUTH,CREDIT, CALCSHIPPING

        $yearlen=strlen($txtYY);

        if($yearlen>2) {
            $CardYear= substr($txtYY,-2);
        }
        # card info
        $myorder["cardnumber"]   = $txtCCNumber ;
        $myorder["cardexpmonth"] = $txtMM;
        $myorder["cardexpyear"]  = $CardYear;
        $myorder["cvmindicator"] = "provided";
        $myorder["cvmvalue"]     =  $txtCVV2;
        //## Payment
        //$myorder["subtotal"]    = $totaltopay;
        //$myorder["tax"]         = number_format($totaltaxrate,2,".","");
        //$myorder["shipping"]    = number_format($shipping_cost,2,".","");
        //$myorder["vattax"]      = "0.00";
        $myorder["chargetotal"] = number_format($totaltopay,2,".","");
        // ## Billing
        $myorder["name"]      = $txtFirstName;
        $myorder["address1"]  = $txtAddress1;
        $myorder["address2"]  = $txtAddress2;
        $myorder["city"]      = $txtCity;
        $myorder["state"]     = $txtState;
        $myorder["country"]   = $ddlCountry;
        $myorder["phone"]     = $txtPhone;
        $myorder["email"]     = $txtEmail;       
        $myorder["addrnum"]   = '';   # Required for AVS. The numeric portion of the street address If not provided, transactions will downgrade.
        $myorder["zip"]       = $txtZIP; # Required for AVS. Billing zip or postal code If not provided, transactions will downgrade.
        //$items = array();
        //$myorder["items"][0] = $items; # put array of items into hash

        $myorder["comments"] = "Seller Registration  Information with  ".SITE_NAME." online store";

        $result = $mylphp->curl_process($myorder);  # use curl methods

        $transactionid		=	$result["r_ordernum"];


        if($transactionid != "" && $result["r_approved"] == "APPROVED") {
            $paymentsuccessful = true;
        }
        if ($result["r_approved"] != "APPROVED")	// transaction failed, print the reason
        {
            if($result["r_error"]=='<') {
                $paymenterror = "Unable to process your payment. Try again later.";
            }
            else {
                $paymenterror=$result["r_error"];
            }

            $msg_error=$paymenterror;
            $_SESSION['PAYMENT_ERROR']=$result["r_error"];
        }


    }else if($txtEnableStripe=="Y"){
        
       

            include_once "../library/stripe/Stripe.php";
            Stripe::setApiKey($txtStripeSecretKey);
            try {
                if (!isset($_POST['stripeToken'])){
                   //throw new Exception("The Stripe Token was not generated correctly");
                    $paymenterror = $error;
                }
                    $order_total  = $totaltopay;
                    $orderTotal   = round($order_total);
                  
                    $txtCurrency          =     $adminCurrency['currency_code'];
                    Stripe_Charge::create(array("amount" => $orderTotal * 100,
                                    "currency" => $txtCurrency,
                                    "card" => $_POST['stripeToken'],
                                    "description" => $txtEmail));
                        $success = '<div class="alert alert-success">
                                    <strong>Success!</strong> Your payment was successful.
                                                    </div>';
                        
                    $paymentsuccessful = true;
                }
                catch (Exception $e) {
                      $error = '<div class="alert alert-danger">
                                        <strong>Error!</strong> '.$e->getMessage().'
                                        </div>';
                      
                      $paymenterror = $error;
                }
                 
                 

     }
    

    if($paymentsuccessful) {

//-----------------------------Inserting artist starts here --------------------------------------------//
        if(isset($_SESSION['SESS_insertQry'])) {
            mysql_query($_SESSION['SESS_insertQry'][0]) or die(mysql_error());
            $userid = mysql_insert_id();
            $_SESSION['sess_artistid']=$userid;

            $_SESSION["sess_artistname"] = trim($_SESSION['SESS_insertQry'][2]['txtUserName']);
            $_SESSION["sess_artistid"] 	 = $userid;

            // Ending Session for User, Affiliates
        }
//------------------------------Ends here--------------------------------------------------------------//



        $select_Plan = "SELECT plan_Period
								   FROM ".$tableprefix."sellerPlans
								   WHERE plan_Id = ".trim($_SESSION['membership']['plan_Id']);
        $result_Plan = mysql_query($select_Plan) or die(mysql_error());
        $result_Plan = mysql_fetch_assoc($result_Plan);
        if($result_Plan['plan_Period']=="M")
            $noOfDays=30;
        if($result_Plan['plan_Period']=="Y")
            $noOfDays=365;


        $_SESSION['SES_MEMPLAN']=$_SESSION['membership']['plan_Id'];

        if($paypal_check==0) { // check if paypal is success

            $sql = "UPDATE " .$tableprefix. "artists SET sellerPlanID =".$_SESSION['membership']['plan_Id']." WHERE artist_id =".$_SESSION['sess_artistid'];
            mysql_query($sql);
            $orderid = mysql_insert_id();

            $fromDate= date("Y-m-d");
            $endDate= date("Y-m-d",strtotime("+".$noOfDays." day"));


            $sql = "INSERT INTO " .$tableprefix. "artists_membershipDetails (artist_id, artist_memStartDate, artist_memEndDate,plan_Id,plan_SubscriptionCharge,transaction_id) VALUES
				(".$_SESSION['sess_artistid'].",'".$fromDate."','".$endDate."',".$_SESSION['membership']['plan_Id'].",".$_SESSION['membership']['plan_SubscriptionCharge'].",'".$transacttion_id."')";
            mysql_query($sql);
            $orderid = mysql_insert_id();
        }


        $select_seller_name = "SELECT * FROM ".$tableprefix."artists WHERE artist_id = ".$_SESSION['sess_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'];
            $txtFirstName  = $seller_name_row['first_name'];
            $txtLastName  = $seller_name_row['last_name'];
            $txtUserName  = $seller_name_row['artist_name'];
            $txtEmail     = $seller_name_row['email'];

        }


        $sellerapproval	=getSettingsValue('approve_sellers');

        $userfullname = $txtFirstName;
        if($txtLastName != "") {
            $userfullname .= " ". $txtLastName;
        }
        $to = $txtEmail;

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

        $subject = MAIL_SELLER_REG_SUBJECT." ".stripslashes(SITE_NAME);


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

        $txtPassword = trim($_SESSION['SESS_insertQry'][2]['txtPassword']);
        $mailcontent = readEmailTemplate('seller_registration','artists');

        //echo $mailcontent;exit;
        $mailcontent = str_replace('[first_name]',$txtFirstName,$mailcontent);
        $mailcontent = str_replace('[last_name]',$txtLastName,$mailcontent);
        $mailcontent = str_replace('[user_name]',$txtUserName,$mailcontent);
        $mailcontent = str_replace('[password]',$txtPassword,$mailcontent);



        /*---------------Seller Login Url-------------------*/


        if($sellerapproval==3 ) { // check if seller approval is through Email - Activation
            $userid=base64_encode($_SESSION['sess_artistid']);
            $mailcontent.="\r\n"."<font color='green'><b>".MAIL_SELLER_REG_TEXT_APPROVAL_LINK."</b></font>\r\n\n";
            $mailcontent.="\r\n"."<a href=".SITE_URL."/sellers_activation.php?aid=$userid&status='Y'>".MAIL_SELLER_REG_TEXT_CLICK_HERE_TO_APPROVE_YOUR_ACCOUNT."</a>\r\n\n";

        } // end email activation check
        if($sellerapproval==1) {
            $mailcontent .= "\r\n".MAIL_PLAN_PURCHASE_TEXT_CLICK."&nbsp;<a href=".SITE_URL."/sellers>".MAIL_PLAN_PURCHASE_TEXT_HERE."</a> ".MAIL_PLAN_PURCHASE_TEXT_TO_LOGIN."\r\n\n";
        }
        if($sellerapproval==2) {
            $mailcontent .= "\r\n\n\n\n\n"."<font color='green'><b>".MAIL_SELLER_REG_TEXT_ACCOUNT_APPROVAL_MESSAGE."</b></font>\r\n\n";
        }



        /*---------------Seller Login Url-------------------*/

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

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

        if($enable_seller_friendly == "Y") {

            $friendly_url = SITE_URL."/store/".$txtSellerName;
        }
        else {
            $friendly_url = SITE_URL."/showportfolio.php?artistid=".$_SESSION['sess_artistid'];
        }

        $mailcontent .= "\r\n"."<font color='#FF0000'>".MAIL_PLAN_PURCHASE_TEXT_SELLER_STORE_URL."</font>"."\r\n\n";
        $mailcontent .= "<b>".$friendly_url."</b>\n\n";



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


        $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";
        //$headers .= "Organization: ".SITE_NAME."\r\n";


        $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_send_details = '<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title >'.SITE_NAME.'</title>

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

        // **********************************************************************Send Mail To Administrator


        $subject_admin = MAIL_NEW_SELLER_REG." ".SITE_NAME;

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

        $mailcontent_admin = readEmailTemplate('seller_registration_admin','artists');

        $mailcontent_admin = str_replace('[user_name]',$txtUserName,$mailcontent_admin);

        $mailcontent_admin = str_replace('[password]',$txtPassword,$mailcontent_admin);

        $mailcontent_admin = str_replace('[firstname]',$txtFirstName,$mailcontent_admin);

        $mailcontent_admin = str_replace('[lastname]',$txtLastName,$mailcontent_admin);

        /*---------------User Login Url-------------------*/

        $mailcontent_admin .= "\r\n";
        $mailcontent_admin .= "\r\n".MAIL_PLAN_PURCHASE_TEXT_CLICK."&nbsp;<a href=".SITE_URL."/admin/login.php>".MAIL_PLAN_PURCHASE_TEXT_HERE."</a> ".MAIL_PLAN_PURCHASE_TEXT_TO_LOGIN_TO_VIEW_DETAILS."\r\n\n";

        /*---------------User Login Url-------------------*/

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

        $mailcontent_admin = nl2br($mailcontent_admin);

        //$mail_send_details_admin = "<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_admin."</div></div><div align='left' class='clear_float'><img src=".$imagefolder."/clear.gif width=1 height=1/></div></div></div></center></body></html>";



        $mail_send_details_admin = '<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title >'.SITE_NAME.'</title>
 </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_admin.'</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>';


        $adminemail	=getSettingsValue('site_email');


        $mailsent = mail($adminemail, $subject_admin, $mail_send_details_admin, $headers);




    }

 
    if($paymentsuccessful) { // check if paypal is success
        unset($_SESSION['membership']);
        unset($_SESSION['SESS_pay_amount']);
        unset($_SESSION['SESS_insertQry']);
        $_SESSION['PAY_MESSAGE']="Payment process has been completed successfully.";


        if($sellerapproval==3) { // Aproval After Email Confirmation
            unset($_SESSION['sess_artistid']);
            header("Location:".SITE_URL."/sellers/validate.php?approval=3");
            exit;
        } // end if
        else if($sellerapproval==2) { // Aproval After Email Confirmation
            unset($_SESSION['sess_artistid']);
            header("Location:".SITE_URL."/sellers/validate.php?approval=2");
            exit;
        } // end if
        else {
            header("location:".SITE_URL."/sellers/artistmain.php");
        }

    }

}

if (isset($_POST["btnCancelOrder"])) {
    $message = "";
    $redirecturl = SITE_URL."/sellers/chooseYourPlan.php";
    header("Location:$redirecturl");
    exit;
}




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



<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")
                        ?>
                <script type="text/javascript" src="https://js.stripe.com/v2/"></script>
                <script language="javascript" src="../includes/function.js"></script>
                <script language="javascript" >
                    function validateForm(){
                        var frm         = window.document.frmPayment;
                        var yearVal     = frm.txtYY.value;
                        var month       = frm.txtMM.value;
                        currentMonth    = new Date().getMonth() + 1,
                        currentYear     = new Date().getFullYear();
                        if (frm.txtCCNumber.value.length == 0 ) {
                            alert('Please enter a valid credit card number!');
                            return false;
                        }else if (frm.txtCVV2.value.length == 0 ) {
                                alert('Please enter CVV Number');
                               
                                return false;
                        }else if ((frm.txtMM.value.length == 0 || frm.txtMM.value > 12 ) || (yearVal < currentYear || yearVal > currentYear + 100) ) {
                            alert('Please enter a valid credit card expiry date!');
                            return false;
                           
                        }else if(yearVal < currentYear || (yearVal == currentYear && month < currentMonth)) {
                                alert('Please enter a valid credit card expiry date!');
                                return false;
                        } else{
                            var txtEnableStripe = '<?php echo $txtEnableStripe; ?>';
                            if(txtEnableStripe=="Y"){
                                Stripe.card.createToken({
                                        number: $('#txtCCNumber').val(),
                                        cvc: $('#txtCVV2').val(),
                                        exp_month: $('#txtMM').val(),
                                        exp_year: $('#txtYY').val(),
                                        name: '<?php echo $txtFirstName; ?>',
                                        address_line1: '<?php echo $txtAddress1; ?>',
                                        address_city: '<?php echo $txtCity; ?>',
                                        address_zip: '<?php echo $txtZIP; ?>',
                                        address_state: '<?php echo $txtState; ?>',
                                        address_country: '<?php echo $ddlCountry; ?>'
                                    }, stripeResponseHandler);
                                    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="";
                        }
                    }
                    Stripe.setPublishableKey('<?php echo $txtStripePublishKey; ?>');
 
                    function stripeResponseHandler(status, response) {
                          if (response.error) {
                              // re-enable the submit button
                             // $('#btnCompleteOrder').removeAttr("disabled");
                                                  // show hidden div
                                                 document.getElementById('a_x200').style.display = 'block';
                              // show the errors on the form
                              $(".payment-errors").html(response.error.message);
                          } else {
                              var form$ = $("#frmPayment");
                              // token contains id, last4, and card type
                              var token = response['id'];
                              // insert the token into the form so it gets submitted to the server
                              form$.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
                              // and submit
                              form$.get(0).submit();
                          }
                  }

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

                    <!--content area start -->
                    <div class="text_information" align="center"><div class="alert alert-danger" id="a_x200" style="display: none;"> <strong>Error!</strong> <span class="payment-errors"></span> </div><?php echo $paymenterror?></div>
                    
                     
                   <br>

                    <div align="left">
                        
                        <form action="<?php echo $_SERVER["PHP_SELF"]?>" method="post" id="frmPayment" 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?>">

                            <input type="hidden" name="userid" value="<?php echo htmlentities($userid);?>">
                            <fieldset>
                                <table width="100%" border="0" cellspacing="2" cellpadding="2" class="manage_table">
                                    <?php

                                    if(!$paymentsuccessful) {

                                        ?>

                                    <tr>
                                        <td height="40" colspan="3"><h2><strong><?php echo TEXT_PAYMNT_DTLS; ?></strong></h2></td>
                                    </tr>
                                    <tr>
                                        <td><?php echo LABEL_TOTAL_TO_PAY; ?></td>
                                        <td colspan="2">
                                                <?php
                                                echo $adminCurrency['currency_symbol']." ".number_format($totaltopay,2,".","");
                                                ?></td>
                                    </tr>
                                        <?php

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

                                            $shipping_cost = $_SESSION['SESS_upscost'];


                                            ?>


                                    <td><?php echo LABEL_GRAND_TOTAL; ?></td>
                                    <td align="left" colspan="2"><input type="hidden" name="cart_total" value="1000">
                                                <?php
                                                echo $currency_attributes[0];
                                                echo "&nbsp;";
                                                $grandtotal=$display_total ;
                                                echo number_format($grandtotal,2,".","");
                                            }
                                            else {

                                                ?>

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

                                                <?php

                                            }

                                            ?>


                                    <tr>
                                        <td width="25%"><?php echo LABEL_CARD_NUMBER; ?></td>
                                        <td width="28%" align="left"><input type=text name="txtCCNumber" id="txtCCNumber" maxlength=16 class=textbox value="<?php echo $txtCCNumber?>" size="30"></td>
                                    </tr>
                                    <tr>
                                        <td><?php echo LABEL_CARD_VALIDATION_CODE; ?></td>
                                        <td><input type="text" name="txtCVV2" id="txtCVV2" maxlength="10"  class="textbox" value="<?php echo $txtCVV2?>" size="15">&nbsp;
                                        </td>
                                        <td width="47%"></td>
                                    </tr>
                                    <tr>
                                        <td><?php echo LABEL_EXPIRATION_DATE; ?></td>
                                        <td colspan="2">
                                            <select name="txtMM" id="txtMM" onBlur="javascript:checkNumber(this);" tabindex="3">
                                                    <?php
                                                    for($i=1;$i<13;$i++) {
                                                        if($i<10)
                                                            $val = "0".$i;
                                                        else
                                                            $val = $i;
                                                        ?>
                                                <option value="<?php echo $val;?>" <?php if($val==$txtMM || $i==$txtMM) echo "selected";?>><?php echo $val;?></option>
                                                        <?php
                                                    }
                                                    ?>
                                            </select>
                                            <select name="txtYY" id="txtYY" onBlur="javascript:checkNumber(this);" tabindex="4">
                                                    <?php
                                                    for($j=date("Y");$j<(date("Y")+35);$j++) {
                                                        j
                                                                ?>
                                                <option value="<?php echo $j;?>" <?php if($j==$txtYY) echo "selected";?>><?php echo $j;?></option>
                                                        <?php
                                                    }
                                                    ?>
                                            </select>

                                        </td>
                                    </tr>

                                    <tr>
                                        <td colspan="3">&nbsp;</td>
                                    </tr>

                                    <tr>
                                        <td colspan="3" align="center">
                                            <input type="submit"  name="btnCancelOrder" value="<?php echo BTN_CANCEL_SUBSCRIPTION; ?>" class="button" onclick="window.location.href='<?php echo SITE_URL?>/sellers/artistmain.php'">
                                            <input type="submit"  name="btnCompleteOrder" value="<?php echo BTN_COMPLETE_SUBSCRIPTION; ?>" class="button" onclick="return validateForm();">&nbsp;&nbsp;
                                        </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 colspan="3" align="center" class="text_information">
					<?php echo MSG_PAYMENT_COMPLETED; ?>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="3">&nbsp;</td>
                                    </tr>
                                    <tr>
                                        <td colspan="3" align="center">
                                            <input type='button' value='<?php echo BTN_HOME; ?>'  class='button' onClick="window.location.href='<?php echo SITE_URL?>/sellers/artistmain.php'">
                                            &nbsp;&nbsp;			</td>
                                    </tr>

                                        <?php


                                    }

                                    ?>
                                </table>
                            </fieldset></form>

                    </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";
            ?>