<?php 
include 'session.php';
require_once('common/getname_functions.php');

include 'includes/image_thumb.php';
$obj=new Gthumb();	

extract($_REQUEST);
$act=$action;

$txt_inv_date_db = date('Y-m-d', strtotime($_POST['txt_inv_date']));
//$_SESSION["financial_id"]
switch($act)
{
	case 'insert':

		//check if company and invoice are already exists
		$str_is_purchase_sql = "select * from t_purchase_entry_main where financial_id='$financial_id' and company_id='$sel_company' and actu_inv_no='$txt_inv_no'";
		$res_is_purchase_res = $db->get_a_line($str_is_purchase_sql);
		if($res_is_purchase_res['p_invoice_no']!='') {
			echo json_encode(array("rslt"=>"3", "err_msg"=>"Purchase Record Already Exists!")); //deletion  
			exit;			
		}


	
		//Transaction purchase main details insert
		$str_insert_main="INSERT into t_purchase_entry_main(cgst_total, sgst_total, igst_total, actu_inv_no, p_invoice_date, financial_id, company_id, sup_id, tot_pur_amount, discount_per, after_discount_amt, cgst_per, sgst_per, igst_per, tot_tax_amt, final_pur_amt, IsActive, UserId, createddate) 
		values('".$txt_cgst_total."', '".$txt_sgst_total."', '".$txt_igst_total."', '".$txt_inv_no."', '".$txt_inv_date_db."', '".$financial_id."', '".$sel_company."', '".$sel_supplier."', '".$txt_tot_purchase_amt."','".$txt_cmn_discount_per."', '".$txt_after_discount_amt."', '".$txt_cgst."', '".$txt_sgst."', '".$txt_igst."', '".$txt_tax_amt."', '".$txt_final_purchase_amt."', '1', '".$_SESSION["UserId"]."', NOW())";
		
		$rslt = $db->insert($str_insert_main);	
		$Last_insert_id=$db->insert_id;
		
		//Transaction purchase details insert [product or category details insert]
		if(isset($Last_insert_id) && !empty($Last_insert_id)){
			$pdt_cnt = count($hdn_pdt_cnt);
			for($i=0; $i<$pdt_cnt; $i++){
				
				if(isset($txt_pdt_sku[$i]) && !empty($txt_pdt_sku[$i]))
				{				
					//product image upload
					$pdt_img_name='';
					if($_FILES["uploadimg_".$i]["name"] != "") {						
						$file_name = $_FILES['uploadimg_'.$i]['name']; // filename to get file's extension
						if (strlen($file_name)) {
							$extension = substr($file_name, strrpos($file_name, '.')+1);
							$pdt_img_name = md5(uniqid().time()).".".$extension;
							$tmp = $_FILES['uploadimg_'.$i]['tmp_name'];
							$upload_dir = CAAROOT_DIR."/uploads/product_image/";
							
							move_uploaded_file($tmp,$upload_dir.$pdt_img_name);				
						}
					}
					
					$str_insert_det="insert into t_purchase_entry_details(p_invoice_no, pdt_sku, saree_desc, upload_img, purchase_rate, pdt_discount_percent, pdt_discount_amt, tot_amount, IsActive, UserId, financial_id, createddate) values('".$Last_insert_id."', '".$txt_pdt_sku[$i]."', '".$txt_pdt_desc[$i]."', '".$pdt_img_name."', '".$txt_pdt_rate[$i]."', '".$txt_pdt_discount_per[$i]."',  '".$txt_pdt_discount_amt[$i]."', '".$txt_tot_amt[$i]."', '1', '".$_SESSION["UserId"]."', '".$_SESSION["Financial_id"]."', NOW())";
													
					$db->insert($str_insert_det);	
					
				}
				
			}			
			//payment details add
			$rslt_payment = $db->query("insert into t_sales_payment(s_bill_no, tot_payment_amt, tot_paid_amt, due_amt, financial_id, IsActive, UserId, createddate)values('".$Last_insert_id."', '".$txt_final_sale_amt."', '0.00', '".$txt_final_sale_amt."', '".$_SESSION["Financial_id"]."', '1', '".$_SESSION["UserId"]."', NOW())");
			
			//payment details add - START
			/*
			$sup_payment_type = get_supplier_payment_type($db, $sel_supplier); //1-GST 2-Non-GST
			$sv_pur_tot_amt=0;
			if($sup_payment_type == "1"){
				$sv_pur_tot_amt = $txt_final_purchase_amt; //gst means final purchase amt get
			}
			else{ 
				$sv_pur_tot_amt = $txt_tot_purchase_amt; //non-gst means total purchase amt get
			}
			
			$m_prev_bal_amt = $db->get_a_line("select p_payment_id, tot_payment_amt, due_amt from t_purchase_payment where sup_id='".$sel_supplier."' and company_id='".$sel_company."' order by p_payment_id DESC LIMIT 1 ");
			
			if(!empty($m_prev_bal_amt)){
				//update	
				$m_cur_tot_payment_amt = (float)$m_prev_bal_amt['tot_payment_amt'] + $sv_pur_tot_amt;
				$m_cur_due_amt = (float)$m_prev_bal_amt['due_amt'] + $sv_pur_tot_amt;
				
				$db->insert("update t_purchase_payment set tot_payment_amt='".$m_cur_tot_payment_amt."', due_amt='".$m_cur_due_amt."' where p_payment_id='".$m_prev_bal_amt['p_payment_id']."'  ");				
			}
			else{
				//insert
				$rslt_payment = $db->insert("insert into t_purchase_payment(sup_id, company_id, tot_payment_amt, tot_paid_amt, due_amt, UserId, createddate)values('".$sel_supplier."', '".$sel_company."', '".$sv_pur_tot_amt."', '0.00', '".$sv_pur_tot_amt."', '".$_SESSION["UserId"]."', NOW())");
			}
			*/
			//payment details add - END
		
		}
		
		echo json_encode(array("rslt"=>"1")); //success
	
	break;
	
	
	case 'update':	 	
	//$edit_id	

		//check if company and invoice are already exists
		// $str_is_purchase_sql = "select * from t_purchase_entry_main where financial_id='$financial_id' and company_id='$sel_company'";
		// $res_is_purchase_res = $db->get_a_line($str_is_purchase_sql);
		// if($res_is_purchase_res['p_invoice_no']!='') {
		// 	echo json_encode(array("rslt"=>"3", "err_msg"=>"Purchase Record Already Exists!")); //deletion  
		// 	exit;			
		// }		
										
		$str_update_main="UPDATE t_purchase_entry_main set cgst_total='".$txt_cgst_total."', sgst_total='".$txt_sgst_total."', igst_total='".$txt_igst_total."',financial_id='".$financial_id."',p_invoice_date='".$txt_inv_date_db."', company_id='".$sel_company."', sup_id='".$sel_supplier."', tot_pur_amount='".$txt_tot_purchase_amt."', discount_per='".$txt_cmn_discount_per."', after_discount_amt='".$txt_after_discount_amt."',  cgst_per='".$txt_cgst."', sgst_per='".$txt_sgst."', igst_per='".$txt_igst."', tot_tax_amt='".$txt_tax_amt."', final_pur_amt='".$txt_final_purchase_amt."', UserId='".$_SESSION["UserId"]."' where p_invoice_no='".$edit_id."'   ";		
		$rslt = $db->insert($str_update_main);	
		
		//Transaction purchase details update [product or category details update]
		$pdt_cnt = count($hdn_pdt_cnt);
		for($i=0; $i<$pdt_cnt; $i++){			
			
			if(!empty($hdn_prev_sv_id[$i])){
				//update
								
				$str_update_det="update t_purchase_entry_details set pdt_sku='".$txt_pdt_sku[$i]."', saree_desc='".$txt_pdt_desc[$i]."', purchase_rate='".$txt_pdt_rate[$i]."',  pdt_discount_percent='".$txt_pdt_discount_per[$i]."', pdt_discount_amt='".$txt_pdt_discount_amt[$i]."', tot_amount='".$txt_tot_amt[$i]."', ";
				
				if($_FILES["uploadimg_".$i]["name"] != "") {						
					$file_name = $_FILES['uploadimg_'.$i]['name']; // filename to get file's extension
					if (strlen($file_name)) {
						$extension = substr($file_name, strrpos($file_name, '.')+1);
						$pdt_img_name = md5(uniqid().time()).".".$extension;
						$tmp = $_FILES['uploadimg_'.$i]['tmp_name'];
						$upload_dir = CAAROOT_DIR."/uploads/product_image/";
							
						move_uploaded_file($tmp,$upload_dir.$pdt_img_name);	
						
						$str_update_det .=" upload_img='".$pdt_img_name."', "; 
					}
				}
				
				$str_update_det .=" UserId='".$_SESSION["UserId"]."' where p_invoice_det_id='".$hdn_prev_sv_id[$i]."' "; 
													
				$db->insert($str_update_det);
				
			}else{
				//insert
									
				//product image upload
				$pdt_img_name='';
				if($_FILES["uploadimg_".$i]["name"] != "") {						
					$file_name = $_FILES['uploadimg_'.$i]['name']; // filename to get file's extension
					if (strlen($file_name)) {
						$extension = substr($file_name, strrpos($file_name, '.')+1);
						$pdt_img_name = md5(uniqid().time()).".".$extension;
						$tmp = $_FILES['uploadimg_'.$i]['tmp_name'];
						$upload_dir = CAAROOT_DIR."/uploads/product_image/";
							
						move_uploaded_file($tmp,$upload_dir.$pdt_img_name);				
					}
				}
					
				$str_insert_det="INSERT into t_purchase_entry_details(p_invoice_no, pdt_sku, saree_desc, upload_img, purchase_rate,pdt_discount_percent, pdt_discount_amt, tot_amount, IsActive, UserId, financial_id, createddate) 
				values('".$edit_id."', '".$txt_pdt_sku[$i]."', '".$txt_pdt_desc[$i]."', '".$pdt_img_name."', '".$txt_pdt_rate[$i]."', '".$txt_pdt_discount_per[$i]."',  '".$txt_pdt_discount_amt[$i]."', '".$txt_tot_amt[$i]."', '1', '".$_SESSION["UserId"]."', '".$_SESSION["Financial_id"]."', NOW())";
													
				$db->insert($str_insert_det);	
			}
		}
						
		echo json_encode(array("rslt"=>"2")); //update success
		
	break;
	
	// case 'del':
	//   $edit_id = base64_decode($Id);
	  
	//   $chk_ref = check_reference($db, $edit_id);
	  
	//   if($chk_ref == 1){
	// 	   $str="update m_customer set IsActive = '2', UserId='".$_SESSION["UserId"]."'  where cus_id = '".$edit_id."'";
	// 	  $db->insert($str); 	 
		  
	// 	  $db->insert_log("delete","m_customer",$edit_id,"Customer deleted","Customer",$str);
	// 	  echo json_encode(array("rslt"=>"5")); //deletion
	//   }
	//   else{
	// 	 echo json_encode(array("rslt"=>"-1", "err_msg"=>"Reference exists with other data. Cannot Perform the action.")); //deletion  
	//   }	 		
	// break;
	
	case 'changestatus':
	  $edit_id = base64_decode($Id);
	  $status = $actval;
	  
	  $chk_ref = check_reference($db, $edit_id);
	//   echo $chk_ref;
	//   exit;
	  if($chk_ref == 1){
			$str="update t_purchase_entry_main set IsActive = '".$status."', UserId='".$_SESSION["UserId"]."'  where p_invoice_no = '".$edit_id."'";
			$db->insert($str); 	 
		  
			// $db->insert_log("changestatus","m_customer",$edit_id,"Customer status changed","Customer",$str);
			echo json_encode(array("rslt"=>"6")); //status update
	  }
	  else{
			echo json_encode(array("rslt"=>"-1", "err_msg"=>"Reference exists with other data. Cannot Perform the action.")); //deletion  
	  }	 
	  	 
		
	break;
	
	case 'del_pdt_det':
		if(isset($pdt_det_id) && !empty($pdt_det_id)){
			$rslt_pdt_det = $db->get_a_line("select t1.*, t2.p_payment_id, t2.tot_paid_amt from t_purchase_entry_details t1 inner join t_purchase_payment t2 on t1.p_invoice_no = t2.p_invoice_no where 1=1 and t1.p_invoice_det_id='".$pdt_det_id."' ");
						
			if((isset($rslt_pdt_det['tot_paid_amt']) && $rslt_pdt_det['tot_paid_amt']=='0.00') || empty($rslt_pdt_det['p_payment_id']) ){	
				$str="update t_purchase_entry_details set IsActive = '2', UserId='".$_SESSION["UserId"]."'  where p_invoice_det_id = '".$pdt_det_id."'";
				$db->insert($str); 
				
				echo json_encode(array("rslt"=>"1"));  
			}else{
				echo json_encode(array("rslt"=>"-9", "err_msg"=>"Reference exists with payment information. Cannot Perform the action."));  
			}
			
		}
		else{
			echo json_encode(array("rslt"=>"-1"));  
		}	 
	break;
	
	case 'check_pdt_sku':
		if(isset($pdt_sku) && !empty($pdt_sku)){
			
			if(isset($invoice_id) && !empty($invoice_id)){
				//$strChk = "select count(p_invoice_det_id) from t_purchase_entry_details where pdt_sku = '".$pdt_sku."' and IsActive != '2'  and p_invoice_no != '".$invoice_id."' ";
				$strChk = "select count(t1.p_invoice_det_id) from t_purchase_entry_details t1
				inner join t_purchase_entry_main t2 on t1.p_invoice_no = t2.p_invoice_no and t2.IsActive=1
				where t1.pdt_sku = '".$pdt_sku."' and t2.company_id='".$company_name."' and t1.IsActive != '2' and t1.p_invoice_no != '".$invoice_id."' ";
				
			}
			else{
				//$strChk = "select count(p_invoice_det_id) from t_purchase_entry_details where pdt_sku = '".$pdt_sku."' and IsActive != '2' and  ";
				$strChk = "select count(t1.p_invoice_det_id) from t_purchase_entry_details t1
				inner join t_purchase_entry_main t2 on t1.p_invoice_no = t2.p_invoice_no and t2.IsActive=1
				where t1.pdt_sku = '".$pdt_sku."' and t2.company_id='".$company_name."' and t1.IsActive != '2'  ";
			}
			
			$reslt = $db->get_a_line($strChk);
			if($reslt[0] == 0) {
				echo json_encode(array("rslt"=>"1")); //success
			}else{
				echo json_encode(array("rslt"=>"-9", "err_msg"=>" Product SKU already exists"));  
			}
		}
	break;

	case 'del':
		$edit_id = base64_decode($Id);
		
		
		$query1 = "DELETE FROM t_purchase_entry_main WHERE p_invoice_no = $edit_id";
		$query2 = "DELETE FROM t_purchase_entry_details WHERE p_invoice_no = $edit_id";
		// $query3 = "DELETE FROM t_purchase_payment WHERE p_invoice_no = $edit_id";
		
		// && $db->insert($query3) 
	
		
	if ($db->insert($query1) && $db->insert($query2)   ) {
		echo json_encode(array("rslt" => "5", "msg" => "Product Deleted Successfully"));
	} else {
		echo json_encode(array("rslt" => "-1", "err_msg" => "Error: " . $e->getMessage()));
	}
exit;
break;

}


function check_reference($db, $customer_id){
	return 1;
}


?>