<?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_once "db_connect.php";

		if( isset($_GET['type']) && ($_GET['type'] == "load")){
			
			// show All products for specific category
			$cond = isset($_GET['id'])? ' AND E.expenses_group_id_fk='.$_GET['id']:'';
			$table  =  '(
				SELECT
					category_id,
					category,
					category_description,
					created_at,
					is_deleted,
					(SELECT COUNT(product_id)  FROM product P WHERE P.is_deleted=0 AND P.category_id_fk = C.category_id) AS product_count
				FROM
					category C
					
					
				WHERE
					( C.is_deleted = 0 ) 
			) AS ALLTBL';
			
			$primaryKey = 'category_id';
			$columns =  array(
				  			  	array( 'db' => 'category_id', 'dt' => 0 ),
			    				array( 'db' => 'category', 'dt' => 1 ),
			    				array( 'db' => 'category_description',  'dt' => 2 ),
			    				array( 'db' => 'product_count',  'dt' => 3 ),
			    				array( 'db' => 'created_at',   'dt' => 4 , 'formatter'=> function($d){
									return date('Y-m-d',strtotime($d));
									 } ),
								array( 'db' => 'is_deleted',   'dt' => 5 )
			);
			// 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 category WHERE is_deleted = 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_description'];
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}


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

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

			$res = $db->query('SELECT
									category_id,
									
									category,
									category_description,
									item_sell_price_per_meter,
									price_profile_id_fk
									

									FROM
										category M
										LEFT JOIN product_profile_price P ON (P.category_id_fk = M.category_id)
									WHERE
										( M.is_deleted = 0 AND M.category_id = '.$id.') 

								');
			if ($res) {
				
				
				while ($row = $res->fetch_assoc()) {
				   
					$result['category_id']  			= $row['category_id'];
					$result['category']  				= $row['category'];
					$result['category_description']  	= $row['category_description'];
					$result['item_sell_price_per_meter']  = $row['item_sell_price_per_meter'];
					$result['price_profile_id_fk']  	= $row['price_profile_id_fk'];
						
						
						
					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'] == "update") {

			$id 		= $_POST['obj_id'];
			$name 		=addslashes($_POST["name"]);
			$cat_desc 	=addslashes($_POST["category_description"]);

			$profile_1	=addslashes($_POST["profile_1"]);
			$profile_2	=addslashes($_POST["profile_2"]);
			$profile_3	=addslashes($_POST["profile_3"]);
			$profile_4	=addslashes($_POST["profile_4"]);
			$profile_5	=addslashes($_POST["profile_5"]);


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

			$res = $db->query("SELECT * FROM category WHERE is_deleted=0 AND category = '$name' AND category_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());


			$lastaction = "Update Category";
			$update_qry = "UPDATE category SET  category = '$name',
												category_description='$cat_desc',
												last_action='$lastaction',
												updated_at='$reg_date',
												last_action_by='".$_SESSION['user_id']."' 
										  WHERE category_id = $id";


			$res = $db->query($update_qry);
			if ($res) {
					$lastaction = "Update Prices";
					
					$update_qryP1 = "UPDATE product_profile_price 
											SET  	item_sell_price_per_meter = '$profile_1',
												
													last_action='$lastaction',
													updated_at='$reg_date',
													last_action_by='".$_SESSION['user_id']."' 
										  WHERE category_id_fk = $id AND price_profile_id_fk = 1";
					
					$res = $db->query($update_qryP1);

					$update_qryP2 = "UPDATE product_profile_price 
											SET  	item_sell_price_per_meter = '$profile_2',
												
													last_action='$lastaction',
													updated_at='$reg_date',
													last_action_by='".$_SESSION['user_id']."' 
										  WHERE category_id_fk = $id AND price_profile_id_fk = 2";
					
					$res = $db->query($update_qryP2);

					$update_qryP3 = "UPDATE product_profile_price 
											SET  	item_sell_price_per_meter = '$profile_3',
												
													last_action='$lastaction',
													updated_at='$reg_date',
													last_action_by='".$_SESSION['user_id']."' 
										  WHERE category_id_fk = $id AND price_profile_id_fk = 3";
					
					$res = $db->query($update_qryP3);

					$update_qryP4 = "UPDATE product_profile_price 
											SET  	item_sell_price_per_meter = '$profile_4',
												
													last_action='$lastaction',
													updated_at='$reg_date',
													last_action_by='".$_SESSION['user_id']."' 
										  WHERE category_id_fk = $id AND price_profile_id_fk = 4";
					
					$res = $db->query($update_qryP4);

					$update_qryP5 = "UPDATE product_profile_price 
											SET  	item_sell_price_per_meter = '$profile_5',
												
													last_action='$lastaction',
													updated_at='$reg_date',
													last_action_by='".$_SESSION['user_id']."' 
										  WHERE category_id_fk = $id AND price_profile_id_fk = 5";
					
					$res = $db->query($update_qryP5);


					$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 Category";


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

			$res = $db->query("SELECT * FROM product WHERE is_deleted=0 AND category_id_fk = '$id'");
			if (mysqli_num_rows($res)>0) {
			
				$op['is_success'] = false;
				$op['data'] 	  = "لا يمكن حذف هذه الفئة فهناك مواد مرتبطة بها";
				echo json_encode($op);
				exit;
			}

			

			


	      $res = $db->query("UPDATE category SET is_deleted = 1 ,
	      										 deleted_at = '$reg_date',
	      										 last_action='$lastaction',
	      										 updated_at='$reg_date',
	      										 last_action_by='".$_SESSION['user_id']."' 
	      								   WHERE category_id=$id");
	     	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'] == "create") {

            $name=addslashes($_POST["name"]);

			$res = $db->query("SELECT * FROM category WHERE category = '$name' AND is_deleted=0");
			
			if (mysqli_num_rows($res)>0) {
				$op['is_success'] = false;
				$op['data'] 	  = "خطأ اسم الفئة مكرر";
				echo json_encode($op);
				exit;
			}
			
			$category_description=addslashes($_POST["category_description"]);

			$profile_1	=addslashes($_POST["profile_1"]);
			$profile_2	=addslashes($_POST["profile_2"]);
			$profile_3	=addslashes($_POST["profile_3"]);
			$profile_4	=addslashes($_POST["profile_4"]);
			$profile_5	=addslashes($_POST["profile_5"]);

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

			$sql ="INSERT INTO category (	category,
										 	category_description,
											created_by,
											created_at,
										    updated_at,
											last_action,
											last_action_by)
									VALUES( '$name',
											'$category_description',
											'".$_SESSION['user_id']."',
											'$reg_date',
											'$reg_date',
											'$lastaction',
											'".$_SESSION['user_id']."')";
			$res = $db->query($sql);
			if ($res) {

				$category_id = $db->insert_id;

				$sqlP ="INSERT INTO product_profile_price (	
										 					item_sell_price_per_meter,
										 					category_id_fk,
										 					price_profile_id_fk,
															created_by,
															created_at,
														    updated_at,
															last_action,
															last_action_by)
													VALUES( '$profile_1',
															'$category_id',
															'1',
															'".$_SESSION['user_id']."',
															'$reg_date',
															'$reg_date',
															'$lastaction',
															'".$_SESSION['user_id']."'),

															( '$profile_2',
															'$category_id',
															'2',
															'".$_SESSION['user_id']."',
															'$reg_date',
															'$reg_date',
															'$lastaction',
															'".$_SESSION['user_id']."'),

															( '$profile_3',
															'$category_id',
															'3',
															'".$_SESSION['user_id']."',
															'$reg_date',
															'$reg_date',
															'$lastaction',
															'".$_SESSION['user_id']."'),

															( '$profile_4',
															'$category_id',
															'4',
															'".$_SESSION['user_id']."',
															'$reg_date',
															'$reg_date',
															'$lastaction',
															'".$_SESSION['user_id']."'),

															( '$profile_5',
															'$category_id',
															'5',
															'".$_SESSION['user_id']."',
															'$reg_date',
															'$reg_date',
															'$lastaction',
															'".$_SESSION['user_id']."')




															";

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

				$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;
	}
?>

