<?php   
    require "commonincludefiles.php";
	
	$action = $_REQUEST['action'];
	$subgroupcode = $_REQUEST['subgroupcode'];
	$subgroupname = $_REQUEST['subgroupname'];
	
	if ($_SESSION['cCompany_id']!="" && isset($_SESSION['cCompany_id'])) {
		
		$objAccountSubGroupMgmt = new AccountSubGroupMgmt();
		
		if($action == "save"){
			$objAccountSubGroupMgmt->subgroup_name = $subgroupname;
			$objAccountSubGroupMgmt->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_accountsubgroup asg
					WHERE am.company_id = '".$_SESSION["cCompany_id"]."' 
						AND asg.company_id = '".$_SESSION["cCompany_id"]."' 
						AND am.subgroup_id=asg.subgroup_id 
						AND asg.subgroup_id = $subgroupcode ";
			$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_accountsubgroup where subgroup_id in ($subgroupcode) 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..."}';	

			////
		
			/*$objAccountSubGroupMgmt->subgroup_id = $subgroupcode;
			$objAccountSubGroupMgmt->delete();
			echo '{"success":"true","msg":"Data has been deleted..."}';	*/
		}
		else{ // edit code
			$objAccountSubGroupMgmt->subgroup_name = $subgroupname;
			$objAccountSubGroupMgmt->subgroup_id = $subgroupcode;
			$objAccountSubGroupMgmt->edit();
			echo '{"success":"true","msg":"Data has been edited..."}';	
		}
	} 
	else {
		echo '{"success":"false","msg":"session expiry"}';
	}
?>