<?php
session_start();
//($_SERVER['REQUEST_METHOD'] == 'POST') ? "":die();
if(!empty($_SESSION['user']['id']) && $_SESSION['user']['account'] > 0 && isset($_POST['branch']) && isset($_POST['account_num']))
{ 

	//$user_id = $_SESSION['user']['id'];
	//$account = $_SESSION['user']['account'];
	$data =[];
	$result = false;
	$msg= "ليس لديك الصلاحيات الكافية لتنفيذ هذا الإجراء";
	$theid = '0';
	$thebranch = '0';

	$branch = $_SESSION['branch'];
	
	$posted_branch = (int)$_POST['branch'];
	$account_num = (int)$_POST['account_num'];
	
	
	
	
	
	
	
	
				
				
	//if($_SESSION['role'] == 'seals' ){
	if($posted_branch != $branch && $_SESSION['role'] !='owner' ){
		//$error= true;
		$result= false;
		$msg= 'ليس لديك صلاحيات حذف الحسابات من فروع أخرى';
	}else{
		
		require('../../../mdtech/inc/config.php');
		$connect_pdo->query("SET NAMES utf8");
		$query = "SELECT * FROM tblaccountguide WHERE AccountID = :account_num and BranchID = :posted_branch limit 1";
		$statement = $connect_pdo->prepare($query);
		$statement->execute(
								array(
									':account_num'  => $account_num, 
									':posted_branch' => $posted_branch
								)
							);
		if( $statement->rowCount()){
			$row = $statement->fetch();
			$AccountID = $row['AccountID'];
			$AccountNumber = $row['AccountNumber'];
			$AccountName = $row['AccountName'];
			$BranchID = $row['BranchID'];
			
			if($row['IsSystem']){
				$result= false;
				$msg= 'لايمكن حذف هذا الحساب';
			}else{
				$q = "SELECT AccountID FROM tblaccountguide WHERE ParentNumber = $AccountID limit 1";
				$stm = $connect_pdo->prepare($q);
				$stm->execute();
				if( $stm->rowCount() > 0){
					$result= false;
					$msg= 'لايمكنك حذف هذا الحساب الآن، لانة يحتوي على حسابات فرعية أخرى';
				}else{
					
					$q2 = "SELECT EntryDetailsID FROM tblentriesdetails WHERE AccountID = $AccountID order by EntryDetailsID DESC limit 1";
					$stm2 = $connect_pdo->prepare($q2);
					$stm2->execute();
					if( $stm2->rowCount() > 0){
						$result= false;
						$msg= 'لايمكن حذف هذا الحساب لإحتوائة على حركات مالية';
					}else{
						$result= true;
						$theid = $AccountID;
						$thebranch = $BranchID;
						$msg= 'هل أنت متأكد من رغبتك في حذف الحساب التالي<br>'.$AccountName.' (#'.$AccountNumber.') ? لن تتمكن من التراجع عن هذا الإجراء..! ';
					}
				}
			
			}
		}else{
			$result= false;
			$msg= 'لم يعد هذا الحساب متوفراً';
		}
		
	}
	
	
	
	 $data = array(
				 "result"		=> $result,
				 "msg"    		=> $msg,
				 "theid"		=> $theid,
				 "thebranch"	=> $thebranch
			);

			
		echo(json_encode($data,JSON_UNESCAPED_UNICODE)); 
	


}

?>