<?php
include("common/connection.php");

$fetch_agreemnt=mysqli_fetch_array(mysqli_query($con,"select * from patient_agreement where SLN='".$_REQUEST['aggrement']."'"));
$fetch_location=mysqli_fetch_array(mysqli_query($con,"select * from location_master where SLN='".$fetch_agreemnt['Control_Location']."'"));

	
 $inv_loc=strtoupper(substr($fetch_location['Location_Name'],0,3));

$month=date('M');
$m=strtoupper(substr($month,0,3));

$max_sln="SELECT Invoice_No from invoice_master WHERE SLN=(select MAX(SLN)as 'MaxSln' from invoice_master where Location='".$inv_loc."')";
$qry=mysqli_query($con,$max_sln);
$FetchSLN=mysqli_fetch_array($qry);
$inv=$FetchSLN['Invoice_No'];
$MAX_SLN=explode("/",$inv);

if($MAX_SLN[3]=="")
	{
	
	$New_INV="INV/".$inv_loc."/".$m."/1";
	}
	else
	{
	$newsln=$MAX_SLN[3]+1;
	
	$New_INV="INV/".$inv_loc."/".$m."/".$newsln;
	}

//echo $New_INV;


if($fetch_agreemnt['End_Date']>date('Y-m-d'))
{
	$end=date('Y-m-d');
}
else
{
	$end=$fetch_agreemnt['End_Date'];
}

if($fetch_agreemnt['Last_Invoice_Date']=="0000-00-00")
{
	$condition="Treatment_Service_Date between '".$fetch_agreemnt['Start_Agreement_Date']."' and '".$end."'";
	$strt_date=$fetch_agreemnt['Start_Agreement_Date'];
}
else
{
	$strt=date('Y-m-d',strtotime($fetch_agreemnt['Last_Invoice_Date']."+1 days"));
	$strt_date=$strt;
	$condition="Treatment_Service_Date between '".$strt."' and '".$end."'";
}

$fetch_id=mysqli_fetch_array(mysqli_query($con,"Select Patient_Id from patient_master where Lead_ID='".$fetch_agreemnt['Lead_ID']."'"));

//echo "select * from roster_master  where Patient_Id='".$fetch_id['Patient_Id']."' and ". $condition;
$get_roster=mysqli_query($con,"select * from roster_master  where Patient_Id='".$fetch_id['Patient_Id']."' and ". $condition); 
$attendance=mysqli_num_rows($get_roster);
 $inv_amt=$attendance*$fetch_agreemnt['Rate_Per_Day'];
 
 mysqli_query($con,"insert into invoice_master (Invoice_No,Start_Date,Invoice_Date,Patient_Id,Total_Days,Rate,Amount,Location,Aggrement_Id) values ('".$New_INV."','".date('Y-m-d',strtotime($strt_date))."','".date('Y-m-d')."','".$fetch_id['Patient_Id']."','".$attendance."','".$fetch_agreemnt['Rate_Per_Day']."','".$inv_amt."','".$inv_loc."','".$_REQUEST['aggrement']."')");
 
 mysqli_query($con,"update patient_agreement set Last_Invoice_Date='".date('Y-m-d')."' where SLN='".$_REQUEST['aggrement']."'");
?>