<?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 Status";
$page="47_customer_invoice_status.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');
  ?>
 
 

<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>
				
				<div class="col-md-2">
				<strong>Select Customer

<?php
//$datePart = date('ymd'); // '250807' (6 digits)
//$randomPart = mt_rand(1000, 9999); // 4 digits
//
//$randomNumber = $datePart . $randomPart; // Total = 6 + 4 = 10 digits
//
//echo $randomNumber; // e.g., 2508074721


//$datePart = date('ymd'); // e.g., "250807"
//
//// Serial part: fetch last serial number from DB or file; here we simulate it
//$serial = 1; // Example starting serial; ideally this comes from storage
//
//// Pad serial with leading zeros to ensure 4 digits
//$serialPart = str_pad($serial, 4, '0', STR_PAD_LEFT);
//
//// Combine to form 10-digit number
//$number = $datePart . $serialPart;
//
//echo $number; // Output: 2508070001
?>
				</strong>
				</div>
				<div class="col-md-4">
			<select id="ref_no_src" name="ref_no_src"  class="form-select"    >
			
			<?php foreign_relation($conn,'accounts_reference','ref_no','display_name',$_POST['ref_no'],'ref_type=2 order by ref_no');?>
		
        	</select>
				</div>
				<div class="col-md-6">
				<button type="submit" class="btn btn-primary btn-sm" name="ins_master_data" id="ins_master_data" ><i class="bi bi-plus-lg me-1"></i> New Invoice&nbsp;&nbsp;&nbsp;</button>
				</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="5%" scope="col"><span class="card-title" style="font-size:12px; text-transform:uppercase;"> Inv No </span></th>
                    <th width="11%" scope="col"><span class="card-title" style="font-size:12px; text-transform:uppercase;">Inv Date </span></th>
                    <th width="11%" scope="col">Customer</th>
                    <th width="10%" scope="col">Quantity</th>
                    <th width="13%" scope="col">Invoice Amt </th>
                    <th width="12%" scope="col">Discount</th>
                    <th width="13%" scope="col">Net Sales </th>
                    <th width="14%" scope="col"><span class="style1">Entry by </span></th>
                    <th width="13%" scope="col"><span class="style1">Entry at </span></th>
                    <th width="9%" 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 ledger_id>0 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(isset($_POST['run_data'])){}?>		
      <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 $fname[$data->entry_by];?></td>
      <td><?php echo date("d-M-y",strtotime($data->checked_at)).' <br />'.date("h:i A",strtotime($data->checked_at));?></td>
      <td>
	  <?php if($_SESSION['user']['id']==10001 || $_SESSION['user']['id']==10002) {?>
	<a href="1001_pos_sales_entry_edit.php?active_id=<?=$active_id?>&menu_id=<?=$menu_id?>&tr_no=<?=$data->tr_no?>"> <button type="submit" class="btn btn-danger btn-sm" name="inv_edit" id="inv_edit" style="white-space:nowrap" ><i class="bi bi-pen"></i> Edit&nbsp;&nbsp;&nbsp;</button></a>
	<?php } ?>	  </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>&nbsp;</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>