   <?php
   // CRUD 
   @$getId = base64_decode($_GET['id']);  
    if(@$getId){ 
        $query = mysql_query("SELECT * FROM requests WHERE id = + $getId");
        $result = mysql_fetch_array($query);
    }
    
    if(isset ($_POST['save'])){
	$p_order = rand(111111,999999);
	$customer = $_POST['customer'];
	$payment = $_POST['payment']; 
	$invoice_email = $_POST['invoice_email']; 
	$billing = $_POST['billing']; 
	$billing_email = $_POST['billing_email']; 
	$date = date('Y-m-d');
	$hour = date('H:i:s');
	$sessao = rand_char(2); 
	$status = $_POST['status']; 

	$crud = new crud('requests');  // table
    $crud->inserir("invoice_email,billing,billing_email,p_order,customer,payment,date,hour,sessao,status", "'$invoice_email','$billing','$billing_email,','$p_order','$customer','$payment','$date','$hour','$sessao','$status'");
	
	$xr = mysql_query("SELECT MAX(ID) as id FROM requests");
	$dr = mysql_fetch_assoc($xr);
	$id_request = $dr['id'];
	
	$product = $_POST['product'];
	$qtd = $_POST['qtd'];
	$domain = $_POST['domain'];
	$actions = $_POST['actions'];
	$tamanho = count($product)-1;
	for ($f = 0; $f <= $tamanho; $f++)
    {
		
	$queryR = mysql_query("SELECT * FROM products WHERE id = '".$product[$f]."'");
    $resultD = mysql_fetch_array($queryR);
	$amount = $resultD['price'];	
		
    $sql = mysql_query("INSERT INTO requests_tbl (request,customer,amount,product,qtd,domain,actions) VALUES ('".$id_request."', '".$customer."', '".$amount."', '".$product[$f]."', '".$qtd[$f]."', '".$domain[$f]."', '".$actions[$f]."')") or die ("<br><br><center>PHP Error: " . mysql_error() . "</center>");
     
    }
    
    $queryC = mysql_query("SELECT * FROM customers WHERE id = '$customer'");
    $ctm = mysql_fetch_array($queryC);
    
    $name = $ctm['name'];
	$email = $ctm['email'];
    $cpf_cnpj = $ctm['cpf_cnpj'];
    $address = $ctm['address'];
    $city = $ctm['city'];
    $passemail = base64_decode($ctm['salt']);
    
	$q = mysql_query("SELECT SUM(amount * qtd) as amount FROM requests_tbl WHERE request = '$id_request'");
 	$r = mysql_fetch_array($q);
	$totalorder = number_format($r["amount"],2,'.','');
    
    if($status == 'S') { 
	
	$dvc = $config['dias_faturas'];
	$payment_date = date('Y-m-d', strtotime("+$dvc days"));
	$arrayData = explode("-",$payment_date);
    $ano = $arrayData[0];
    $mes = $arrayData[1];
    $dia = $arrayData[2];
	
	$crud = new crud('invoices');  // table
    $crud->inserir("payment,customer,request,total,date,expiration_date,payment_date,dia,mes,ano,status", "'$payment','$customer','$id_request','$totalorder','$date','','$payment_date','$dia','$mes','$ano','open'");
	
	// SEND MAIL 
	require_once("config/mail/class.phpmailer.php");
	$query_tpl = mysql_query("SELECT * FROM email_template WHERE id = '13'");
    $template_mail = mysql_fetch_array($query_tpl);
	
	$mail = new PHPMailer();
	$mail->IsSMTP();		
	$mail->SMTPDebug = 0;		
	$mail->SMTPAuth = true;		
	$mail->IsHTML(true);
	$mail->Host = $config['smtp_host'];	
	$mail->Port = $config['smtp_port'];		
	$mail->Username = $config['smtp_user'];	
	$mail->Password = $config['smtp_pass'];	

	$mail->From = $template_mail['from_mail'];  
	$mail->FromName = $template_mail['name_from']; 

	$mail->AddAddress($email);
	$mail->IsHTML(true); 
	$mail->CharSet = 'iso-8859-1'; 
	$mail->Subject  = $template_mail['subject']; 
	
	$corpoDoEmail = $template_mail['msg']; 
	$signature = $config['signature'];
	$logo = $config['logo'];
	$company = $config['company'];
	$dvc = $config['dias_faturas'];
	$vencimentobr = date('d/m/Y', strtotime("+$dvc days"));
	$vencimentorn = date('m-d-Y', strtotime("+$dvc days"));
	
	// MAIL Variables
    $corpoDoEmail = str_replace( '%NOME%', $name, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%PEDIDO%', $p_order, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%FORMA_PAGTO%', $payment, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%SENHA%',  $passemail, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%EMPRESA%',  $company, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%CPFCNPJ%',  $cpf_cnpj, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%ENDERECO%',  $address, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%CIDADE%',  $city, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%EMAIL%',  $email, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%SIGNATURE%',  $signature, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%LOGO%',  $logo, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%TOTAL%',  $totalorder, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%DATABR%',  $vencimentobr, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%DATAEN%',  $vencimentorn, $corpoDoEmail );
    
    // END Variables
	$mail->Body = $corpoDoEmail;
	$SendOK = $mail->Send();
	$mail->ClearAllRecipients();
	$mail->ClearAttachments();
	if ($SendOK) {
	header("Location: index.php?mod=OrderAccepted&y=1"); // redirect send mail ok
    } else {
	echo "<script>
        alert ('Error sending email, please check the e-mail settings!');
        document.location.href = ('index.php?mod=OrderAccepted&y=1');
	</script>";
    }
	// END SEND 	
		
	}
	// END STATUS S
	
	if($status == 'A') { 
    
    // SEND MAIL 
	require_once("config/mail/class.phpmailer.php");
	$query_tpl = mysql_query("SELECT * FROM email_template WHERE id = '13'");
    $template_mail = mysql_fetch_array($query_tpl);
	
	$mail = new PHPMailer();
	$mail->IsSMTP();		
	$mail->SMTPDebug = 0;		
	$mail->SMTPAuth = true;		
	$mail->IsHTML(true);
	$mail->Host = $config['smtp_host'];	
	$mail->Port = $config['smtp_port'];		
	$mail->Username = $config['smtp_user'];	
	$mail->Password = $config['smtp_pass'];	

	$mail->From = $template_mail['from_mail'];  
	$mail->FromName = $template_mail['name_from']; 

	$mail->AddAddress($email);
	$mail->IsHTML(true); 
	$mail->CharSet = 'iso-8859-1'; 
	$mail->Subject  = $template_mail['subject']; 
	
	$corpoDoEmail = $template_mail['msg']; 
	$signature = $config['signature'];
	$logo = $config['logo'];
	$company = $config['company'];
	$dvc = $config['dias_faturas'];
	$vencimentobr = date('d/m/Y', strtotime("+$dvc days"));
	$vencimentorn = date('m-d-Y', strtotime("+$dvc days"));
	
	// MAIL Variables
    $corpoDoEmail = str_replace( '%NOME%', $name, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%PEDIDO%', $p_order, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%FORMA_PAGTO%', $payment, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%SENHA%',  $passemail, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%EMPRESA%',  $company, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%CPFCNPJ%',  $cpf_cnpj, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%ENDERECO%',  $address, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%CIDADE%',  $city, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%EMAIL%',  $email, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%SIGNATURE%',  $signature, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%LOGO%',  $logo, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%TOTAL%',  $totalorder, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%DATABR%',  $vencimentobr, $corpoDoEmail );
    $corpoDoEmail = str_replace( '%DATAEN%',  $vencimentorn, $corpoDoEmail );
    
    // END Variables
	$mail->Body = $corpoDoEmail;
	$SendOK = $mail->Send();
	$mail->ClearAllRecipients();
	$mail->ClearAttachments();
	if ($SendOK) {
	header("Location: index.php?mod=Orders&y=1"); // redirect send mail ok
    } else {
	echo "<script>
        alert ('Error sending email, please check the e-mail settings!');
        document.location.href = ('index.php?mod=Orders&y=1');
	</script>";
    }
	// END SEND 
	} 
	// END STATUS A 
	}
	
	if($status == 'N') { 
		
	header("Location: index.php?mod=OrderCanceled&y=1"); // redirect send mail ok	
    }
    // END STATUS N		
	
	
    if ((isset($_GET["action"])) && ($_GET["action"] == "delete")) {
    $id = base64_decode($_GET['id']); 
    $crud = new crud('requests'); // Table
    $crud->excluir("id = $id"); // ID
    
    $crud = new crud('requests_tbl'); // Table
    $crud->excluir("request = $id"); // ID
    
    $rft = $_GET['rft'];
    if($rft == 'A') { 
	header("Location: index.php?mod=Orders&y=3"); // redirect send mail ok
    }
    if($rft == 'S') { 
	header("Location: index.php?mod=OrderAccepted&y=3"); // redirect send mail ok
    }
    if($rft == 'N') { 
	header("Location: index.php?mod=OrderCanceled&y=3"); // redirect send mail ok
    }
    }
    
    
    ?>

    
    <script type="text/javascript">  
$(document).ready(function(){  
 
    var input = '<label style="display: block"><tr><td><div class="form-group"><label for="Input"><?php echo $lang['PRODUCT']; ?></label><select id="product" name="product[]" class="form-control select2" style="width: 100%;"><option value="">Select</option><?php $prds = mysql_query("SELECT * FROM products order by product ASC"); while($prd = mysql_fetch_array($prds)){ ?><option value="<?php echo $prd['id']; ?>"><?php echo $prd['product']; ?> - <?php echo $prd['price']; ?></option><?php } ?> </select></div></td><td><div class="form-group"><label for="Input"><?php echo $lang['DOMAIN']; ?></label><input type="text" class="form-control" name="domain[]"></div></td><td><div class="form-group"><label for="Input"><?php echo $lang['QTD']; ?></label><input type="number" min="1" class="form-control" name="qtd[]"></div></td><td><div class="form-group"><label for="Input"><?php echo $lang['ACTION_DOMAIN']; ?></label><select name="actions[]" class="form-control" style="width: 100%;"><option value="">Select</option><option value="Register">Register</option><option value="Transfer">Transfer</option></select></div></td></tr><a href="#" class="remove btn btn-danger"><i class="fa fa-remove"></i></a><hr></label>';  
    $("input[name='add']").click(function( e ){  
        $('#inputs_adicionais').append( input );  
    });  
 
    $('#inputs_adicionais').delegate('a','click',function( e ){  
        e.preventDefault();  
        $( this ).parent('label').remove();  
    });  
 
});  

$(function () {
        //Initialize Select2 Elements
        $(".select2").select2();       
        });
</script> 
      
    <!-- Content Wrapper. Contains page content -->
      <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <section class="content-header">
          <h1>
            <?php echo $lang['TITLE_NEW_ORDER']; ?>
          </h1>
          
        </section>

       
       <!-- Main content -->
        <section class="content">
          <div class="row">
			  
			  
            <!-- left column -->
            <div class="col-md-12">
              <!-- general form elements -->
              <div class="box box-primary">
                <div class="box-header with-border">
                  <h3 class="box-title"><?php echo $lang['ORDER']; ?></h3>
                </div><!-- /.box-header -->
                <!-- form start -->
                <form role="form" method="POST" id="Order" name="Order">

					
                  <div class="box-body">
				 
				 <table class="table table-striped">
				 <tr>
					 
				 <td>
				 <div class="form-group">
                      <label for="Input"><?php echo $lang['CUSTOMER']; ?></label>
                      <select id="customer" name="customer" class="form-control select2" style="width: 100%;">
						  <option value="">Select</option>
                    <?php
					$catcc = mysql_query("SELECT * FROM customers order by name ASC");
					while($custm = mysql_fetch_array($catcc)){ 
					?>
                    <option value="<?php echo $custm['id']; ?>" <?php if (@$result['customer'] == $custm['id']) { echo "selected"; } ?>><?php echo $custm['name']; ?> - <?php echo $custm['email']; ?></option>
				    <?php } ?> 
				    </select>
                    </div>
				 </td>
				 
				 <td>
				 <div class="form-group">
                      <label for="Input"><?php echo $lang['ORDER_PAY']; ?></label>
                    <select id="payment" name="payment" class="form-control" style="width: 100%;">
					<option value="PayPal">PayPal</option>
                    <option value="PagSeguro">PagSeguro</option>
                    <option value="bCash">bCash</option>
                    <option value="Boleto">Boleto</option>
				    </select>
                    </div>
				 </td>
				
				 <td>
				 <div class="form-group">
                      <label for="Input"><?php echo $lang['STATUS']; ?></label>
                    <select id="status" name="status" class="form-control" style="width: 100%;">
					<option value="A"><?php echo $lang['ORDER_STATUS_A']; ?></option>
                    <option value="S"><?php echo $lang['ORDER_STATUS_S']; ?></option>
                    <option value="N"><?php echo $lang['ORDER_STATUS_N']; ?></option>
				    </select>
                    </div>
				 </td>

				 </tr>
				 </table>	
				 
				   
		
        <label style="display: block">
		<table class="table table-striped">
		<tr>
		
		<td>
		<div class="form-group">
        <label for="Input"><?php echo $lang['PRODUCT']; ?></label>
        <select id="product" name="product[]" class="form-control " style="width: 100%;">
		<option value="">Select</option>
        <?php
		$prds = mysql_query("SELECT * FROM products order by product ASC");
		while($prd = mysql_fetch_array($prds)){ 
		?>
        <option value="<?php echo $prd['id']; ?>"><?php echo $prd['product']; ?> - <?php echo $prd['price']; ?></option>
		<?php } ?> 
		</select>
        </div>
		</td>
		
		<td>
		<div class="form-group">
        <label for="Input"><?php echo $lang['DOMAIN']; ?></label>
        <input type="text" class="form-control" name="domain[]">
        </div>
		</td>
		<td>
		<div class="form-group">
        <label for="Input"><?php echo $lang['QTD']; ?></label>
        <input type="number" min="1" class="form-control" name="qtd[]">
        </div>
		</td>
		<td>
		<div class="form-group">
        <label for="Input"><?php echo $lang['ACTION_DOMAIN']; ?></label>
        <select name="actions[]" class="form-control" style="width: 100%;">
		<option value="">Select</option>
		<option value="Register">Register</option>
        <option value="Transfer">Transfer</option>
		</select>
        </div>
		</td>
		<td><div class="form-group"><label for="Input">&nbsp;</label><label style="display: block"><input type="button" class="btn btn-info" name="add" value="Add" /></label></div></td>
		
		</tr>
		
		
		</table></label> 
		<hr>
		<table class="table table-condensed "><thead>
        <fieldset id="inputs_adicionais" style="border: none">  
        </fieldset>	
		</thead></table>	
		
                   
                  
                  
                  <div class="box-footer">
					  
		  <?php if (@$result['id'] <> '') { ?>

		  <input type="submit" value="<?php echo $lang['UPDATE']; ?>" name="update" style="text-transform:uppercase" class="btn btn-info btn-lg btn-block">
		  <input type="hidden" name="registerID" value="<?php echo @$result['id']; ?>"> 
		  <? } else { ?>
		  <input type="submit" value="<?php echo $lang['REGISTER']; ?>" name="save" style="text-transform:uppercase" class="btn btn-success btn-lg btn-block">
		  <?php } ?>
					  
                  </div>
                  
                 
                </form>
                    
                   
                  </div><!-- /.box-body -->

                 
                
                
              </div><!-- /.box -->
           </div><!-- /.col -->
           
           
         
           
          </div><!-- /.row -->
        </section><!-- /.content -->
       
        
      </div><!-- /.content-wrapper -->
   
   
   
   
