<?php
ini_set('display_errors', 0);
//error_reporting(E_ALL);
//ini_set('display_errors', 1);

session_start();
ob_start();

require_once('configuration/server_connect.php');
require_once('configuration/all_function.php');

$active_id=$_REQUEST['active_id'];
$menu_id=$_REQUEST['menu_id'];

// Common Information

$page_title="Sales Invoice Journal";
$page="47_customer_invoice_journal.php?active_id=".$active_id."&menu_id=".$menu_id."";
$table='journal_master';	
$unique='jv_no';

// End Common Information



if(isset($_POST['ins_master_data']))

{


$sales_inv_page="1001_pos_sales_entry.php?active_id=".$active_id."&menu_id=".$menu_id."";

$status='MANUAL';
$entry_by =  $_SESSION['user']['id'];
$entry_at = date('Y-m-d H:i:s');
$group_for = $_SESSION['user']['group'];
$warehouse_id = $_SESSION['user']['depot'];
$jv_date=date('Y-m-d');
$ref_no_src=$_POST['ref_no_src'];
$jv_type=5;
$jv_special=1;
$acc_terms=1;
$tr_from='Sales';
//$tr_no=1001;
$blank=0;
$blank_date='0000-00-00';
$ms_data_table='journal_master';

$date = date('ymd');
$file = "serial_$date.txt";


if (file_exists($file)) {
    $serial = (int)file_get_contents($file);
    $serial++;
} else {
    $serial = 1;
}

file_put_contents($file, $serial);

$serialPart = str_pad($serial, 4, '0', STR_PAD_LEFT);
$number = $date . $serialPart;

 $number; 



if($ref_no_src==200001){
$sales_type=1;
}else{
$sales_type=2;
}



if($ref_no_src>0){
  $ins_sql = 'INSERT INTO  journal_master (jv_no, year, jv_id, view_jv_no, jv_type, jv_special, jv_date, group_for, warehouse_id, ref_no, master_ledger_id, emp_code, tr_from, tr_no, remarks, acc_terms, status, entry_at, entry_by, edit_at, edit_by, checked_at, checked_by, approve_by, approve_at, sales_type) VALUES

("'.$number.'", "'.$blank.'", "'.$blank.'", "'.$blank.'", "'.$jv_type.'", "'.$jv_special.'", "'.$jv_date.'", "'.$group_for.'", "'.$warehouse_id.'", "'.$ref_no_src.'", "'.$blank.'", "'.$blank.'", "'.$tr_from.'", "'.$number.'", "'.$blank.'", "'.$acc_terms.'", "'.$status.'", "'.$entry_at.'", "'.$entry_by.'", "'.$blank_date.'", "'.$blank.'", "'.$blank_date.'", "'.$blank.'", "'.$blank.'", "'.$blank_date.'", "'.$sales_type.'")';
	
mysqli_query($conn,$ins_sql);
}


header("location:".$sales_inv_page.'&tr_no='.$number."");

}




?>

<!DOCTYPE html>
<html lang="en"><style type="text/css">
<!--
.style1 {font-size: 12px}
-->
</style>

 <?php require_once('inc_files/inc_head.php'); ?>
 
 <?php
  do_calander('#fdate');
  do_calander('#tdate');
  ?>
 
 <script language="javascript">

function getXMLHTTP() { //fuction to return the xml http object



		var xmlhttp=false;	



		try{



			xmlhttp=new XMLHttpRequest();



		}



		catch(e)	{		



			try{			



				xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");

			}

			catch(e){



				try{



				xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");



				}



				catch(e1){



					xmlhttp=false;



				}



			}



		}



		 	



		return xmlhttp;



    }







	function update_value(jv_no)
	{

//var unit_price=(document.getElementById('unit_price_'+jv_no).value); 


var flag=(document.getElementById('flag_'+jv_no).value); 

var strURL="47_customer_invoice_journal_ajax.php?jv_no="+jv_no+"&flag="+flag;


		var req = getXMLHTTP();



		if (req) {



			req.onreadystatechange = function() {

				if (req.readyState == 4) {

					// only if "OK"

					if (req.status == 200) {						

						document.getElementById('divi_'+jv_no).style.display='inline';

						document.getElementById('divi_'+jv_no).innerHTML=req.responseText;						

					} else {

						alert("There was a problem while using XMLHTTP:\n" + req.statusText);

					}

				}				

			}

			req.open("GET", strURL, true);

			req.send(null);

		}	



}




</script>

