<?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 = 'suppliers';
			// Table's primary key
			$primaryKey = 'supplier_id';
			$columns =  array(
				  			  	array( 'db' => 'supplier_id', 'dt' => 0 ),
			    				array( 'db' => 'supplier_full_name', 'dt' => 1 ),
			    				array( 'db' => 'supplier_email',  'dt' => 2 ),
			    				array( 'db' => 'supplier_phone',   'dt' => 3 ),
								array( 'db' => 'supplier_address',   'dt' => 4 ),
								array( 'db' => 'supplier_job_title',   'dt' => 5 ),
								array( 'db' => 'supplier_note',   'dt' => 6 ),
								array( 'db' => 'created_at',   'dt' => 7 , 'formatter'=> function($d){
									return date('Y-m-d',strtotime($d));
									 } ),
								array( 'db' => 'supplier_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 suppliers WHERE is_deleted = 0");
			if ($res) {
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				    // do what you need.
						$result[0] = $row['supplier_id'];
						$result[1] = $row['supplier_full_name'];
						$result[2] = $row['supplier_phone'];
						$result[3] = $row['supplier_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 suppliers WHERE is_deleted = 0");
			if ($res) {
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				    // do what you need.
						$result[0] = $row['supplier_id'];
						$result[1] = $row['supplier_full_name'];
						$result[2] = $row['supplier_phone'];
						$result[3] = $row['supplier_email'];
						
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

		

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

			$id 				= $_POST['obj_id'];
			$supplier_full_name	=addslashes($_POST["supplier_full_name"]);
            $supplier_email		=addslashes($_POST["supplier_email"]);
            $supplier_phone		=addslashes($_POST["supplier_phone"]);
            $supplier_phone2	=addslashes($_POST["supplier_phone2"]);
            $supplier_address	=addslashes($_POST["supplier_address"]);
            $supplier_job_title	=addslashes($_POST["supplier_job_title"]);
            $supplier_note		=addslashes($_POST["supplier_note"]);
			

			
			$lastaction = "Update Supplier";

			$res = $db->query("SELECT * FROM suppliers WHERE supplier_full_name = '$supplier_full_name' AND supplier_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 suppliers SET  supplier_full_name = '$supplier_full_name', supplier_phone='$supplier_phone', supplier_phone2='$supplier_phone2', supplier_address='$supplier_address', supplier_email='$supplier_email', supplier_job_title='$supplier_job_title',supplier_note='$supplier_note',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE supplier_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 Supplier";

			$res = $db->query("SELECT * FROM purchase WHERE supplier_id_fk = '$id' AND is_deleted=0");
			if (mysqli_num_rows($res)>0) {
				
				
				$Validator['is_success'] = false;
				$Validator['data'] = "لا يمكن حذف هذا المورد فلديه وصولات شراء باسمه";
				echo json_encode($Validator);
				exit;
			}

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

		if ($_POST['type'] == "create") {
            $supplier_full_name	=addslashes($_POST["supplier_full_name"]);
            $supplier_email		=addslashes($_POST["supplier_email"]);
            $supplier_phone		=addslashes($_POST["supplier_phone"]);
            $supplier_phone2	=addslashes($_POST["supplier_phone2"]);
            $supplier_address	=addslashes($_POST["supplier_address"]);
            $supplier_job_title	=addslashes($_POST["supplier_job_title"]);
            $supplier_note		=addslashes($_POST["supplier_note"]);

			$res = $db->query("SELECT * FROM suppliers WHERE supplier_full_name = '$supplier_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 Supplier";

			$sql ="INSERT INTO suppliers(supplier_full_name,supplier_email,supplier_phone,supplier_phone2,supplier_address,supplier_job_title,supplier_note,created_by,last_action,last_action_by)
			VALUES('$supplier_full_name','$supplier_email','$supplier_phone','$supplier_phone2','$supplier_address','$supplier_job_title','$supplier_note','".$_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;
	}
?>

