<?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']);

if (isset($_POST['type']) || isset($_GET['type'])){
		require("db_connect.php");

		if( isset($_GET['type']) && ($_GET['type'] == "load")){
			// DB table to use
			// show All products for specific category
			$cond = isset($_GET['id'])? ' AND IT.item_type_id='.$_GET['id']:'';
			$table  =  '(
				SELECT
					price_profile_id,
					profile_name,
					profile_description,
					created_at
					
				FROM
					price_profile PP
					
				WHERE
					( PP.is_deleted = 0 '.$cond.') 
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'price_profile_id';
			$columns = array(
			    array( 'db' => 'price_profile_id', 'dt' => 0 ),

			    array( 'db' => 'profile_name', 'dt' => 1 ),
			    array( 'db' => 'profile_description', 'dt' => 2 ),
			    array( 'db' => 'created_at',   'dt' => 3 , 'formatter'=> function($d){
									return date('Y-m-d',strtotime($d));
									 } )
			   
			    
			);
			// 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 price_profile WHERE is_deleted = 0");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['price_profile_id'];
						$result[1]  = $row['profile_name'];
						
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

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

			$user_id = $_POST['obj_id'];

			$res = $db->query("SELECT * FROM product_image WHERE is_deleted=0 AND product_id_fk = '$user_id'");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				    // do what you need.
						$result[0] = $row['image_path'];
						array_push($op,$result);
				}

				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

	

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

			$id 											= $_POST['obj_id'];
			$profile_name							=addslashes($_POST["profile_name"]);
			$profile_description			=addslashes($_POST["profile_description"]);
			
			$lastaction = "Update Profile Price";

			$op  = array('is_success'=>false, 'data' => '');

			

			$res = $db->query("SELECT * FROM price_profile WHERE is_deleted=0 AND profile_name = '$profile_name' AND price_profile_id != '$id'");
			if (mysqli_num_rows($res)>0) {
					$op['is_success'] = false;
					$op['data'] 	  = "خطأ الاسم مكرر";
					echo json_encode($op);
					exit;
			}

			$reg_date = date("Y-m-d h:i:s", time());
			
			$update_qry = "UPDATE price_profile SET  profile_name = '$profile_name',
													 profile_description='$profile_description',
													 last_action='$lastaction',
													 updated_at ='$reg_date',
													 last_action_by='".$_SESSION['user_id']."' 
											   WHERE price_profile_id = $id";


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


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

			$id=addslashes($_POST["obj_id"]);
			$reg_date = date("Y-m-d h:i:s", time());
			$lastaction = "Delete Profile Price";

			$op  = array('is_success'=>false, 'data' => '');

			
			
			$db->autocommit(FALSE); // to rollback insertion if update fail
	  		$res = $db->query("UPDATE price_profile SET is_deleted = 1 ,
	  													deleted_at = '$reg_date',
	  													last_action='$lastaction',
	  													updated_at 	='$reg_date',
	  													last_action_by='".$_SESSION['user_id']."' 
	  											  WHERE price_profile_id=$id");

	    	if ($res){

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

		if ($_POST['type'] == "create") {
     		 $profile_name					=addslashes($_POST["profile_name"]);
			$profile_description	=addslashes($_POST["profile_description"]);
			
			$res = $db->query("SELECT * FROM price_profile WHERE is_deleted=0 AND profile_name = '$profile_name'");
			if (mysqli_num_rows($res)>0) {
					$op['is_success'] = false;
					$op['data'] 	  = "خطأ الاسم مكرر";
					echo json_encode($op);
					exit;
			}

			
				

			$reg_date = date("Y-m-d h:i:s", time());
			$lastaction = "Create New Profile Price";

			$sql ="INSERT INTO price_profile (	profile_name,
												profile_description,
												created_by,
												created_at,
												updated_at,
												last_action,
												last_action_by)
										 VALUES('$profile_name',
										 		'$profile_description',
										 		'".$_SESSION['user_id']."',
										 		'$reg_date',
										 		'$reg_date',
										 		'$lastaction',
										 		'".$_SESSION['user_id']."')";

			$res = $db->query($sql);

			if ($res) {

					$op['is_success'] = true;
					$op['data'] 	  = "تمت عملية الاضافة بنجاح";
					echo json_encode($op);
					exit;
			}
			else{
						$op['is_success'] = false;
						$op['data'] 	  = "حصل خطأ: الرجاء اعادة تحميل الصفحة والمحاولة من جديد";
						echo json_encode($op);
						exit;
			}
			

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