<body>

  <!-- ======= Header ======= -->
  <?php 
  require_once('inc_files/inc_header.php');
  ?><!-- End Header -->

  <!-- ======= Sidebar ======= -->
  <?php  require_once('inc_files/inc_menu.php'); ?><!-- End Sidebar-->

  <main id="main" class="main">

    <div class="pagetitle">
      <h1><?php echo $page_title?></h1>
      <nav>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="home.php">Home</a></li>
          <li class="breadcrumb-item">Sales Management</li>
          <li class="breadcrumb-item active"><?php echo $page_title?></li>
        </ol>
      </nav>
    </div><!-- End Page Title -->

    <section class="section">
      <div class="row">
        <div class="col-lg-12"> 

          <div class="card">
            <div class="card-body">
			<br>
            <form class="row g-3" action="" method="post" name="codz" id="codz" onSubmit="return check()">
	 
                <div class="col-md-6">
                 <label for="first_name" class="form-label"><strong>From Date</strong></label>
                 <input type="text" class="form-control" id="fdate" name="fdate" value="<?php echo isset($_POST['fdate'])?$_POST['fdate']:date('Y-m-d');?>" >
			    
                </div>
				
				<div class="col-md-6">
                 <label for="first_name" class="form-label"><strong>To Date</strong></label>
     			<input type="text" name="tdate" id="tdate" class="form-control"  value="<?php echo isset($_POST['tdate'])?$_POST['tdate']:date('Y-m-d');?>" />
			   
                </div>
				
				<div class="col-md-3">
                 <label for="first_name" class="form-label"><strong>Invoice No</strong></label>
            <select id="jv_no_src" name="jv_no_src"  class="form-select"    >
			<option></option>
			
			<?php foreign_relation($conn,'journal_master','jv_no','view_jv_no',$_POST['jv_no_src'],'jv_type=5 and jv_id>0 order by year,jv_id');?>
		
        	</select>
			    
                </div>
				
				<div class="col-md-4">
                 <label for="first_name" class="form-label"><strong>Customer Name</strong></label>
     		<select id="ref_no" name="ref_no"  class="form-select"    >
			<option></option>
			<?php foreign_relation($conn,'accounts_reference','ref_no','display_name',$_POST['ref_no'],'ref_type=2 order by display_name');?>
		
        	</select>
			   
                </div>
				
				<div class="col-md-3">
                 <label for="first_name" class="form-label"><strong>Sales Type</strong></label>
            <select id="sales_type_src" name="sales_type_src"  class="form-select"    >
			<option></option>
			
			<?php foreign_relation($conn,'sales_type','id','sales_type',$_POST['sales_type_src'],'1 order by id');?>
		
        	</select>
			    
                </div>
				
				<div class="col-md-2" style="text-align:center">
                 <label for="first_name" class="form-label"><strong>&nbsp;</strong></label><br />
     	 <button type="submit" name="run_data" id="run_data" class="btn btn-success rounded-pill btn-sm">&nbsp;<i class="bi bi-filter me-1"></i> Run Report&nbsp;&nbsp;</button>
			   
                </div>
				
				<div class="col-md-12">
				</div>
				<div class="col-md-12">
				</div>
			
				
				
               
  </form>
  <br>
	
              <!-- Table with stripped rows -->
              <table width="100%" class="table table-sm" style="font-size:12px;">
                <thead>
                  <tr style="text-transform:uppercase; color:#012970; background:#f6f9ff;  border-top: 1px solid #CCCCCC;">
                    <th width="4%" scope="col"><span class="card-title" style="font-size:12px; text-transform:uppercase;"> Inv No </span></th>
                    <th width="8%" scope="col"><span class="card-title" style="font-size:12px; text-transform:uppercase;">Inv Date </span></th>
                    <th width="8%" scope="col">Customer</th>
                    <th width="8%" scope="col">Quantity</th>
                    <th width="10%" scope="col">Invoice Amt </th>
                    <th width="9%" scope="col">Discount</th>
                    <th width="10%" scope="col">Net Sales </th>
                    <th width="10%" scope="col">DR Amt </th>
                    <th width="10%" scope="col">CR Amt </th>
                    <th width="15%" scope="col"><span class="style1">Entry by </span></th>
                    <th width="8%" scope="col"><span class="style1">Action </span></th>
                  </tr>
                </thead>
                <tbody>
					<?php
					
					
 
//if($_POST['fdate']!=''&&$_POST['tdate']!='') $date_con .= ' and jv_date between "'.$_POST['fdate'].'" and "'.$_POST['tdate'].'"';


if($_POST['jv_no_src']==""){ 
  
   if($_POST['fdate']!=""){
  	 $fdate=$_POST['fdate'];
  }else{
  	 $fdate=date('Y-m-d');
	//$fdate = date("Y-m-d", strtotime("-6 month"));
  }
 
 
 if($_POST['tdate']!=""){
  	$tdate=$_POST['tdate'];
  }else{
  	$tdate=date('Y-m-d');
	//$tdate = date("Y-m-d", strtotime("+1 day"));
  }
  
  $date_con .= ' and jv_date between "'.$fdate.'" and "'.$tdate.'"';
  
 }




if($_POST['ref_no']!=''){
$ref_no_con=" and ref_no='".$_POST['ref_no']."' ";
}


if($_POST['jv_no_src']!=''){
$jv_no_con=" and jv_no='".$_POST['jv_no_src']."' ";
}

