<?php
if(!isset($_SESSION)) 
{ 
session_start(); 
} 
if(!isset($_SESSION['is_login']) ){
header("location: login.php");
?>
<script>
window.location="login.php";
</script>
<?php
}

// $permission  = explode(',',$_SESSION['permission_id']);
// if(!in_array(19,$permission) && !in_array(1,$permission)  ){

// $op['is_success'] = false;
// $op['data'] 	  = "عذرا انت غير مخول للوصل الى هذه الصفحة";
// echo json_encode($op);
// exit;

// }

date_default_timezone_set($_SESSION['SYSTimezone']);

	$Validator = array('is_success'=>false, 'data'=>array());
if (isset($_POST['type']) || isset($_GET['type'])){
		require_once "db_connect.php";

		if( isset($_GET['type']) && ($_GET['type'] == "load")){

			$cond = isset($_GET['typ'])? ' AND customer_type='.$_GET['typ']:'';

			// DB table to use
			$table = 'customer';
			// Table's primary key
			$primaryKey = 'customer_id';
			$columns =  array(
				  			  	array( 'db' => 'customer_id', 'dt' => 0 ),
			    				array( 'db' => 'customer_full_name', 'dt' => 1 ),
			    				array( 'db' => 'customer_email',  'dt' => 2 ),
			    				array( 'db' => 'customer_phone',   'dt' => 3 ),
								array( 'db' => 'customer_address',   'dt' => 4 ),
								array( 'db' => 'customer_job_title',   'dt' => 5 ),
								array( 'db' => 'customer_type',   'dt' => 6 ),
								array( 'db' => 'created_at',   'dt' => 7 , 'formatter'=> function($d){
									return date('Y-m-d',strtotime($d));
									 } ),
								array( 'db' => 'customer_phone2',   'dt' => 8 ),

			);
			// SQL server connection information
			$sql_details = array(
			    'user' => $mysql_user,
			    'pass' => $mysql_password,
			    'db'   => $mysql_db,
			    'host' => $mysql_server
			);
			require( 'ssp.class.php' );
			echo json_encode(
			    SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns ,null, " is_deleted=0 ". $cond )
			);
			exit;
		}

		if ($_POST['type']=="get") {

			//$user_id = $_POST['cusid'];


		
			$res = $db->query("SELECT * FROM customer WHERE is_deleted = 0  ");
			if ($res) {
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				    // do what you need.
						$result[0] = $row['customer_id'];
						$result[1] = $row['customer_full_name'];
						$result[2] = $row['customer_phone'];
						$result[3] = $row['customer_email'];
						
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}


		if ($_POST['type']=="get_customer_new") {

			//$user_id = $_POST['cusid'];

			$cond = "";

			if(isset($_POST['typ']) ){
				$cond = ' AND customer_type='.$_POST['typ'];
			}

			

			$res = $db->query("SELECT * FROM customer WHERE is_deleted = 0 $cond ");
			if ($res) {
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				    // do what you need.
					$result[0] = $row['customer_id'];
					$result[1] = $row['customer_full_name'];
					$result[2] = $row['customer_phone'];
					$result[3] = $row['customer_email'];
					
					array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

		if ($_POST['type']=="get_Customer") {

			$cust_typ = $_POST['cust_typ'];

			$res = $db->query("SELECT * FROM customer WHERE is_deleted = 0 AND customer_type = '$cust_typ'");
			if ($res) {
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				    // do what you need.
						$result[0] = $row['customer_id'];
						$result[1] = $row['customer_full_name'];
						$result[2] = $row['customer_phone'];
						$result[3] = $row['customer_email'];
						
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

		if ($_POST['type']=="get_outcome") {

			//$user_id = $_POST['cusid'];

			$res = $db->query("SELECT * FROM category WHERE is_deleted = 0 AND category_type=1");
			if ($res) {
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				    // do what you need.
						$result[0] = $row['category_id'];
						$result[1] = $row['category'];
						$result[2] = $row['category_type'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

		if ($_POST['type']=="get_income") {

			//$user_id = $_POST['cusid'];

			$res = $db->query("SELECT * FROM category WHERE is_deleted = 0 AND category_type=0");
			if ($res) {
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				    // do what you need.
						$result[0] = $row['category_id'];
						$result[1] = $row['category'];
						$result[2] = $row['category_type'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

		if ($_POST['type'] == "update") {

			$id 				= $_POST['obj_id'];
			$customer_full_name	=addslashes($_POST["customer_full_name"]);
            $customer_email		=addslashes($_POST["customer_email"]);
            $customer_phone		=addslashes($_POST["customer_phone"]);
            $customer_phone2	=addslashes($_POST["customer_phone2"]);
            $customer_address	=addslashes($_POST["customer_address"]);
            $customer_job_title	=addslashes($_POST["customer_job_title"]);
            $customer_type		=addslashes($_POST["customer_type"]);
			

			
			$lastaction = "Update Customer";

			$res = $db->query("SELECT * FROM customer WHERE customer_full_name = '$customer_full_name' AND customer_id != $id");
			if (mysqli_num_rows($res)>0) {
				$error= "خطأ الاسم مكرر";
				$State=false;
				$Validator['is_success'] = $State;
				$Validator['data'] = $error;
				echo json_encode($Validator);
				exit;
			}

			$update_qry = "UPDATE customer SET  customer_full_name = '$customer_full_name', customer_phone='$customer_phone', customer_phone2='$customer_phone2', customer_address='$customer_address', customer_email='$customer_email', customer_job_title='$customer_job_title',customer_type='$customer_type',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE customer_id = $id";


			$res = $db->query($update_qry);
			if ($res) {
				$error= "تمت عملية التحديث بنجاح";
				$State=true;
				$Validator['is_success'] = $State;
				$Validator['data'] = $error;
				echo json_encode($Validator);
				exit;
			}
			else{
				$error= "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
				$State=false;
				$Validator['is_success'] = $State;
				$Validator['data'] = $error;
				echo json_encode($Validator);
				exit;
			}
		}


		if ($_POST['type']=="delete") {
			$id=addslashes($_POST["obj_id"]);
			$reg_date = date("Y-m-d h:i:s", time());
			$lastaction = "Delete Customer";

			$res = $db->query("SELECT * FROM invoice WHERE customer_id_fk = '$id' AND is_deleted=0");
			if (mysqli_num_rows($res)>0) {
				
				echo "لا يمكن حذف هذا الزبون فلديه وصولات بيع باسمه";
				exit;
			}

			$res = $db->query("SELECT * FROM capital_withdraw WHERE gived_to_id_fk = '$id' AND is_deleted=0");
			if (mysqli_num_rows($res)>0) {
				
				echo "لا يمكن حذف الزبون فلديه قرض";
				exit;
			}

			$res = $db->query("SELECT * FROM payments WHERE customer_id_fk = '$id' AND is_deleted=0");
			if (mysqli_num_rows($res)>0) {
				
				echo "لا يمكن حذف الزبون فلديه دفوعات";
				exit;
			}

	      	$res = $db->query("UPDATE customer SET is_deleted = 1 ,deleted_at = '$reg_date',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE customer_id=$id");
	     	if ($res){
	     		echo 1;
	     		exit;
	     	}
	      	else{
		      	echo "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
		      	exit;
	     	}
		}

		if ($_POST['type'] == "create") {
            $customer_full_name	=addslashes($_POST["customer_full_name"]);
            $customer_email		=addslashes($_POST["customer_email"]);
            $customer_phone		=addslashes($_POST["customer_phone"]);
            $customer_phone2	=addslashes($_POST["customer_phone2"]);
            $customer_address	=addslashes($_POST["customer_address"]);
            $customer_job_title	=addslashes($_POST["customer_job_title"]);
            $customer_type		=addslashes($_POST["customer_type"]);

						$res = $db->query("SELECT * FROM customer WHERE customer_full_name = '$customer_full_name' AND is_deleted=0");
						if (mysqli_num_rows($res)>0) {
							$error= "خطأ الاسم مكرر";
							$State=false;
							$Validator['is_success'] = $State;
							$Validator['data'] = $error;
							echo json_encode($Validator);
							exit;
						}else{
							
							$delete = 0;
							$reg_date = date("Y-m-d h:i:s", time());
							$lastaction = "Create New Customer";

						$sql ="INSERT INTO customer(customer_full_name,customer_email,customer_phone,customer_phone2,customer_address,customer_job_title,customer_type,created_by,last_action,last_action_by)
						VALUES('$customer_full_name','$customer_email','$customer_phone','$customer_phone2','$customer_address','$customer_job_title','$customer_type','".$_SESSION['user_id']."','$lastaction','".$_SESSION['user_id']."')";
						$res = $db->query($sql);
							if ($res) {
								$error= "تمت عملية الاضافة بنجاح";
								$State=true;
								$Validator['is_success'] = $State;
								$Validator['data'] = $error;
								echo json_encode($Validator);
								exit;
							}
							else{
								$error= "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
								$State=false;
								$Validator['is_success'] = $State;
								$Validator['data'] = $error;
								echo json_encode($Validator);
								exit;
							}
						}

		}
	}
	else{
		header("Location:../");
		exit;
	}
?>

