<?php 
include 'session.php';

extract($_REQUEST);



$requestData= $_REQUEST;
$stt = $requestData['start'];
$len = $requestData['length'];
// print_r($requestData);
 
$data = array();
// echo $data;

if($_REQUEST['pageaction'] == "product_purchase_listing"){
	include "includes/Mdme-functions.php";	
	$mdme = getMdmeProduct_PurchaseEntry($db,'');	
	include_once "includes/pagepermission.php";	
	include_once('includes/display-functions.php');

		
	$cond_subtbl = ""; $cond_mntbl = "";
	
		
	$cond_finyear = "";	
	if(isset($_REQUEST['srch_finyear']) && $_REQUEST['srch_finyear'] !="" ){	
		$cond_finyear ="  and (t1.financial_id='".$_REQUEST['srch_finyear']."') ";
	} 
		
	$cond_pdt_type = "";	
	if(isset($_REQUEST['srch_pdt_type']) && $_REQUEST['srch_pdt_type'] !="" ){	
		$cond_pdt_type ="  and (t3.product_id='".$_REQUEST['srch_pdt_type']."') ";
	} 
		
	$cond_supplier = "";	
	if(isset($_REQUEST['srch_supplier']) && $_REQUEST['srch_supplier'] !="" ){	
		$cond_supplier ="  and (t1.sup_id='".$_REQUEST['srch_supplier']."') ";
	}
		
	$whrcon = "";
	if(isset($_REQUEST['srch_fmdate']) && $_REQUEST['srch_fmdate'] !="" )
	{
		$whrcon .= " and CAST(t1.p_invoice_date as date) >=  cast(DATE_FORMAT(STR_TO_DATE('".$_REQUEST['srch_fmdate']."','%d-%m-%Y'), '%Y-%m-%d') as date) ";
	}
	if(isset($_REQUEST['srch_todate']) && $_REQUEST['srch_todate'] !="" )
	{
		$whrcon .= " and CAST(t1.p_invoice_date as date) <= cast(DATE_FORMAT(STR_TO_DATE('".$_REQUEST['srch_todate']."','%d-%m-%Y'), '%Y-%m-%d') as date) ";
	}
// 	echo 'hi';
// exit;
$str_all = "SELECT t1.*, 
                        DATE_FORMAT(t1.p_invoice_date,'%d-%m-%Y') AS disp_inv_date, 
                            t1.IsActive AS status, 
							t1.p_invoice_no as invoice_no,
                           
                            t3.sup_name, 
                            t3.sup_state, 
                            t3.sup_city, 
                            t3.sup_address, 
                            t3.sup_gstno, 
                            t3.sup_postcode
                        FROM t_product_entry_main t1 
                       
                        INNER JOIN m_supplier t3 ON t1.sup_id = t3.sup_id 
                        WHERE 1=1 
                        AND t1.IsActive <> 2 
                        AND t1.p_invoice_no IN 
                        (SELECT t1.p_invoice_no FROM t_product_entry_details t1  
							INNER JOIN t_product_entry_main t2 on t1.p_invoice_no = t2.p_invoice_no 
							INNER JOIN m_product t3 on t1.pdt_type = t3.product_id
							WHERE t1.IsActive <> 2 ".$cond_subtbl." ".$cond_pdt_type." )
                            ".$cond_mntbl."  
                            ".$cond_finyear." 
                            
                            ".$cond_supplier."  
                            ".$whrcon."  
                        ORDER BY t1.p_invoice_no DESC";

	
	// print_r($str_all);
	// exit;
	
	$get_tota = $db->get_rsltset($str_all);
	$totalData = count($get_tota);
	$totalFiltered = $totalData;	
		
	$str_all .= " limit ".$stt.",".$len;		
	
    $rslt_info =  $db->get_rsltset($str_all);
		

	$s_no = 1;
    foreach($rslt_info as $rs){
		$nestedData=array();

		$editid = base64_encode($rs['p_invoice_no']);
		$stats = $rs['status'];					
					
		$pdt_skus = $db->get_rsltset(" SELECT 
											t1.pdt_type,
											t1.qty_grm,
											t1.amt_per_grm,
											t2.product_name
										FROM 
											t_product_entry_details t1
										INNER JOIN
											m_product t2 ON t1.pdt_type = t2.product_id
										WHERE 
											t1.p_invoice_no = '".$rs['p_invoice_no']."'
									");

		
            $pdt_type = array(); 
            $pdt_qty = array(); 
            $pdt_amount = array();
            
            foreach ($pdt_skus as $pdt_sku) {
                $pdt_type[] = $pdt_sku['product_name'];
                $pdt_qty[] = $pdt_sku['qty_grm'];
            	$pdt_amount[] = $pdt_sku['amt_per_grm'];
            }
            
            // Convert the array of values to a comma-separated string
            $pdt_type = implode(', ', $pdt_type);
            $pdt_csv = implode(', ', $pdt_qty);
            $pdt_amt = implode(', ', $pdt_amount);

		if( $stats == '1') 

		 {
			//change status active to inactive
			$statusurl = "'product_purchase_actions.php','Id=$editid&action=changestatus&actval=0'";

		   $incstat =  '<div class="btn-group" data-toggle="btn-toggle" >
				<button class="btn btn-success btn-sm active" type="button"><i class="fa fa-square text-green"></i> Active</button>
				<button class="btn btn-default btn-sm" type="button" onclick="funchangestatus(this,'.$statusurl.');"><i class="fa fa-square text-red"></i> &nbsp;</button>
				</div>'	;				
		 } else {
			//change status inactive to active
			$statusurl = "'product_purchase_actions.php','Id=$editid&action=changestatus&actval=1'";
			
			 $incstat =  '<div class="btn-group" data-toggle="btn-toggle" >
				<button class="btn btn-default btn-sm" type="button" onclick="funchangestatus(this,'.$statusurl.');"><i class="fa fa-square text-green"></i> &nbsp;</button>
				<button class="btn btn-danger btn-sm active" type="button"><i class="fa fa-square text-red"></i> InActive</button>
			</div>'	;	
		}

			
		
		$edit_html = '<a href="product_purchase_form.php?act=edit&id='.$editid.'" title="edit" data-toggle="tooltip" class="btn btn-info btn-sm"> <i class="fa fa-edit"></i> </a>';      
		       
		//del 
	    $delurl = "product_purchase_actions.php?Id=$editid&action=del";

		$del_html = '<a href="javascript:void(0);" title="delete" data-toggle="tooltip" class="btn btn-danger btn-sm" onClick="javascript:funStats_purchase(this, \''.$delurl.'\')"><i class="fa fa-times"></i></a>';	     
				
		$pdt_cnt =$db->get_a_line("select count(*) as disp_cnt from t_product_entry_details where 1=1 and IsActive=1 and p_invoice_no='".$rs['p_invoice_no']."' ");

		if(trim($res_modm_prm['EditPrm'])=="1") {
			$edit_html = $edit_html;
		  }else{
			$edit_html = "";			
		}
		 
		if(trim($res_modm_prm['DeletePrm'])=="1") {
			$del_html = $del_html;
		}else{
			$del_html = "";
		}			
			
		//get product count lists 		
		$pdt_sku_cnt = get_purchase_pdt_cnt_lists($db,$rs['p_invoice_no']);	
					
		
		$nestedData[]=$s_no++;
		$nestedData[]=$rs['actu_inv_no'];
		$nestedData[]=$rs['disp_inv_date'];
		// $nestedData[]=$rs['product_name'];
		$nestedData[]=$rs['sup_name']. '</br><span style="color:green; font-size:12px">'.$rs['sup_gstno'].'</span>';
		$nestedData[] = $rs['sup_city'].'</br>'.$rs['sup_state'].'</br>'.$rs['sup_postcode']; 
		// $nestedData[] = $pdt_csv;
		// $nestedData[]=$rs['sup_city'];
		$nestedData[]=$pdt_type.'</br>(<span style="color:blue; font-size:12px">'.$pdt_csv.'</span>)';
		$nestedData[]=$rs['tot_pur_amount'];
 			
		$nestedData[]=$rs['tot_tax_amt'];
		$nestedData[]=$rs['final_pur_amt'];
		$nestedData[] = $incstat;					
			
		$nestedData[] =  $edit_html.'&nbsp;'.$del_html;
		$nestedData[] = $pdt_amt;	
		$nestedData[] = $rs['sup_name'];
		$nestedData[] = $rs['sup_gstno'];
		
		
		$data[] = $nestedData;
	}		

	
}
else if($_REQUEST['pageaction'] == "product_flow_listing"){
	include "includes/Mdme-functions.php";	
	$mdme = getMdmeProduct_flowEntry($db,'');	
	include_once "includes/pagepermission.php";	
	include_once('includes/display-functions.php');

		
	$cond_subtbl = ""; $cond_mntbl = "";
	
		
	$cond_finyear = "";	
	if(isset($_REQUEST['srch_finyear']) && $_REQUEST['srch_finyear'] !="" ){	
		$cond_finyear ="  and (t1.financial_id='".$_REQUEST['srch_finyear']."') ";
	} 
		
	$cond_pdt_type = "";	
	if(isset($_REQUEST['srch_pdt_type']) && $_REQUEST['srch_pdt_type'] !="" ){	
		$cond_pdt_type ="  and (t1.pdt_type='".$_REQUEST['srch_pdt_type']."') ";
	} 
		
	$cond_supplier = "";	
	if(isset($_REQUEST['srch_supplier']) && $_REQUEST['srch_supplier'] !="" ){	
		$cond_supplier ="  and (t1.sup_id='".$_REQUEST['srch_supplier']."') ";
	}
	$cond_flow = "";	
	if(isset($_REQUEST['product_flow']) && $_REQUEST['product_flow'] !="" ){	
		$cond_flow ="  and (t1.p_flow='".$_REQUEST['product_flow']."') ";
	}
		
	$whrcon = "";
	if(isset($_REQUEST['srch_fmdate']) && $_REQUEST['srch_fmdate'] !="" )
	{
		$whrcon .= " and CAST(t1.p_date as date) >=  cast(DATE_FORMAT(STR_TO_DATE('".$_REQUEST['srch_fmdate']."','%d-%m-%Y'), '%Y-%m-%d') as date) ";
	}
	if(isset($_REQUEST['srch_todate']) && $_REQUEST['srch_todate'] !="" )
	{
		$whrcon .= " and CAST(t1.p_date as date) <= cast(DATE_FORMAT(STR_TO_DATE('".$_REQUEST['srch_todate']."','%d-%m-%Y'), '%Y-%m-%d') as date) ";
	}
// 	echo 'hi';
// exit;

$str_all = "SELECT t1.*, 
                        DATE_FORMAT(t1.p_date,'%d-%m-%Y') AS disp_inv_date, 
                            t1.IsActive AS status, 
							t1.p_flow,
							t1.qty_grm,
                            t2.product_name, 
                            t3.sup_name, 
                            t3.sup_state, 
                            t3.sup_city, 
                            t3.sup_address, 
                            t3.sup_gstno, 
                            t3.sup_postcode
                        FROM t_product_flow_details t1 
                        
                        INNER JOIN m_product t2 ON t1.pdt_type = t2.product_id
                        INNER JOIN m_supplier t3 ON t1.sup_id = t3.sup_id 
                        WHERE 1=1 
                        AND t1.IsActive <> 2 
						AND t1.financial_id = '".$_SESSION["Financial_id"]."'
							".$cond_subtbl."
                            ".$cond_mntbl."  
                            ".$cond_finyear." 
                            ".$cond_pdt_type." 
                            ".$cond_supplier."  
                            ".$cond_flow."  
                            ".$whrcon."  
                        ORDER BY t1.p_id DESC";

	
	// print_r($str_all);
	// exit;

	$get_tota = $db->get_rsltset($str_all);
	$totalData = count($get_tota);
	$totalFiltered = $totalData;	
		
	$str_all .= " limit ".$stt.",".$len;		
	
    $rslt_info =  $db->get_rsltset($str_all);

	$s_no = 1;
    foreach($rslt_info as $rs){
		$nestedData=array();

		$editid = base64_encode($rs['p_id']);
		$stats = $rs['status'];		

		if( $stats == '1') 

		 {
			//change status active to inactive
			$statusurl = "'product_flow_actions.php','Id=$editid&action=changestatus&actval=0'";

		   $incstat =  '<div class="btn-group" data-toggle="btn-toggle" >
				<button class="btn btn-success btn-sm active" type="button"><i class="fa fa-square text-green"></i> Active</button>
				<button class="btn btn-default btn-sm" type="button" onclick="funchangestatus(this,'.$statusurl.');"><i class="fa fa-square text-red"></i> &nbsp;</button>
				</div>'	;				
		 } else {
			//change status inactive to active
			$statusurl = "'product_flow_actions.php','Id=$editid&action=changestatus&actval=1'";
			
			 $incstat =  '<div class="btn-group" data-toggle="btn-toggle" >
				<button class="btn btn-default btn-sm" type="button" onclick="funchangestatus(this,'.$statusurl.');"><i class="fa fa-square text-green"></i> &nbsp;</button>
				<button class="btn btn-danger btn-sm active" type="button"><i class="fa fa-square text-red"></i> InActive</button>
			</div>'	;	
		}

			
		
		$edit_html = '<a href="product_flow_form.php?act=edit&id='.$editid.'" title="edit" data-toggle="tooltip" class="btn btn-info btn-sm"> <i class="fa fa-edit"></i> </a>';      
		       
		//del 
	    $delurl = "product_flow_actions.php?Id=$editid&action=del";

		$del_html = '<a href="javascript:void(0);" title="delete" data-toggle="tooltip" class="btn btn-danger btn-sm" onClick="javascript:funStats_purchase(this, \''.$delurl.'\')"><i class="fa fa-times"></i></a>';	     
				
		

		if(trim($res_modm_prm['EditPrm'])=="1") {
			$edit_html = $edit_html;
		  }else{
			$edit_html = "";			
		}
		 
		if(trim($res_modm_prm['DeletePrm'])=="1") {
			$del_html = $del_html;
		}else{
			$del_html = "";
		}			

		$flow = "";
		$cnd = "";
		
			//product flow details 
			if ($rs['p_flow'] == '1') {
				$flow = "Inward";
				$cnd = "Debit"; // Example value for '1'
			} else if ($rs['p_flow'] == '2') {
				$flow = "Outward";
				$cnd = "Credit"; // Example value for '2'
			}
		//get product count lists 		
		$pdt_sku_cnt = get_purchase_pdt_cnt_lists($db,$rs['p_invoice_no']);	
					
		
		$nestedData[]=$s_no++;
		$nestedData[]=$rs['disp_inv_date'];
		$nestedData[]=$rs['sup_name']. '</br><span style="color:green; font-size:12px">'.$rs['sup_gstno'].'</span>';
		$nestedData[] = $rs['sup_city'].'</br>'.$rs['sup_state'].'</br>'.$rs['sup_postcode']; 
		
		$nestedData[]=$rs['product_name'];
		$nestedData[]=$flow;
		$nestedData[]=$rs['qty_grm'];
		$nestedData[]=$cnd;
		$nestedData[] = $incstat;					
			
		$nestedData[] =  $edit_html.'&nbsp;'.$del_html;
		$nestedData[]=$rs['sup_name'];
		$nestedData[] = $rs['sup_gstno'];
		$nestedData[] = $rs['sup_city'];
		$nestedData[] = $rs['sup_state'];
		$nestedData[] = $rs['sup_postcode'];
		
		$data[] = $nestedData;
	}	

}

else{
	echo "No-Data";
}

$json_data = array(
				"draw"            => intval( $requestData['draw'] ),   // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw. 
				"recordsTotal"    => intval( $totalData ),  // total number of records
				"recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
				"data"            => $data   // total data array			
);	

echo json_encode($json_data);  // send data as json format

?>