<?php
include('db_connection.php');
$Mainclass=new DB_Controller();


$Product_Id=ltrim($_REQUEST['Product_Code'],'^');
$Product_Id=ltrim($Product_Id,'~');

$ScanProductCode=$Product_Id;
/*
 $ScanProductSize=strlen($Product_Id);

if($ScanProductSize<6)
{
   
	
	 $contains_letters = preg_match('/[A-Za-z]+/', $Product_Id);
	 
	 if( $contains_letters==1)
	 {
	    $ProductFristCh=substr($Product_Id, 0, 1);
	    $RestProductCh=substr($Product_Id, 1, 5);
		$RestNewCode=sprintf("%05d", $RestProductCh);
		 
		$CreatePrCode=$ProductFristCh.$RestNewCode;
	 }
	 else{
	 
	       $CreatePrCode=sprintf("%06d", $Product_Id);
	 }
	 
	 $Product_Id=$CreatePrCode;

}
else{

      $Product_Id=$Product_Id;

}*/

//echo $Product_Id;

//=========check diamond========//
/*
if(substr($Product_Id, -1)=="D")
{
    $Product_Id=$Product_Id;
}
else
{ 
     $Product_Id=substr($Product_Id, 0, 6);
}*/


$Product_Id=substr($Product_Id, 0, 11);



$Order_No=$_REQUEST['Order_No'];

$Indent_No=$_REQUEST['Indent_No'];

$FetchDealerCon=" Order_Code= '".$_REQUEST['dealer']."'";
$Field_Needed="State,Dealer_Credit_Limit,Dealer_Type";
$DeaerDtl=$Mainclass->Fetch_individual_data('dealer_master',$Field_Needed,$FetchDealerCon);


