<?php   
    require "commonincludefiles.php";
	error_reporting(1);
	
	$action = $_REQUEST['action'];
	$groupcode = $_REQUEST['groupcode'];
	$groupname = $_REQUEST['groupname'];
	$grouptype = $_REQUEST['group_type'];
		
	if ($_SESSION['cCompany_id']!="" && isset($_SESSION['cCompany_id'])) {
		
		$objAccountGroup = new AccountGroupMgmt();
		
		if($action == "save"){
			$objAccountGroup->account_groupname = $groupname;
			$objAccountGroup->account_type 		= $grouptype;
			$objAccountGroup->add();			
			echo '{"success":"true","msg":"Data has been saved..."}';	
		}
		elseif($action == "delete"){
		
			$str_voucherid = "";
			$str_accountid = "";
		
			$qry1 = "SELECT group_concat(am.account_id) AS account_id
					FROM ams_accountmaster am,ams_accountgroup ag
					WHERE am.company_id = '".$_SESSION["cCompany_id"]."' 
						AND ag.company_id = '".$_SESSION["cCompany_id"]."' 
						AND am.account_groupid=ag.account_groupid 
						AND ag.account_groupid = $groupcode ";
			$result = dbQuery($qry1);
			
			if(dbRows($result)>0){
				$record_account = dbArray($result);
				$str_accountid = $record_account['account_id'];
				if($str_accountid!=""){
					$qry2 = "SELECT group_concat(vm.voucher_id) AS voucher_id
							FROM ams_vouchermaster vm,ams_voucherdetail vd
							WHERE vm.company_id = '".$_SESSION["cCompany_id"]."' 
								AND vd.company_id = '".$_SESSION["cCompany_id"]."' 
								AND vm.voucher_id=vd.voucher_id 
								AND vd.account_id in($str_accountid) ";
					$result = dbQuery($qry2);
					if(dbRows($result)>0){
						$record_voucher = dbArray($result);
						$str_voucherid = $record_voucher['voucher_id'];
					}
				}
			}
			
			$qry3 = "delete from ams_accountgroup where account_groupid in ($groupcode) And company_id='".$_SESSION["cCompany_id"]."'";
			dbQuery($qry3);
			
			if($str_accountid!=""){
				$qry4 = "delete from ams_accountmaster where account_id in ($str_accountid) And company_id='".$_SESSION["cCompany_id"]."'";
				dbQuery($qry4);
			}
			
			if($str_voucherid != ""){
				$qry5 = "delete from ams_vouchermaster where voucher_id in ($str_voucherid) And company_id='".$_SESSION["cCompany_id"]."'";
				$qry6 = "delete from ams_voucherdetail where voucher_id in ($str_voucherid) And company_id='".$_SESSION["cCompany_id"]."'";
				dbQuery($qry5);
				dbQuery($qry6);
			}
			echo '{"success":"true","msg":"Data has been deleted..."}';	
		}
		else{ // edit code
			$objAccountGroup->account_groupid 	= $groupcode;
			$objAccountGroup->account_groupname = $groupname;
			$objAccountGroup->account_type 		= $grouptype;
			$objAccountGroup->edit();
			echo '{"success":"true","msg":"Data has been edited..."}';	
		}
	} 
	else {
		echo '{"success":"false","msg":"session expiry"}';
	}
?>