<?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 C.customer_type='.$_GET['typ']:'';

			// DB table to use
			$table  =  '(
				SELECT
					customer_id,
					customer_full_name,
					customer_email,
					customer_phone,
					customer_address,
					customer_company,
					allowed_max_money,
					customer_phone2,
					note,
					customer_job_title,
					city_id_fk,
					city_name,
					branch_id_fk,
					branch_name,
					login_count,
					customer_username,
					C.is_deleted
					
				FROM
					customer C

					LEFT JOIN city Cy ON (C.city_id_fk = Cy.city_id)
					LEFT JOIN branch B ON (C.branch_id_fk = B.branch_id)
					
					
				WHERE
					( C.is_deleted <2 '.$cond.' ) 
			) AS ALLTBL';
			// Table's primary key
			$primaryKey = 'customer_id';
			$columns =  array(
				  			  	array( 'db' => 'customer_id', 'dt' => 0 ),
			    				array( 'db' => 'customer_username', 'dt' => 1 ),
			    				array( 'db' => 'customer_full_name',  'dt' => 2 ),
			    				array( 'db' => 'customer_phone',   'dt' => 3 ),
								array( 'db' => 'customer_address',   'dt' => 4 ),
								array( 'db' => 'customer_company',   'dt' => 5 ),
								// array( 'db' => 'allowed_max_money',   'dt' => 6 ,  ),
								// array( 'db' => 'profile_name',   'dt' => 7 ),
								array( 'db' => 'city_name',   'dt' => 6 ),
								// array( 'db' => 'branch_name',   'dt' => 7 ),
								array( 'db' => 'note',   'dt' => 7 ),
								array( 'db' => 'login_count',   'dt' => 8 ),
								array( 'db' => 'is_deleted',   'dt' => 9 ),
								array( 'db' => 'customer_phone2',   'dt' => 10 ),
			    				array( 'db' => 'customer_email',  'dt' => 11 ),


			);
			// SQL server connection information
			$sql_details = array(
			    'user' => $mysql_user,
			    'pass' => $mysql_password,
			    'db'   => $mysql_db,
			    'host' => $mysql_server
			);
			require( 'ssp.php' );
			echo json_encode(
			    SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns ,null, '' )
			);
			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'];
						$result[4] = $row['customer_company'];
						$result[5] = $row['allowed_max_money'];
						$result[6] = $row['branch_id_fk'];
						
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

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

			$id = $_POST['id'];
			
			$op  = array('is_success'=>false, 'data'=>array());

			
			$res = $db->query("SELECT * FROM customer WHERE is_deleted < 2 AND customer_id=$id");
			if ($res) {
				while ($row = $res->fetch_assoc()) {
						$result['customer_id'] 			= $row['customer_id'];
						$result['customer_full_name'] 	= $row['customer_full_name'];
						$result['customer_phone'] 		= $row['customer_phone'];
						$result['customer_email'] 		= $row['customer_email'];
						$result['customer_phone2'] 		= $row['customer_phone2'];
						$result['customer_address'] 		= $row['customer_address'];
						$result['customer_job_title'] 	= $row['customer_job_title'];
						$result['branch_id_fk'] 		= $row['branch_id_fk'];
						$result['city_id_fk'] 		= $row['city_id_fk'];
						$result['customer_username'] 	= $row['customer_username'];
						
						
						
						array_push($op['data'],$result);
				}

				$op['is_success'] = true;
				echo json_encode($op);
				exit;
			}else{
				$op['is_success'] = false;
				$op['data'] = $db->error;
				echo json_encode($op);
				exit;
			}
		}


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

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

			$res = $db->query("SELECT * FROM city WHERE is_deleted = 0 ORDER BY city_id DESC");
			if ($res) {
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				    // do what you need.
						$result[0] = $row['city_id'];
						$result[1] = $row['city_name'];
						
						
						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 ");
			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'];
						$result[4] = $row['customer_company'];
						$result[5] = $row['allowed_max_money'];
						$result[6] = $row['branch_id_fk'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

		if ($_POST['type']=="deactive") {
			$id=addslashes($_POST["obj_id"]);
			$reg_date = date("Y-m-d H:i:s", time());
			$lastaction = "De-Activated User";

			if($_SESSION['profile_type'] != 2 && $_SESSION['profile_type'] != 1){
				$Validator['is_success'] = false;
				$Validator['data'] = "You Are Not Allowed To perform this Action";
				echo json_encode($Validator);
				exit;
			}

			

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




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

			if($_SESSION['profile_type'] != 2 && $_SESSION['profile_type'] != 1){
				$Validator['is_success'] = false;
				$Validator['data'] = "You Are Not Allowed To perform this Action";
				echo json_encode($Validator);
				exit;
			}

	      	$res = $db->query("UPDATE customer SET is_deleted = 0 ,last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE customer_id=$id");
	     	if ($res){
	     		$Validator['is_success'] = true;
				$Validator['data'] = "User has been Activated.";
				echo json_encode($Validator);
				exit;
	     	}
	      	else{
	      		$Validator['is_success'] = false;
				$Validator['data'] = "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
				echo json_encode($Validator);
				exit;
	     	}
		}




		if ($_POST['type']=="change_password") {
			$id 			=		addslashes($_POST["obj_id"]);
			$password 		=		addslashes($_POST["password"]);
      		$repassword 	=		addslashes($_POST["repassword"]);

			$reg_date = date("Y-m-d h:i:s", time());
			$lastaction = "Change User Password";

			if($_SESSION['profile_type'] != 2 && $_SESSION['profile_type'] != 1){
				$Validator['is_success'] = false;
				$Validator['data'] = "You Are Not Allowed To perform this Action";
				echo json_encode($Validator);
				exit;
			}

			if($repassword != $password){
					$error= "Passwords does not match";
					$State=false;
					$Validator['is_success'] = $State;
					$Validator['data'] = $error;
					echo json_encode($Validator);
					exit();
			}

				$password=hash('sha256',$password);
				$password= stripslashes($password);
				$password=mysqli_real_escape_string($db,$password);


		      $res = $db->query("UPDATE customer SET customer_password = '$password' ,last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE customer_id=$id");
		     	if ($res){
		     				$error= "Passwords Successfully Changed";
							$State=true;
							$Validator['is_success'] = $State;
							$Validator['data'] = $error;
							echo json_encode($Validator);
							exit();
		     	}
		      else{
		      				$error= "Some Thing Went Wrong";
							$State=false;
							$Validator['is_success'] = $State;
							$Validator['data'] = $error;
							echo json_encode($Validator);
							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"]);
		    $branch_id_fk 		=addslashes($_POST["branch_id_fk"]);
		    $note 				=addslashes($_POST["note"]);
            $username			=addslashes($_POST["username"]);

            // $price_profile_id_fk=addslashes($_POST["price_profile_id_fk"]);
            // $customer_type		=addslashes($_POST["customer_type"]);
            $customer_company	=addslashes($_POST["customer_company"]);
            $city_id_fk			=addslashes($_POST["city_id_fk"]);
			
			$res = $db->query("SELECT * FROM customer WHERE customer_username = '$username' 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;
			}

			$reg_date = date("Y-m-d h:i:s", time());
			
			$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',
												branch_id_fk		='$branch_id_fk',
												note				='$note',
											 	
											 	customer_company	='$customer_company',
											 	customer_username	='$username',
											 	city_id_fk			='$city_id_fk',
											 	updated_at			='$reg_date',
											 	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("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"]);
		    $branch_id_fk 		=addslashes($_POST["branch_id_fk"]);
		    $note 				=addslashes($_POST["note"]);

            // $price_profile_id_fk=addslashes($_POST["price_profile_id_fk"]);
            $customer_company	=addslashes($_POST["customer_company"]);
            $city_id_fk			=addslashes($_POST["city_id_fk"]);

            $customer_username  =addslashes($_POST["username"]);
            $password			=addslashes($_POST["password"]);
            $repassword			=addslashes($_POST["repassword"]);


            $res = $db->query("SELECT * FROM customer WHERE customer_username = '$customer_username' 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;
			}

			if($repassword != $password){
					$error= "Passwords does not match";
					$State=false;
					$Validator['is_success'] = $State;
					$Validator['data'] = $error;
					echo json_encode($Validator);
					exit();
			}

			$password=hash('sha256',$password);
			$password= stripslashes($password);
			$password=mysqli_real_escape_string($db,$password);
			

			
			$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;
			}
							
			$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_company,
										city_id_fk,
										branch_id_fk,
										note,
										customer_username,
										customer_password,
										created_by,
										created_at,
										updated_at,
										last_action,
										last_action_by)
								VALUES('$customer_full_name',
									   '$customer_email',
									   '$customer_phone',
									   '$customer_phone2',
									   '$customer_address',
									   '$customer_job_title',
									   '$customer_company',
									   '$city_id_fk',
									   '$branch_id_fk',
									   '$note',
									   '$customer_username',
									   '$password',
									   '".$_SESSION['user_id']."',
									   '$reg_date',
									   '$reg_date',
									   '$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;
	}
?>