if($Product_Id!='')
{




	$SqCheckIndent="select * from gold_indent_master where Order_No='".$Order_No."' and Indent_Status='Completed'";
    $RsCheckIndent=mysqli_query($Mainclass->dbh,$SqCheckIndent);
	$CreateIndent=mysqli_num_rows($RsCheckIndent);
	
	if($CreateIndent>0)
	{
	
	    echo "Already exist";
		  exit;
	}
	  




    

    //$Check=$Mainclass->product_check('gold_products_master',$Product_Id);
	//$Get_Product=$Mainclass->product_det('gold_products_master',$Product_Id);
	
	$Check=$Mainclass->barcode_check('gold_products_master',$ScanProductCode);
	$Get_Product=$Mainclass->product_barcode_det('gold_products_master',$ScanProductCode);
	
	if($Check==0)
	{
	   echo "Not Found";
	   exit;
	
	}
	
    if(strtoupper($Get_Product['Metal_Type'])!='GOLD')
	{
		echo "Invalid Metal Type";
	    exit;
	}
	
   
	 
	
	$SqlOrderDtl="select sum(Order_Quantity) as Order_Quantity from  gold_indent_details where Order_No='".$Order_No."' and Product_Code='".$Product_Id."'";
	$RsOrderDtl=mysqli_query($Mainclass->dbh,$SqlOrderDtl);
	$CountIndentDtl=mysqli_num_rows($RsOrderDtl);
	$FchIndentDtl=mysqli_fetch_array($RsOrderDtl);
	
	
	//=================Check Stock================//
	$PMSDCondition=" Product_Code ='".$Product_Id."'"; 
	//$PMSD_QTY=$Mainclass->product_det('product_master',$PMSDCondition);
	$PMSD_QTY=$Mainclass->product_det('gold_products_master',$Product_Id);
	
	$IndOrderQty=$FchIndentDtl['Order_Quantity']+1;
	
	//echo "SS=".$PMSD_QTY['Stock'];
	
	if($PMSD_QTY['Stock']<$IndOrderQty)
	{
	    echo "Stock Out";
	    exit;
	
	}
	
	
	$Gold_Wt=$Get_Product['GoldWeight']; 
	$Stone_Value=$Get_Product['total_stone_price'];
   // $Diamond_Value=$Get_Product['total_diamond_price']; 
    $Diamond_Value=$Get_Product['DiamondValue']*$Get_Product['Diamond_Carat']; 
//	$Solitaire_Value=$Get_Product['total_sollitaire_price']; 
    $Solitaire_Value=$Get_Product['Solitaire_Value']*$Get_Product['sollitaire_Carat']; 
	$Making_Charge_Type=$Get_Product['MakingChargesType'];
	$Making_Charge=$Get_Product['MakingChargesValue'];
    $Wastage_Cost=$Get_Product['WastedCost'];
	$Gold_Purity=$Get_Product['GoldPurity'];
	
	//$Today_Gold_Rate=$Mainclass->today_gold_rate($Gold_Purity,$_REQUEST['dealer']);
	$Today_Gold_Rate=$Mainclass->today_gold_dealer_rate($Gold_Purity);
	
	
	
	//===================================//
	 $Dealer_Code=$_REQUEST['dealer'];
	
	 $FetchCatCon=" SLN= '".$Get_Product['ProductCategory']."'";
     $Field_Needed="SLN,Category";
     $CategoryDtl=$Mainclass->Fetch_individual_data('gold_product_category_master',$Field_Needed,$FetchCatCon);
	
	 // echo "XXX=".$CategoryDtl['SLN'];
	
	
	 if(strtoupper($DeaerDtl['Dealer_Type'])=="OWNED" && strtoupper($DeaerDtl['State'])=="WEST BENGAL")
	 {
	  //$GetDealerMargin=0;
	  $MakingChargMargin=0;
	  $DiamondMargin=0;
	  $StoneMargin=0;
	  $SolitaireMargin=0;
	 }
	 else
	 {
	     
	    /* $GetStnDis=$Mainclass->GetStnDis($Product_Id); 
	     
	     
	     
	   
	    
	    if($GetStnDis>0)
		{
			$GetDealerMargin=$GetStnDis;
		}
		else{
			
	      $GetDealerMargin=$Mainclass->GetDealerMarginAmt($CategoryDtl['SLN'],$Dealer_Code);
		 }*/
	    
	    if($Diamond_Value>0)
		{
			$GetDiamondMargin=$Mainclass->GetDealerMarginAmt('Diamond',$Dealer_Code);
		}
		else{
			$GetDiamondMargin=0;
		}
		
		if($Stone_Value>0)
		{
			$GetStoneMargin=$Mainclass->GetDealerMarginAmt('Stone',$Dealer_Code);
		}
		else{
			$GetStoneMargin=0;
		}
		if($Solitaire_Value>0)
		{
			$GetSolitaireMargin=$Mainclass->GetDealerMarginAmt('Solitaire',$Dealer_Code);
		}
		else{
			$GetSolitaireMargin=0;
		}
	    
	     $MakingChargMargin=$Mainclass->GetDealerMarginAmt('Making Charge',$Dealer_Code);
		 $GoldMargin=$Mainclass->GetDealerMarginAmt('Gold',$Dealer_Code);
	 }

     
    $Total_Gold_Value=$Gold_Wt*$Today_Gold_Rate;
	
	$GoldMarginValue=$Today_Gold_Rate*$GoldMargin/100;
	$GoldMarginValue=number_format((float)$GoldMarginValue, 2, '.', '');
	
	$Total_GoldMarginValue=$Gold_Wt*$GoldMarginValue;
	
	$DMGold=$Total_Gold_Value-$Total_GoldMarginValue;
	
	if($Making_Charge_Type=="Flat")
	{
		$Making_Charge_Val=$Making_Charge;
	}
	if($Making_Charge_Type=="Percentage")
	{
		//$Making_Charge_Val=($Total_Gold_Value*$Making_Charge)/100;
		$Making_Charge_Val=($DMGold*$Making_Charge)/100;
	}
	if($Making_Charge_Type=="Rate per gram")
	{
		$Making_Charge_Val=$Making_Charge * $Gold_Wt;
	}	 
	 
	$StonePrice=$Diamond_Value+$Stone_Value+$Solitaire_Value;
	//====Taxable_Amount=====//
	$ProductPrice=$Total_Gold_Value+$Making_Charge_Val+$StonePrice+$Wastage_Cost;	

    // echo $Get_Product['Price'];

	//$DMPrice=$Get_Product['Price']*$GetDealerMargin/100;
	//$DMPrice=number_format((float)$DMPrice, 2, '.', '');
	//$DMProductPrice=$Get_Product['Price']-$DMPrice;
	
	$DiamondMarginValue=$Diamond_Value*$GetDiamondMargin/100;
	$DiamondMarginValue=number_format((float)$DiamondMarginValue, 2, '.', '');
	
	$StoneMarginValue=$Stone_Value*$GetStoneMargin/100;
	$StoneMarginValue=number_format((float)$StoneMarginValue, 2, '.', '');
	
	$SolitaireMarginValue=$Solitaire_Value*$GetSolitaireMargin/100;
	$SolitaireMarginValue=number_format((float)$SolitaireMarginValue, 2, '.', '');
	
	
	$MakingChargeMarginValue=$Making_Charge_Val*$MakingChargMargin/100;
	$MakingChargeMarginValue=number_format((float)$MakingChargeMarginValue, 2, '.', '');
	
	//$GoldMarginValue=$Today_Gold_Rate*$GoldMargin/100;
	//$GoldMarginValue=number_format((float)$GoldMarginValue, 2, '.', '');
	
	
	//$DMGold=$Today_Gold_Rate-$GoldMarginValue;
	$DMDiamond=$Diamond_Value-$DiamondMarginValue;
	$DMStone=$Stone_Value-$StoneMarginValue;
	$DMSolitaire=$Solitaire_Value-$SolitaireMarginValue;
	$DMMakingCharge=$Making_Charge_Val-$MakingChargeMarginValue;
	
	
	$Stone=$DMDiamond+$DMStone+$DMSolitaire;
	//====Taxable_Amount=====//
	$Amt_Bf_Tax=$Total_Gold_Value+$DMMakingCharge+$Stone+$Wastage_Cost;	
	
	//echo "XX=".$Amt_Bf_Tax;
	
	
	//$GST=$Mainclass->Get_GST_Product('product_gst_master',$Get_Product['HSN_Code']);
	
	
	$DMProductPrice=$ProductPrice-($GoldMarginValue+$DiamondMarginValue+$StoneMarginValue+$SolitaireMarginValue+$MakingChargeMarginValue);
	//===============check Ct limit===============//	
	$AvailableCr=$DeaerDtl['Dealer_Credit_Limit'];
    
	
	$SqIndent="select * from indent_master where Order_No='".$Order_No."'";
    $RsIndent=mysqli_query($Mainclass->dbh,$SqIndent);
    $FchIndentMaster=mysqli_fetch_array($RsIndent);
	
	$GST=3;
	
	if(strtoupper($DeaerDtl['Dealer_Type'])=="OWNED" && strtoupper($DeaerDtl['State'])=="WEST BENGAL")
	{
		 $OrderProduct=$Amt_Bf_Tax;
	}
	else{
		
		
		$App_GST_Amount=($GST * $Amt_Bf_Tax)/100; 
		
		$OrderProduct=$Amt_Bf_Tax+$App_GST_Amount;
	
	}
	
	$IndentOrderAmt=$FchIndentMaster['Net_Total']+$OrderProduct;
	
	
	
	if(($IndentOrderAmt>$AvailableCr) && $FchIndentMaster['Consignment_Stn']==0)
	{
	   //echo "Your Credit limit has exceeded";
	   //exit;
	
	}
//=====================check Ct limit===================//	

	
		//===========Check ROL 24-07-21==================//
    $FetchRolCon=" Dealer_Code='".$_REQUEST['dealer']."'";
	$FetchRolCon.="  group by Dealer_Code order by SLN desc";

	
    $Field_Needed_Rol="ROL_Limit";
    $DeaerRolDtl=$Mainclass->Fetch_individual_data('gold_dealer_rol_master',$Field_Needed_Rol,$FetchRolCon);
	
	
	$SQL_SUM="select sum(`Cost_Price`*`Quantity`) as TotalStockAmt from dealer_stock_master where Dealer_Code='".$_REQUEST['dealer']."' and (Category_Code!=38 and Category_Code!=39 and Category_Code!=40 and Category_Code!=41 and Category_Code!=42 and Category_Code!=0)";
    $QRY_SUM=mysqli_query($Mainclass->dbh,$SQL_SUM);
	$Ft_SUM=mysqli_fetch_array($QRY_SUM);
		
	$Diff=round($Ft_SUM['TotalStockAmt'])-$DeaerRolDtl['ROL_Limit'];
	
	$AvlRolLt=$AvailableCr-(-1*$Diff);
	if($Diff<0)
	{
	if($AvlRolLt<0)
	{
	  // echo "Your Rol limit has exceeded";
	  // exit;
	
	}
	}
	//============ROL===================//
	
	
	
	
	
	
	
	
	
	/*if($CountIndentDtl==0)
	{*/

	 $Qty=1;
	 $Price=$ProductPrice;
	// $Order_Total=$Price*$Qty;
	 
	 //$Total_Product_Cost_Price=$DMProductPrice*$Qty;
	 $Total_Product_Cost_Price=$Amt_Bf_Tax*$Qty;
	 
	// $Discount=$DMPrice*$Qty;
	
	 
	 //$Discount=($DiamondMarginValue+$StoneMarginValue+$SolitaireMarginValue+$MakingChargeMarginValue)*$Qty;
	 $Discount=($Total_GoldMarginValue+$DiamondMarginValue+$StoneMarginValue+$SolitaireMarginValue+$MakingChargeMarginValue)*$Qty;
	 
	 
	
	 
	 
	if( strtoupper($DeaerDtl['Dealer_Type'])=="OWNED" && strtoupper($DeaerDtl['State'])=="WEST BENGAL")
	{
	    $Net_Price=$Total_Product_Cost_Price;
	
	 }
	 else{
	 

	   $XR=($GST * $Total_Product_Cost_Price)/100; 

	   $GST_Amount= $XR;		
	   //echo "CP2=".$Total_Price=$Total_Product_Cost_Price;
	   //$Net_Price=$Total_Price + $GST_Amount;
	 }
	 
	 
	 	
    if( strtoupper($DeaerDtl['Dealer_Type'])=="OWNED" && strtoupper($DeaerDtl['State'])=="WEST BENGAL")
    {	
	         $CGST=0;
			 $SGST=0;
			 $IGST=0;
		
	 }
	 else{
	 
	 
	     if(strtoupper($DeaerDtl['State'])=="WEST BENGAL")
		 {
			 $GST_Div=$GST_Amount/2;
			 $CGST=$GST_Div;
			 $SGST=$GST_Div;
		 }
		 else{
			 $IGST=$GST_Amount;
		 }
	 
	 
	 }
	$Net_Price= $Total_Product_Cost_Price+number_format((float)$CGST, 2, '.', '')+number_format((float)$SGST, 2, '.', '')+number_format((float)$IGST, 2, '.', ''); 
	 
   $SqlIndentDetail="insert into gold_indent_details(Order_No,Indent_No,Adding_Date,Dealer_Code,Product_Code,HSN_Code,Block_Product,Product_Category,Size,Discount,Price,Total,Order_Total,GST,CGST,SGST,IGST,Order_Quantity,Product_Weight,Scan1,Ref_Product_Code,gold_rate,gold_discount,total_gold_value,gold_wt,gold_purity,no_diamond,diamond_carat,diamond_rate,diamond_discount,total_diamond_value,no_stone,stone_price,stone_discount,total_stone_value,no_solitaire,sollitaire_carat,solitaire_price,solitaire_discount,total_sollitaire_value,making_charge_type,making_charge_val,total_making_charge,wastage_cost,making_charge_discount,gold_value,stone_value,diamond_value,sollitaire_value,making_charge) values('".$Order_No."','".$Indent_No."','".date('Y-m-d H:i:s')."','".$_REQUEST['dealer']."','".strtoupper($Product_Id)."','".$PMSD_QTY['HSNCode']."','".$FchOrderDtl['Urgent']."','".$CategoryDtl['SLN']."','".$FchOrderDtl['Size']."','".$Discount."','".$Price."','".$DMProductPrice."','".$Net_Price."','".$GST_Amount."','".$CGST."','".$SGST."','".$IGST."','".$Qty."','".$Get_Product['Weight']."','1','".$ScanProductCode."','".$Today_Gold_Rate."','".$Total_GoldMarginValue."','".$DMGold."','".$Gold_Wt."','".$Gold_Purity."','".$Get_Product['No_Diamond']."','".$Get_Product['Diamond_Carat']."','".$Get_Product['DiamondValue']."','".$DiamondMarginValue."','".$DMDiamond."','".$Get_Product['No_Stone']."','".$Get_Product['StoneValue']."','".$StoneMarginValue."','".$DMStone."','".$Get_Product['No_Solitaire']."','".$Get_Product['sollitaire_Carat']."','".$Get_Product['Solitaire_Value']."','".$SolitaireMarginValue."','".$DMSolitaire."','".$Making_Charge_Type."','".$Making_Charge."','".$DMMakingCharge."','".$Wastage_Cost."','".$MakingChargeMarginValue."','".$Total_Gold_Value."','".$Stone_Value."','".$Diamond_Value."','".$Solitaire_Value."','".$Making_Charge_Val."')";
	mysqli_query($Mainclass->dbh,$SqlIndentDetail);
	/*}
	else{
	    
		
	  
		$UpQty=$FchIndentDtl['Order_Quantity']+1;
	    $Price=$FchIndentDtl['Price'];
	  
		
		$Total_Product_Cost_Price=$DMProductPrice*$UpQty;
		
		$Discount=$DMPrice*$UpQty;
		
		 $XR=($GST * $Total_Product_Cost_Price)/100; 

		 $GST_Amount= $XR;		
		 $Total_Price=$Total_Product_Cost_Price;
		 $Net_Price=$Total_Price + $GST_Amount;
		 
		 
		  if(strtoupper($DeaerDtl['State'])=="WEST BENGAL")
		 {
			 $GST_Div=$GST_Amount/2;
			 $CGST=$GST_Div;
			 $SGST=$GST_Div;
		 }
		 else{
			 $IGST=$GST_Amount;
		 }
		 
		 
		 
	
	   $UpdateIndDtl="update indent_details set Order_Quantity='".$UpQty."',Order_Total='".$Net_Price."' ,Discount='".$Discount."',GST='".$GST_Amount."',CGST='".$CGST."',SGST='".$SGST."',IGST='".$IGST."' where Order_No='".$Order_No."' and Product_Code='".$Product_Id."'";
	   mysqli_query($Mainclass->dbh,$UpdateIndDtl);
	
	}*/
	

	

	
	
	$SqCheckIndent="select * from gold_indent_master where Order_No='".$Order_No."'";
    $RsCheckIndent=mysqli_query($Mainclass->dbh,$SqCheckIndent);
    $FchIndent=mysqli_fetch_array($RsCheckIndent);

    $CreateIndent=mysqli_num_rows($RsCheckIndent);
    if($CreateIndent==0)
	{

	
	/* $InnserIndentMast="insert into indent_master(Order_No,Order_No,Dealer_Code,Total_Quantity,Net_Total,Indent_Date,Created_By,Status)values('".$Order_No."', '".$FchRow['Order_No']."','".$_REQUEST['dealer']."','1','','".date('Y-m-d')."','".$_SESSION['PIP_Login_User']."','Processing')";
	 mysqli_query($Mainclass->dbh,$InnserIndentMast);
	 echo 1;*/
	 
	}
	else{
		   $Sql="select sum(Price) as TotalPrice,sum(Discount) as TotalDiscount, sum(Total) as Gross_Total,sum(Order_Total) as Net_Amt, sum(Order_Quantity) as Total_Qty,sum(GST) as GST,sum(CGST) as CGST,sum(SGST) as SGST,sum(IGST) as IGST,sum(Product_Weight) as Product_Weight from gold_indent_details where Order_No='".$Order_No."'";
           $RS=mysqli_query($Mainclass->dbh,$Sql);
           $ROW=mysqli_fetch_array($RS);
		  
		  $UpdateOrder="update gold_indent_master set Total_Quantity='".$ROW['Total_Qty']."',Total='".$ROW['TotalPrice']."',Discount='".$ROW['TotalDiscount']."',Gross_Total='".$ROW['Gross_Total']."',Net_Total='".$ROW['Net_Amt']."',GST='".$ROW['GST']."',CGST='".$ROW['CGST']."',SGST='".$ROW['SGST']."',IGST='".$ROW['IGST']."',Toal_Product_Weight='".$ROW['Product_Weight']."' where Order_No='".$Order_No."'";
		   mysqli_query($Mainclass->dbh,$UpdateOrder);
		
		}
	
	

}
?>