<?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 E.expenses_group_id_fk='.$_GET['id']:'';
			$table  =  '(
				SELECT
					other_id,
					other_name,
					other_description,
					other_buy_price_per_unit,
					other_note
				FROM
					others 					
					
				WHERE
					(is_deleted = 0 '.$cond.') 
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'other_id';
			$columns = array(
			    array( 'db' => 'other_id', 'dt' => 0 ),
			    array( 'db' => 'other_name', 'dt' => 1 ),
			    array( 'db' => 'other_description', 'dt' => 2 ),
			    array( 'db' => 'other_buy_price_per_unit', 'dt' => 3 ),
			    array( 'db' => 'other_note', 'dt' => 4 ),
			    

			);
			// 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 P.*,C.category,C.category_type,
				(SELECT sum(purchase_quantity) from purchase where purchase.product_id_fk = P.product_id AND purchase.is_deleted=0) as total_quantity,
				(SELECT sum(sell_quantity) from sell_item where sell_item.product_id_fk = P.product_id AND sell_item.is_deleted=0) as sold_quantity,
				(COALESCE((SELECT sum(COALESCE(purchase_quantity, 0)) from purchase where purchase.product_id_fk = P.product_id AND purchase.is_deleted=0),0)  -
					COALESCE((SELECT sum(COALESCE(sell_quantity, 0)) from sell_item where sell_item.product_id_fk = P.product_id AND sell_item.is_deleted=0),0) )  AS Remianed_quantity
				FROM product P, category C WHERE P.category_id_fk=C.category_id AND P.is_deleted = 0");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['product_id'];
						$result[1]  = $row['product'];
						$result[2]  = $row['part_number'];
						$result[3]  = $row['made_in'];
						$result[4]  = $row['sell_price'];
						$result[5]  = $row['sell_price_percentage'];
						$result[6]  = $row['average_price'];
						$result[7]  = $row['category_id_fk'];
						$result[8]  = $row['is_deleted'];
						$result[9]  = $row['created_at'];
						$result[10] = $row['updated_at'];
						$result[11] = $row['deleted_at'];
						$result[12] = $row['created_by'];
						$result[13] = $row['last_action'];
						$result[14] = $row['last_action_by'];
						$result[15] = $row['category'];
						$result[16] = $row['category_type'];
						$result[17] = $row['total_quantity'];
						$result[18] = $row['sold_quantity'];
						$result[19] = $row['Remianed_quantity'];
						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'];
			$other_name					=addslashes($_POST["other_name"]);
			$other_description			=addslashes($_POST["other_description"]);
			$other_buy_price_per_unit	=addslashes($_POST["other_buy_price_per_unit"]);
			$other_note					=addslashes($_POST["other_note"]);
				
			$op  = array('is_success'=>false, 'data' => '');

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


			$lastaction = "Update Others";
			$update_qry = "UPDATE others SET  other_name = '$other_name', other_description='$other_description',other_buy_price_per_unit='$other_buy_price_per_unit',	other_note='$other_note',	last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE other_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 Other";

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

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

	  		$res = $db->query("UPDATE others SET is_deleted = 1 ,deleted_at = '$reg_date',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE other_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") {
	      		$other_name					=addslashes($_POST["other_name"]);
				$other_description			=addslashes($_POST["other_description"]);
				$other_buy_price_per_unit	=addslashes($_POST["other_buy_price_per_unit"]);
				$other_note					=addslashes($_POST["other_note"]);
				
				$res = $db->query("SELECT * FROM others WHERE other_name = '$other_name' AND is_deleted=0");
				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 Other";

				$sql ="INSERT INTO others(other_name,other_description,other_buy_price_per_unit,other_note,created_by,last_action,last_action_by)
				VALUES('$other_name','$other_description','$other_buy_price_per_unit','$other_note','".$_SESSION['user_id']."','$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;
	}
?>
