<?php
include("../connect.php"); 
$response = array();
if(isset($_POST['a_name']) && isset($_POST['a_phone']) && isset($_POST['manager_id']))
{
	$ver = $_POST['manager_id'];
	$a_name=$_POST['a_name'];
	$a_phone=$_POST['a_phone'];
	// $agent_code=$_POST['agent_code'];
	date_default_timezone_set('Asia/Calcutta');
	$cdate  = date("Y-m-d")." ".date('h:i:sa');
	$t_date  = date("Y-m-d");
	$t_time  = date('h:i:sa');
	
	$qur = mysqli_query($con,"Select * from tbl_agent_code_sequence where admin_id = (Select admin_id from tbl_manager where manager_id='$ver') order by sequence_id desc limit 1");
  	if(mysqli_num_rows($qur)>0){

	$fetch_qur=mysqli_fetch_assoc($qur);
	$code1 = $fetch_qur['sequence_code'];
	$code = substr($code1, 4);
	$int = (int)$code;
	$invID = str_pad(++$int, 3, '0', STR_PAD_LEFT);
	$code = substr($code1, 0,4);
	$agent_code = $code.$invID;
	
	}else{
		$q1=mysqli_query($con,"select * from tbl_admin_panel where admin_id=(select admin_id from tbl_manager where manager_id='$ver')");
		$g1=mysqli_fetch_assoc($q1);
		$code1=$g1['admin_name'];
		$adminId=$g1['admin_id'];
		$code=substr($code1,1);
		$agent_code=$code.'-001';
		$insert_seq=mysqli_query($con,"INSERT INTO `tbl_agent_code_sequence`( `admin_id`, `sequence_code`, `insert_date`, `insert_time`) VALUES ('$adminId','$acode','$t_date','$t_time'))");
	}

	// $query = mysqli_query($con,"INSERT INTO `tbl_agent_code_sequence`(`manager_id`, `sequence_code`, `insert_date`, `insert_time`) VALUES ('$ver','$agent_code','$t_date','$t_time')");	

	$res_product_stock = mysqli_query($con,"SELECT agent_name FROM  tbl_agent where agent_phone='$a_phone'");
	if(mysqli_num_rows($res_product_stock)<=0)
	{									
		$query = mysqli_query($con,"INSERT INTO `tbl_agent`(`agent_name`, `agent_phone`, `agent_code`, `manager_id`, `status`, `insert_datetime`) VALUES ('$a_name','$a_phone','$agent_code','$ver','Active','$cdate')");	
		$add_code=mysqli_query($con,"update tbl_agent_code_sequence SET sequence_code='$agent_code' where admin_id = (Select admin_id from tbl_manager where manager_id='$ver') ");
		$response['success']='1';
		$response['details']="Insert Successful";			
	}
	else
	{
		$response['success']='0';
		$response['details']="Agent already exists";
	}
}
else
{
	$response['success']='0';
	$response['details']="Required field missing";
}	
echo json_encode($response);
?>