if($_POST['sales_type_src']!=''){
$sales_type_con=" and sales_type='".$_POST['sales_type_src']."' ";
}

	
		 $sql = "select ref_no, display_name from accounts_reference where 1 group by ref_no";
		 $query = mysqli_query($conn,$sql);
		 while($info=mysqli_fetch_object($query)){
  		 $display_name[$info->ref_no]=$info->display_name;
		}	
		
		 $sql = "select user_id, fname from user_management where 1 group by user_id";
		 $query = mysqli_query($conn,$sql);
		 while($info=mysqli_fetch_object($query)){
  		 $fname[$info->user_id]=$info->fname;
		}	
		
		
		 $sql = "select jv_no, sum(dr_amt) as dr_amt, sum(cr_amt) as cr_amt from secondary_journal where tr_from='Sales' group by jv_no";
		 $query = mysqli_query($conn,$sql);
		 while($info=mysqli_fetch_object($query)){
  		 $dr_amt[$info->jv_no]=$info->dr_amt;
		 $cr_amt[$info->jv_no]=$info->cr_amt;
		}
		
		 $sql = "select jv_no, sum(total_unit) as total_unit, sum(total_amt) as total_amt, sum(discount_amt) as discount_amt from sales_invoice where 1 group by jv_no";
		 $query = mysqli_query($conn,$sql);
		 while($info=mysqli_fetch_object($query)){
  		 $total_unit[$info->jv_no]=$info->total_unit;
		 $total_amt[$info->jv_no]=$info->total_amt;
		 $discount_amt[$info->jv_no]=$info->discount_amt;
		}	
		
		
			
					  $sql = 'select * from '.$table.' where jv_type="5" and status!="MANUAL" '.$date_con.$ref_no_con.$jv_no_con.$sales_type_con.' 
					  order by jv_no desc ';
						$query = mysqli_query($conn,$sql);
						while ($data = mysqli_fetch_object($query)) {

					?>
	<?php //if($total_amt[$data->jv_no]-$dr_amt[$data->jv_no]!=0){}?>		
      <tr>
      <td><a href="view_file/sales_pos_print_view.php?jv_no=<?php echo $data->jv_no;?>" target="_blank"><?php echo $data->view_jv_no;?></a></td>
      <td><?php echo date('d-M-y',strtotime($data->jv_date));?></td>
      <td><?php echo $display_name[$data->ref_no];?></td>
      <td><?php echo number_format($total_unit[$data->jv_no],2);?></td>
	  <td><?php echo number_format($total_amt[$data->jv_no],2); $tot_total_amt +=$total_amt[$data->jv_no];?></td>
	  <td><?php echo number_format($discount_amt[$data->jv_no],2); $tot_discount_amt +=$discount_amt[$data->jv_no];?></td>
	  <td><?php echo $net_sales_amt=number_format(($total_amt[$data->jv_no]-$discount_amt[$data->jv_no]),2); 
	  $tot_net_sales_amt +=$total_amt[$data->jv_no]-$discount_amt[$data->jv_no];?></td>
	  <td><?php echo $dr_amt[$data->jv_no]; $tot_dr_amt +=$dr_amt[$data->jv_no]; ?></td>
	  <td><?php echo $cr_amt[$data->jv_no]; $tot_cr_amt +=$cr_amt[$data->jv_no]; ?></td>
	  <td><?php echo $fname[$data->entry_by];?></td>
      <td><span id="divi_<?php echo $data->jv_no?>">
			<?php if ($dr_amt[$data->jv_no]>0) {?>	  
			<a href="view_file/journal_print_view.php?jv_no=<?=$data->jv_no?>" target="_blank"> <button type="submit" class="btn btn-success btn-sm" name="inv_edit" id="inv_edit" style="white-space:nowrap" ><i class="bi bi-eye"></i> VIEW&nbsp;&nbsp;&nbsp;</button></a>
			<?php }else{?>
			  <input name="flag_<?php echo $data->jv_no?>" type="hidden" id="flag_<?php echo $data->jv_no?>" value="1" />
			  <input class="form-control" type="button" name="Button" value="JOURNAL"  onclick="update_value(<?php echo $data->jv_no?>)" style="width:80px; height:35px; background-color: #FF3366; font-weight:700; font-size:12px;"/>
			  <?php }?>
          </span></td>
      </tr>
      
				  <?php } ?>
				  
	 <tr>
        <td>&nbsp;</td>
        <td><strong>TOTAL:</strong></td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td><strong><?php echo number_format($tot_total_amt,2);?></strong></td>
        <td><strong><?php echo number_format($tot_discount_amt,2);?></strong></td>
        <td><strong><?php echo number_format($tot_net_sales_amt,2);?></strong></td>
        <td><strong><?php echo number_format($tot_dr_amt,2);?></strong></td>
        <td><strong><?php echo number_format($tot_cr_amt,2);?></strong></td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
	 </tr>
                </tbody>
              </table>
              <!-- End Table with stripped rows -->

            </div>
          </div>

        </div>

        
      </div>
    </section>

  </main><!-- End #main -->

  <!-- ======= Footer ======= -->
  <?php require_once('inc_files/inc_footer.php'); ?>
 <!-- ======= Footer ======= -->
 <?php 
 selected_two("#jv_no_src");
 selected_two("#ref_no");
  //selected_two("#ref_no_src");
 ?>
</body>

</html>