<?php 
include 'session.php';
extract($_REQUEST);
$act=$action;


switch($act)
{		
	case 'get_product_det_by_pdtsku':
		if(isset($_REQUEST['product_sku']) && !empty($_REQUEST['product_sku'])){
			$pdt_prev_img='NoImageAvailable.png';			
			$rslt_pdt_det = $db->get_a_line("select * from t_purchase_entry_details where p_invoice_det_id='".$_REQUEST['pdt_invDet_id']."' ");
			
			if (!empty($rslt_pdt_det['upload_img'])) { 
				if(file_exists(CAAROOT_DIR."/uploads/product_image/".$rslt_pdt_det['upload_img']))
				{
					$pdt_prev_img = $rslt_pdt_det['upload_img'];	
				}											
			}
			//image url	
			$img_url =BASE_URL.'uploads/product_image/'.$pdt_prev_img;

			$rslt_sales_det = $db->get_a_line("select * from t_sales_entry_details where pdt_sku='".$_REQUEST['product_sku']."' ");
			$pdt_sales_det = $db-> get_a_line("select stock_status from t_purchase_entry_details where pdt_sku='".$_REQUEST['product_sku']."' AND IsActive = '1'  ");
			$supplier_det = $db->get_a_line("SELECT sup_name FROM m_supplier WHERE sup_id IN ( SELECT sup_id FROM t_purchase_entry_main WHERE p_invoice_no IN ( SELECT p_invoice_no FROM t_purchase_entry_details WHERE pdt_sku = '".$_REQUEST['product_sku']."' AND IsActive = '1' ) AND financial_id IN ( SELECT financial_id FROM t_purchase_entry_details WHERE pdt_sku = '".$_REQUEST['product_sku']."' AND IsActive = '1' ) ) LIMIT 0, 25;
			");
			$sup_name = $supplier_det['sup_name'];
			$stock_status = $pdt_sales_det['stock_status'];

			if(($stock_status )== 2) $sa = 'Sold';

			// if(!empty($rslt_sales_det)) $sa = 'Sold';
			else $sa = 'Available';
						
			echo json_encode(array("rslt"=>"1", "pdt_desc"=>$rslt_pdt_det['saree_desc'], "pdt_img_url"=>$img_url, "pdt_price"=>$rslt_pdt_det['purchase_rate'],'pdt_sold' => $sa, 'sup_name'=>$sup_name));
		}
		else{
			echo json_encode(array("rslt"=>"-1")); // error
		}
		exit();
	break;	

	case 'get_product_det_by_purchase' :
		$rslt_pdt_list = $db->get_rsltset("select * from t_purchase_entry_details where 1=1 and IsActive=1 and p_invoice_no='".$_REQUEST['pdt_inv_no']."' ");
		$html = "<table style='border:1px solid #eceeef; margin:5px;'>";
		if(count($rslt_pdt_list) > 0) {
			foreach($rslt_pdt_list as $r){
				$pdt_prev_img='NoImage.png';			
					if($r['upload_img'] != '' && file_exists(CAAROOT_DIR."/uploads/product_image/".$r['upload_img']))
					{
						$pdt_prev_img = $r['upload_img'];	
					}														
				$html .= "<tr ><td style='padding:10px;'>".$r['pdt_sku']."</td><td style='padding:10px;'>".$r['saree_desc']."</td>";
				$html .= '<td style="padding:10px;"><img src="'.BASE_URL.'uploads/product_image/'.$pdt_prev_img.'" width="50px" height="50px" align="absmiddle"/>	</td>';
				$html .='<td style="padding:10px;">'.$r['purchase_rate'].'</td>';
				$html .="</tr>";
			}
		}else $html .="<tr>No Product Found</tr>";

		$html .= "</table>";
		echo $html;
	break;
	
	case 'get_supplier_det_by_sup_id':
				
		if(isset($_REQUEST['supplier_id']) && !empty($_REQUEST['supplier_id'])){
			$rslt_sup_det = $db->get_a_line("select * from m_supplier where sup_id='".$_REQUEST['supplier_id']."' ");

									
			echo json_encode(array("rslt"=>"1",
			"sup_state"=>$rslt_sup_det['sup_state'],
			"sup_city"=>$rslt_sup_det['sup_city'],
			"sup_address" => $rslt_sup_det['sup_address'],
			"sup_gstno" => $rslt_sup_det['sup_gstno'],
			"sup_postcode" => $rslt_sup_det['sup_postcode'],
			"sup_type" =>$rslt_sup_det['sup_type']
			));
		}
		else{
			echo json_encode(array("rslt"=>"-1")); // error
		}
		exit();
	break;
	
	case 'get_customer_det_by_cus_id':
				
		if(isset($_REQUEST['customer_id']) && !empty($_REQUEST['customer_id'])){
			$rslt_cus_det = $db->get_a_line("select * from m_customer where cus_id='".$_REQUEST['customer_id']."' ");
									
			echo json_encode(array("rslt"=>"1",
			"cus_address"=>$rslt_cus_det['cus_address'],
			"cus_city"=>$rslt_cus_det['cus_city'],
			 "cus_state"=>$rslt_cus_det['cus_state'],
			 "cus_postcode"=>$rslt_cus_det['cus_postcode'],
			 "customer_gst"=>$rslt_cus_det['cus_gstno']));
		}
		else{
			echo json_encode(array("rslt"=>"-1")); // error
		}
		exit();
	break;

	case 'get_pdt_type_qty':
				
		if(isset($_REQUEST['product_type']) && !empty($_REQUEST['product_type']))
		{
			$rslt_pdt_det = $db->get_a_line("SELECT SUM(qty_grm) AS pdt_grams from t_product_entry_details where pdt_type ='".$_REQUEST['product_type']."' and stock_status = 0  and IsActive = 1 and financial_id = '".$financial_id."'  ");
									
			$rslt_pdt_flow = $db->get_a_line(
				("SELECT SUM(qty_grm) AS pdt_grams FROM t_product_flow_details WHERE pdt_type = '".$_REQUEST['product_type']."' and IsActive = 1 and financial_id = '".$financial_id."' and p_flow = 1 ") -
				("SELECT SUM(qty_grm) AS pdt_grams FROM t_product_flow_details WHERE pdt_type = '".$_REQUEST['product_type']."' and IsActive = 1 and financial_id = '".$financial_id."' and p_flow = 2 ")

			);
			$pdt_total = $rslt_pdt_det['pdt_grams'] + $rslt_pdt_flow['pdt_grams'];

			echo json_encode(array("rslt"=>"1", "pdt_qty"=>$pdt_total));
		}
		else{
			echo json_encode(array("rslt"=>"-1")); // error
		}
		exit();
	break;

	
	case 'get_inv_no_by_company_id':
		$rslt_data='';
		
		if(isset($company_id) && !empty($company_id) && !empty($financial_id)){			
			$res_AI = $db->get_a_line("SELECT IFNULL(MAX(`actu_inv_no`), 0) + 1 as disp_inv_no FROM t_purchase_entry_main where 1=1 and company_id='".$company_id."' and financial_id = '".$financial_id."'");				
			$rslt_data = $res_AI['disp_inv_no'];

			$res_pe = $db->get_a_line("SELECT * FROM t_purchase_entry_details as t left join t_purchase_entry_main as t1 on t.p_invoice_no = t1.p_invoice_no  WHERE t1.company_id = '".$company_id."' and t.financial_id = '".$financial_id."' and pdt_sku != '' order by p_invoice_det_id desc");				
			$rslt_data_sku = $res_pe['pdt_sku'];
			if($rslt_data_sku == ""){
				if($company_id == '2' && $financial_id == '3')
					$rslt_data_sku = 'PB20-000';
				else
					$rslt_data_sku = 'HM20-000';	
			}
			
							
		}else if(!isset($financial_id)){
			$res_AI = $db->get_a_line("SELECT IFNULL(MAX(`actu_inv_no`), 0) + 1 as disp_inv_no FROM t_purchase_entry_main where 1=1 and company_id='".$company_id."'");				
			$rslt_data = $res_AI['disp_inv_no'];	
		}
		
		echo json_encode(array("rslt"=>$rslt_data,"pdt_sku"=>$rslt_data_sku)); //success
		exit();
	break;

	case 'get_inv_no_by_supplier_id':
		$rslt_data='';
		
		if(isset($supplier_id) && !empty($supplier_id) && !empty($financial_id)){			
			$res_AI = $db->get_a_line("SELECT IFNULL(MAX(`actu_inv_no`), 0) + 1 as disp_inv_no FROM t_product_entry_main where 1=1 and sup_id='".$supplier_id."' and financial_id = '".$financial_id."'");				
			$rslt_data = $res_AI['disp_inv_no'];

			// $res_pe = $db->get_a_line("SELECT * FROM t_product_entry_details as t left join t_product_entry_main as t1 on t.p_invoice_no = t1.p_invoice_no  WHERE t1.sup_id = '".$supplier_id."' and t.financial_id = '".$financial_id."' and pdt_sku != '' order by p_invoice_det_id desc");				
			// $rslt_data_sku = $res_pe['pdt_sku'];
			// if($rslt_data_sku == ""){
			// 	if($supplier_id == '2' && $financial_id == '3')
			// 		$rslt_data_sku = 'PB20-000';
			// 	else
			// 		$rslt_data_sku = 'HM20-000';	
			// }
			
							
		}else if(!isset($financial_id)){
			$res_AI = $db->get_a_line("SELECT IFNULL(MAX(`actu_inv_no`), 0) + 1 as disp_inv_no FROM t_product_entry_main where 1=1 and supplier_id='".$supplier_id."'");				
			$rslt_data = $res_AI['disp_inv_no'];	
		}
		
		echo json_encode(array("rslt"=>$rslt_data)); //success
		exit();
	break;

	case 'get_bill_no_by_company_id':
		$rslt_data='';
	
		if(isset($company_id) && !empty($company_id) && !empty($financial_id)){	
			
			$res_AI = $db->get_a_line("SELECT IFNULL(MAX(`actu_bill_no`), 0) + 1 as disp_inv_no FROM t_sales_entry_main where 1=1 and company_id='".$company_id."' and financial_id = '".$financial_id."' ");				
			$rslt_data = $res_AI['disp_inv_no'];				
		}else if(!isset($financial_id)){
			$res_AI = $db->get_a_line("SELECT IFNULL(MAX(`actu_bill_no`), 0) + 1 as disp_inv_no FROM t_sales_entry_main where 1=1 and company_id='".$company_id."' ");				
			$rslt_data = $res_AI['disp_inv_no'];	
		}
		
		echo json_encode(array("rslt"=>$rslt_data)); //success
		exit; 
		
	break;
	
	case 'get_bill_no_by_company_id_return':
		$rslt_data = '';
		// print_r('hi');
	
		if (isset($company_id) && !empty($company_id) && !empty($financial_id)) {
	
			$companyRow = $db->get_row("SELECT company_name FROM m_company WHERE company_id='" . $company_id . "'");
			
			$company_name = $companyRow->company_name;
			// print_r($company_name);
			$company_without_dots = preg_replace('/[^a-zA-Z]/', '', $company_name);
			$comp = substr($company_without_dots, 0, 2);
	
			$res_AI = $db->get_a_line("SELECT IFNULL(MAX(`r_bill_no`), 0) + 1 as disp_inv_no FROM t_return_entry_main where  company_id='" . $company_id . "' and financial_id = '" . $financial_id . "'");
			$formattedBillNumber = str_pad($res_AI['disp_inv_no'], 3, '0', STR_PAD_LEFT);
			$invoice_id = $comp.'-' .'SR'. '-' . $formattedBillNumber;
		
		} else if (!isset($financial_id)) {
			$res_AI = $db->get_a_line("SELECT IFNULL(MAX(`r_bill_no`), 0) + 1 as disp_inv_no FROM t_return_entry_main where  company_id='" . $company_id . "'");
			$formattedBillNumber = str_pad($res_AI['disp_inv_no'], 3, '0', STR_PAD_LEFT);
			$invoice_id = $comp.'-' . $formattedBillNumber;
		}
	
		echo json_encode(array("rslt" => $invoice_id)); //success
		exit;
	
		break;


	case 'get_purchase_id_return':
		$rslt_data = '';
		// print_r('hi');	
	
		if (isset($company_id) && !empty($company_id) && !empty($financial_id)) {
	
			$companyRow = $db->get_row("SELECT company_name FROM m_company WHERE company_id='" . $company_id . "'");
			
			$company_name = $companyRow->company_name;
			// print_r($company_name);
			$company_without_dots = preg_replace('/[^a-zA-Z]/', '', $company_name);
			$comp = substr($company_without_dots, 0, 2);
	
			$res_AI = $db->get_a_line("SELECT IFNULL(MAX(`r_bill_no`), 0) + 1 as disp_inv_no FROM t_pur_return_entry_main where  company_id='" . $company_id . "' and financial_id = '" . $financial_id . "'");
			$formattedBillNumber = str_pad($res_AI['disp_inv_no'], 3, '0', STR_PAD_LEFT);
			$p_invoice_id = $comp.'-' .'PR'. '-' . $formattedBillNumber;
		
		} else if (!isset($financial_id)) {
			$res_AI = $db->get_a_line("SELECT IFNULL(MAX(`r_bill_no`), 0) + 1 as disp_inv_no FROM t_pur_return_entry_main where  company_id='" . $company_id . "'");
			$formattedBillNumber = str_pad($res_AI['disp_inv_no'], 3, '0', STR_PAD_LEFT);
			$p_invoice_id = $comp.'-' . $formattedBillNumber;
		}
	
		echo json_encode(array("rslt" => $p_invoice_id)); //success
		exit;
	
		break;

	case 'get_bill_no_by_company_id_payment':
		$rslt_data = '';
		
		$responseData = array();
		if (isset($company_id) && !empty($company_id) && !empty($financial_id)) {

				$customerRow = $db->get_row("SELECT cus_id, cus_name,cus_city,cus_state,cus_gstno,cus_postcode FROM m_customer WHERE cus_id = '".$customer_id."'");

				$companyRow = $db->get_a_line("SELECT * FROM m_company WHERE company_id='".$company_id."'");
				$sql = "SELECT * FROM t_sales_entry_main WHERE company_id='".$company_id."' AND cus_id='".$customer_id."' AND financial_id = '".$financial_id."' AND IsActive=1";
					// echo "SQL Query: " . $sql . "<br>";
					// echo "Company ID: " . $company_id . "<br>";
					// echo "Customer ID: " . $customer_id . "<br>";
					//  echo "Customer ID: " . $payment_status . "<br>";
					//  echo "Customer ID: " . $financial_id . "<br>";
					//  exit;

					$main_details = $db->get_rsltset($sql);
								// Assuming $main_details is an array of results
					foreach ($main_details as $main_detail) {
						$bill_no = $main_detail['s_bill_no']; 
						$financial_id = $main_detail['financial_id']; 
						$actu_bill_no = $main_detail['actu_bill_no']; 
						$return_sql = "SELECT SUM(final_sale_amt) as total_return_amt FROM t_return_entry_main WHERE actu_bill_no='".$actu_bill_no."' AND financial_id='".$financial_id."' AND company_id='".$company_id."' AND cus_id='".$customer_id."'  AND IsActive=1";
						$paid_sql = "SELECT SUM(paid_amt) as total_paid_amt FROM t_payment_details WHERE s_bill_no='".$actu_bill_no."' AND 
						financial=( SELECT CONCAT(YEAR(f_start_date), ' - ', YEAR(f_end_date)) AS financial_year FROM m_financial_year WHERE financial_id='" . $financial_id . "') AND company =( SELECT company_name FROM m_company WHERE company_id='" . $company_id . "' )   AND IsActive=1";

						$paid_result = $db->get_row($paid_sql);
						if ($paid_result && $paid_result->total_paid_amt != null) {
							$total_paid_amt = $paid_result->total_paid_amt;
						} else {
							
							$total_paid_amt = "0.00"; 
						}


						$return_result = $db->get_row($return_sql);
						if ($return_result && $return_result->total_return_amt !== null) {
							$total_return_amt = $return_result->total_return_amt;
						} else {
							
							$total_return_amt = "0.00"; 
						}

						$financial_year = $db->get_a_line("SELECT financial_id AS Id, CONCAT(YEAR(f_start_date), ' - ', YEAR(f_end_date)) AS financial_year FROM m_financial_year WHERE financial_id='" . $financial_id . "'");
						$customerRow = $db->get_row("SELECT cus_id, cus_name,cus_city,cus_state,cus_gstno,cus_postcode FROM m_customer WHERE cus_id='" . $customer_id . "'");

						$companyRow = $db->get_a_line("SELECT * FROM m_company WHERE company_id='" . $company_id . "'");
						$sql = $db->get_a_line("SELECT * FROM t_sales_entry_main WHERE  s_bill_no='" . $bill_no . "' AND IsActive=1");
						

										
// echo $bill_status;
						$bill_number = $db->get_a_line("SELECT s_bill_no from t_sales_entry_main where actu_bill_no='" . $actu_bill_no . "' AND financial_id='" . $financial_id . "' AND company_id='" . $company_id . "' AND  cus_id='" . $customer_id . "'");
						// print_r( $bill_number);
						$s_bill_no = $bill_number['s_bill_no'];

						if($bill_status == '3'){
							$bill_payment = $db->get_row("SELECT * FROM t_sales_payment WHERE s_bill_no='" . $s_bill_no . "'  AND IsActive=1 ");
						}
						else {
						$bill_payment = $db->get_row("SELECT * FROM t_sales_payment WHERE s_bill_no='" . $s_bill_no . "'AND payment_status_id ='".$bill_status."'  AND IsActive=1 ");
						}
						// print_r($bill_payment);
						// exit;

						if ($bill_payment && $companyRow ) {
							$bill_amount = 0.00;
						
							if ($bill_payment->payment_status_id === '2') {
							
								$bill_amount = $sql['final_sale_amt'] - $total_paid_amt;

							} else if ($bill_payment->payment_status_id === '1') {
								
								$bill_amount = $sql['final_sale_amt'] - $total_return_amt - $total_paid_amt ;
							}
							$formatted_bill_amount = number_format($bill_amount, 2);
							$cleaned_bill_amount = str_replace(',', '', $formatted_bill_amount);
							// print_r($bill_amount);
							$responseData[] = array(
								's_payment_id' => $bill_payment->s_payment_id, 
								's_bill_no' => $actu_bill_no, 
								'bill_status' => $bill_payment->payment_status_id, 
								'companyName' => $companyRow['company_name'],
								'financial_year' => $financial_year['financial_year'],
								'customerName' => $customerRow->cus_name,
								'tot_sale_amt' => $sql['total_sale_amount'], 
								'discount' => $sql['after_discount_amt'], 
								'tot_tax_amt' => $sql['tot_tax_amt'], 
								'final_sale_amt' => $sql['final_sale_amt'], 
								'billDate' => $sql['s_bill_date'],															
								'return_amt' => $total_return_amt, 
								'paid_amt' => $total_paid_amt,
								'bill_amount' => $cleaned_bill_amount,

							);
							
						

						} else {
							// echo "No payment details found for s_bill_no: " . $bill_no . "<br>";
						}
					}
		
		}
	
		echo json_encode($responseData); //success
		exit;
	
		break;

	case 'get_purchase_payment':
		$rslt_data = '';
		
		$responseData = array();
		if (isset($company_id) && !empty($company_id) && !empty($financial_id)) {

				$supplierRow = $db->get_row("SELECT sup_id, sup_name,sup_city,sup_state,sup_gstno,sup_postcode FROM m_supplier WHERE sup_id = '".$supplier_id."'");

				$companyRow = $db->get_a_line("SELECT * FROM m_company WHERE company_id='".$company_id."'");
				$sql = "SELECT * FROM t_purchase_entry_main WHERE company_id='".$company_id."' AND sup_id='".$supplier_id."' AND financial_id = '".$financial_id."' AND IsActive=1";
					// echo "SQL Query: " . $sql . "<br>";
					// echo "Company ID: " . $company_id . "<br>";
					// echo "Customer ID: " . $customer_id . "<br>";
					//  echo "Customer ID: " . $payment_status . "<br>";
					//  echo "Customer ID: " . $financial_id . "<br>";
					//  exit;

					$main_details = $db->get_rsltset($sql);
								// Assuming $main_details is an array of results
					foreach ($main_details as $main_detail) {
						$bill_no = $main_detail['p_invoice_no']; 
						$financial_id = $main_detail['financial_id']; 
						$actu_inv_no = $main_detail['actu_inv_no']; 
						$return_sql = "SELECT SUM(final_pur_amt) as total_return_amt FROM t_pur_return_entry_main WHERE actu_pur_bill_no='".$actu_inv_no."' AND financial_id='".$financial_id."' AND company_id='".$company_id."' AND sup_id='".$supplier_id."'  AND IsActive=1";

						$paid_sql = "SELECT SUM(tot_paid_amt) as total_paid_amt FROM t_purchase_payment WHERE p_bill_no='".$actu_inv_no."' AND 
						financial_id=( SELECT CONCAT(YEAR(f_start_date), ' - ', YEAR(f_end_date)) AS financial_year FROM m_financial_year WHERE financial_id='" . $financial_id . "') AND company =( SELECT company_name FROM m_company WHERE company_id='" . $company_id . "' )   AND IsActive=1";
// echo "Paid SQL: " . $paid_sql . "<br>";
// echo "Return SQL: " . $return_sql . "<br>";
// exit();
						$paid_result = $db->get_row($paid_sql);
						if ($paid_result && $paid_result->total_paid_amt != null) {
							$total_paid_amt = $paid_result->total_paid_amt;
						} else {
							
							$total_paid_amt = "0.00"; 
						}


						$return_result = $db->get_row($return_sql);
						if ($return_result && $return_result->total_return_amt !== null) {
							$total_return_amt = $return_result->total_return_amt;
						} else {
							
							$total_return_amt = "0.00"; 
						}

						$financial_year = $db->get_a_line("SELECT financial_id AS Id, CONCAT(YEAR(f_start_date), ' - ', YEAR(f_end_date)) AS financial_year FROM m_financial_year WHERE financial_id='" . $financial_id . "'");
						$supplierRow = $db->get_row("SELECT sup_id, sup_name,sup_city,sup_state,sup_gstno,sup_postcode FROM m_supplier WHERE sup_id='" . $supplier_id . "'");

						$companyRow = $db->get_a_line("SELECT * FROM m_company WHERE company_id='" . $company_id . "'");
						$sql = $db->get_a_line("SELECT * FROM t_purchase_entry_main WHERE  p_invoice_no='" . $bill_no . "' AND IsActive=1");
						

// echo $bill_status;
						$bill_number = $db->get_a_line("SELECT p_invoice_no from t_purchase_entry_main where actu_inv_no='" . $actu_inv_no . "' AND financial_id='" . $financial_id . "' AND company_id='" . $company_id . "' AND  sup_id='" . $supplier_id . "'");
						// print_r( $bill_number);
						$p_invoice_no = $bill_number['p_invoice_no'];

						if($bill_status == '3'){
							$bill_payment = $db->get_row("SELECT * FROM t_purchase_payment WHERE p_bill_no='" . $p_invoice_no . "'  AND IsActive=1 ");
						}
						else {
						$bill_payment = $db->get_row("SELECT * FROM t_purchase_payment WHERE p_bill_no='" . $p_invoice_no . "'AND payment_status_id ='".$bill_status."'  AND IsActive=1 ");
						}
						// print_r($bill_payment);
						// exit;

						if ($bill_payment && $companyRow ) {
							$bill_amount = 0.00;
						
							if ($bill_payment->payment_status_id === '2') {
							
								$bill_amount = $sql['final_pur_amt'] - $total_paid_amt;

							} else if ($bill_payment->payment_status_id === '1') {
								
								$bill_amount = $sql['final_pur_amt'] - $total_return_amt - $total_paid_amt ;
							}
							$formatted_bill_amount = number_format($bill_amount, 2);
							$cleaned_bill_amount = str_replace(',', '', $formatted_bill_amount);
							// print_r($bill_amount);
							$responseData[] = array(
								's_payment_id' => $bill_payment->s_payment_id, 
								'p_invoice_no' => $actu_inv_no, 
								'bill_status' => $bill_payment->payment_status_id, 
								'companyName' => $companyRow['company_name'],
								'financial_year' => $financial_year['financial_year'],
								'supplierName' => $supplierRow->sup_name,
								'tot_sale_amt' => $sql['total_sale_amount'], 
								'discount' => $sql['after_discount_amt'], 
								'tot_tax_amt' => $sql['tot_tax_amt'], 
								'final_pur_amt' => $sql['final_pur_amt'], 
								'billDate' => $sql['s_bill_date'],															
								'return_amt' => $total_return_amt, 
								'paid_amt' => $total_paid_amt,
								'bill_amount' => $cleaned_bill_amount,

							);
							
						

						} else {
							// echo "No payment details found for s_bill_no: " . $bill_no . "<br>";
						}
					}
		
		}
	
		echo json_encode($responseData); //success
		exit;
	
		break;

case 'get_customer_report':

		$rslt_data = '';
		$responseData = array();
		if (isset($company_id) && !empty($company_id) ) {

				$customerRow = $db->get_row("SELECT cus_id, cus_name,cus_city,cus_state,cus_gstno,cus_postcode FROM m_customer WHERE cus_id='" . $customer_id . "'");

				$companyRow = $db->get_row("SELECT company_name FROM m_company WHERE company_id='" . $company_id . "'");
				$sales = "SELECT * FROM t_sales_entry_main WHERE company_id='" . $company_id . "' AND cus_id='" . $customer_id . "' AND financial_id='" . $financial_id . "' AND IsActive=1";
					// echo 'hi';

				$main_details = $db->get_rsltset($sales);
				foreach ($main_details as $main_detail) {
					$bill_no = $main_detail['s_bill_no']; 
					$financial_id = $main_detail['financial_id']; 
					$actu_bill_no = $main_detail['actu_bill_no'];
					// print_r($actu_bill_no);

					$return = $db->get_a_line("SELECT * FROM t_return_entry_main WHERE actu_bill_no='" . $actu_bill_no . "' AND cus_id='" . $customer_id . "' AND financial_id='" . $financial_id . "' AND IsActive=1");

					$payment =  $db->get_a_line("SELECT * FROM t_payment_details WHERE s_bill_no = '".$actu_bill_no."' AND IsActive=1");

					// print_r($return);
					// print_r($companyRow);

					$responseData[] = [
						'customer_name' => $customerRow->cus_name,
						'company_name' => $companyRow->company_name,
						'bill_no' => $main_detail['actu_bill_no'],
						'sales_entry' => $main_detail['final_sale_amt'],
						'sales_date' => $main_detail['createddate'],
						'return_date' => $return['createddate'],
						'return_entry' => $return['final_sale_amt'],
						'payment_amount' =>$payment['paid_amt'],
						// 'payment_info' =>$payment['payment_status_id'],
						'payment_date' =>$payment['createddate'],
					];

				}

				
// print_r($customerRow);
				

		}


		echo json_encode($responseData); //success
		exit;
		break;

	
	case 'get_details_by_bill_number':
		$rslt_data = array();
		
		if (isset($_POST['bill_number']) && !empty($_POST['bill_number'])) {
			$billNumber = $_POST['bill_number'];
			
			$main_details = $db->get_row("SELECT * FROM t_sales_entry_main WHERE s_bill_no='" . base64_decode($billNumber) . "' AND IsActive=1");
			$details_list = $db->get_rsltset("SELECT * FROM t_sales_entry_details WHERE s_bill_no='" . base64_decode($billNumber) . "' AND IsActive=1");

			if ($main_details) {
				$rslt_data = array(
					'rslt' => '1',
					'companyName' => $main_details['company_name'],
					'customerName' => $main_details['customer_name'],
					'billDate' => $main_details['s_bill_date'],
					'billType' => $main_details['bill_type'],
					'products' => $details_list,
				);
			} else {
				$rslt_data = array(
					'rslt' => '-1', // No data found
				);
			}
		} else {
			$rslt_data = array(
				'rslt' => '-1', // Invalid input
			);
		}

		echo json_encode($rslt_data);
		exit;
		break;
	
}


?>
<?php
if (isset($_GET['bill_number']) && isset($_GET['return']) != 'purchase') {
$billNumber = $_GET['bill_number'];
$financial_id = $_GET['financial_id'];
$company_id = $_GET['company_id'];
 $company_name = $_GET['company_name'];

// exit;


 $row = $db->get_row("SELECT * FROM t_sales_entry_main WHERE actu_bill_no='" . $billNumber . "' AND company_id='" . $company_id . "' AND financial_id='" . $financial_id . "'");

 $product_bill_id = $row->s_bill_no;
 $product_date = date('Y', strtotime($row->s_bill_date));

if ($row )
 {
		$customerRow = $db->get_row("SELECT cus_id, cus_name,cus_city,cus_state,cus_gstno,cus_postcode FROM m_customer WHERE cus_id='" . $row->cus_id . "'");
	$companyRow = $db->get_row("SELECT company_name FROM m_company WHERE company_id='" . $row->company_id . "'");
	$productDetails = $db->get_results("SELECT * FROM t_sales_entry_details WHERE s_bill_no='" . $product_bill_id . "'");
// 	$lastRBillNo = $db->get_var("SELECT MAX(r_bill_no) FROM t_return_entry_main");


// $newRBillNo = $lastRBillNo + 1;

// 	$company_without_dots =  preg_replace('/[^a-zA-Z]/', '', $company_name);
	
// 	$comp= substr($company_without_dots, 0, 2);
	// $formattedBillNumber = str_pad($newRBillNo, 3, '0', STR_PAD_LEFT);

	// $invoice_id =$product_date.'-'.$comp.'-'.$formattedBillNumber ;
	// $pdt_sku ="SELECT invoice_id FROM t_return_entry_main WHERE invoice_id='".$invoice_id."'";
// $result = $db->get_a_line($pdt_sku);
	
	$response = [
		'success' => true,
		'data' => [
			'bill_date' => $row->s_bill_date,
			'bill_number' => $row->actu_bill_no,
			// 'invoice_id' => $invoice_id ,
			'discount_per' => $row->discount_per,
			'cgst' => $row->cgst_per,
			'sgst' => $row->sgst_per,
			'igst' => $row->igst_per,
			'customer_id' => $customerRow->cus_id,
			'customer_name' => $customerRow->cus_name,
			'customer_city' => $customerRow->cus_city,
			'customer_state' => $customerRow->cus_state,
			'customer_gst' => $customerRow->cus_gstno,
			'customer_pin' => $customerRow->cus_postcode,
			'company_name' => $companyRow->company_name,
			'notes' => $row->notes,
			'product_details' => []
		]
	];
foreach ($productDetails as $product) {
	$product_sku = $product->pdt_sku;
	// echo "Product SKU: " . $product_sku.'<br>'; // Echo the product SKU

	// Retrieve the corresponding status from t_purchase_entry_details
	$status = $db->get_row("SELECT stock_status FROM t_purchase_entry_details WHERE pdt_sku='" . $product_sku . "' AND IsActive = '1'");
        
			$status_text = ($status->stock_status == 0) ? 'Returned' : 'Sold';
			// print_r($status_text);
			// exit();
            $response['data']['product_details'][] = [
                'p_bill_det_id' => $product->p_invoice_det_id,
                'pdt_sku' => $product->pdt_sku,
                'saree_desc' => $product->saree_desc,
                'pdt_img' => $product->pdt_img,
                'purchase_price' => $product->purchase_price,
                'sale_price' => $product->sale_price,
                'pdt_discount_percent' => $product->pdt_discount_percent,
                'pdt_discount_amt' => $product->pdt_discount_amt,
                'tot_amount' => $product->tot_amount,
                'status' => $status_text,
            ];
}
	
	
	
			
	
	
	
} else {
	$response = [
		'success' => true,
		'data' => [
			'bill_date' => '',
			'customer_name' => '',
			'customer_city' => '',
			'company_name' => '',
			'notes' => '',
		],
		'message' => 'Bill not found'
	];
}
} 

else if (isset($_GET['bill_number']) && isset($_GET['return']) == 'purchase') {
$billNumber = $_GET['bill_number'];
$financial_id = $_GET['financial_id'];
$company_id = $_GET['company_id'];
 $return = $_GET['return'];

// exit;


 $row = $db->get_row("SELECT * FROM t_purchase_entry_main WHERE actu_inv_no='" . $billNumber . "' AND company_id='" . $company_id . "' AND financial_id='" . $financial_id . "'");

 $product_bill_id = $row->p_invoice_no;
 $product_date = date('Y', strtotime($row->p_invoice_date));

if ($row )
 {
		$supplierRow = $db->get_row("SELECT sup_id, sup_name,sup_city,sup_state,sup_gstno,sup_postcode FROM m_supplier WHERE sup_id='" . $row->sup_id . "'");
	$companyRow = $db->get_row("SELECT company_name FROM m_company WHERE company_id='" . $row->company_id . "'");
	$productDetails = $db->get_results("SELECT * FROM t_purchase_entry_details WHERE p_invoice_no='" . $product_bill_id . "'");

	
	$response = [
		'success' => true,
		'data' => [
			'bill_date' => $row->p_invoice_date,
			'bill_number' => $row->actu_inv_no,
			'discount_per' => $row->discount_per,
			'cgst' => $row->cgst_per,
			'sgst' => $row->sgst_per,
			'igst' => $row->igst_per,
			'supplier_id' => $supplierRow->sup_id,
			'supplier_name' => $supplierRow->sup_name,
			'supplier_city' => $supplierRow->sup_city,
			'supplier_state' => $supplierRow->sup_state,
			'supplier_gst' => $supplierRow->sup_gstno,
			'supplier_pin' => $supplierRow->sup_postcode,
			'company_name' => $companyRow->company_name,
			'notes' => $row->notes,
			'product_details' => []
		]
	];
foreach ($productDetails as $product) {
	$product_sku = $product->pdt_sku;
	// echo "Product SKU: " . $product_sku.'<br>'; // Echo the product SKU

	// Retrieve the corresponding status from t_purchase_entry_details
	$status = $db->get_row("SELECT stock_status FROM t_purchase_entry_details WHERE pdt_sku='" . $product_sku . "' AND IsActive = '1'");
        
	if($status->stock_status == 0){
		$status_text = 'Available';
	}
	else if($status->stock_status == 2){
		$status_text = 'Sold';
	}
	else if($status->stock_status == 3){
		$status_text = 'Returned';
	}
			 
			// print_r($status_text);
			// exit();
            $response['data']['product_details'][] = [
                's_bill_det_id' => $product->s_bill_det_id,
                'pdt_sku' => $product->pdt_sku,
                'saree_desc' => $product->saree_desc,
                'pdt_img' => $product->upload_img,
                'purchase_price' => $product->purchase_rate,
                'pdt_discount_percent' => $product->pdt_discount_percent,
                'pdt_discount_amt' => $product->pdt_discount_amt,
                'tot_amount' => $product->tot_amount,
                'status' => $status_text,
            ];
		}
	
} else {
	$response = [
		'success' => true,
		'data' => [
			'bill_date' => '',
			'customer_name' => '',
			'customer_city' => '',
			'company_name' => '',
			'notes' => '',
		],
		'message' => 'Bill not found'
	];
}
} else {
$response = [
	'success' => false,
	'message' => 'Invalid input'
];
}

// Send the response as JSON
header('Content-Type: application/json');
echo json_encode($response);
exit();
?>
<?php

if (isset($_POST['bill_no'])) {
    $billNo = $_POST['bill_no'];
	$row = $db->get_row("SELECT * FROM t_sales_entry_main WHERE actu_bill_no='" . $billNo . "' ");
    
    $taxDetails = array(
        'cgst' => $row->cgst_per,
        'sgst' => $row->sgst_per,
        'igst' => $row->igst_per,
    );

   
    echo json_encode($taxDetails);
} else {
    
    echo json_encode(array('error' => 'Bill number not provided.'));
}
exit();

?>
