<?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 PPP.price_profile_id_fk='.$_GET['id']:'';
			$table  =  '(
				SELECT
					product_profile_price_id,
					profile_name,
					item_sell_price_per_meter,
					PPP.product_id_fk,
					product_serial_id_fk,
					price_profile_id_fk,
					product_name,
					
					product_code
					
					
					
					
				FROM
					product_profile_price  PPP
					LEFT JOIN price_profile PP ON (PPP.price_profile_id_fk = PP.price_profile_id AND PP.is_deleted=0)
					LEFT JOIN product PR ON (PR.product_id = PPP.product_id_fk AND PR.is_deleted=0)
					
					
				WHERE
					( PPP.is_deleted = 0 '.$cond.') 
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'product_profile_price_id';
			$columns = array(
			    array( 'db' => 'product_profile_price_id', 'dt' => 0 ),
			    array( 'db' => 'product_name', 'dt' => 1 ),
			    array( 'db' => 'product_code', 'dt' => 2 ),
			    array( 'db' => 'item_sell_price_per_meter', 'dt' => 3 ),
			    array( 'db' => 'profile_name', 'dt' => 4 ),
			    array( 'db' => 'product_id_fk', 'dt' => 5 ),
			    array( 'db' => 'price_profile_id_fk', 'dt' => 6 ),
			    // array( 'db' => 'price_profile_id_fk', 'dt' => 7 ),
			    // array( 'db' => 'product_serial_id', 'dt' => 8 ),
			    
			   
			    
			);
			// 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") {

			$Price_id 	= $_POST['PP_ID'];
			$Product_id = $_POST['p_val'];
			
			$res = $db->query("SELECT 	price_profile_id_fk,
										product_profile_price_id,
									  	item_sell_price_per_meter
       
        
								FROM product_profile_price  PR
						        LEFT JOIN product P ON (P.product_id = $Product_id  )
						        WHERE P.category_id_fk=PR.category_id_fk AND PR.price_profile_id_fk =$Price_id  AND PR.is_deleted = 0");

			// $res = $db->query("SELECT *
			// 					FROM product_profile_price  WHERE product_id_fk=$Product_id AND price_profile_id_fk =$Price_id  AND is_deleted = 0");


			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['product_profile_price_id'];
						$result[1]  = $row['item_sell_price_per_meter'];
						// $result[2]  = $row['last_sell_price'];
						
						array_push($op,$result);
				}
				echo json_encode($op);
				exit;
			}else{
				echo 0;
				exit;
			}
		}

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

			
			$Product_id = $_POST['p_val'];
			$Customer_id = $_POST['Cus_ID'];

			$res = $db->query("SELECT item_sell_price_per_unit FROM invoice INV, sell_item S 
								WHERE INV.customer_id_fk ='$Customer_id' AND INV.is_deleted=0 AND S.invoice_id_fk = INV.invoice_id AND S.product_id_fk=$Product_id AND S.is_deleted=0 ORDER BY INV.invoice_id DESC LIMIT 1");
			if ($res) {
				//$row = $res->fetch_all();
				$op  = array();
				while ($row = $res->fetch_assoc()) {
				   
						$result[0]  = $row['item_sell_price_per_unit'];
						// $result[1]  = $row['decorate_price_per_meter'];
						
						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;
			}


			$update_qry = "UPDATE price_profile SET  profile_name = '$profile_name', profile_description='$profile_description',last_action='$lastaction',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']=="save_single") {

			$id 					=	addslashes($_POST["obj_id"]);
			$single_price	=	addslashes($_POST["single_price"]);

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

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

			
			if ($single_price<=0) {
				$op['is_success'] = false;
				$op['data'] 	  = "الرجاء ادخال سعر للمادة اكبر من الصفر!";
				echo json_encode($op);
				exit;
			}


			

			

			

	  		$res = $db->query("UPDATE product_profile_price SET item_sell_price_per_meter = '$single_price' ,last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE product_profile_price_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") {
     	
     		$price_profile_id_fk			=	addslashes($_POST["price_profile_id_fk"]);
			$create_type							=	addslashes($_POST["create_type"]);
			$price_profile_id_fk_copy	=	addslashes($_POST["price_profile_id_fk_copy"]);
			$increase_decrease				=	addslashes($_POST["increase_decrease"]);
			$abs_percent							=	addslashes($_POST["abs_percent"]);
			$price										=	addslashes($_POST["price"]);
			
			
			
			$operation_in_de ='';
			if($increase_decrease == 0){
				$operation_in_de =' + ';
			}elseif($increase_decrease == 1){
				$operation_in_de =' - ';
			}else{
				$op['is_success'] = false;
				$op['data'] 	  = "الرجاء قم بتحديد العملية هل زيادة ام نقصان!!";
				echo json_encode($op);
				exit;
			}

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

				if($create_type ==1){
						$operation_qry ='';
						if($abs_percent == 0){
							$operation_qry = ' ( P2.item_sell_price_per_meter '. $operation_in_de. $price . ' )';
						}elseif($abs_percent == 1){
							$operation_qry = ' ( P2.item_sell_price_per_meter '. $operation_in_de. $price . ' * P2.item_sell_price_per_meter / 100 )';
						}else{
							$op['is_success'] = false;
							$op['data'] 	  = "الرجاء قم بتحديد العملية هل قيمة مطلقة ام نسبة مؤية!!";
							echo json_encode($op);
							exit;
						}

					$sql ="UPDATE product_profile_price P1, (select item_sell_price_per_meter,product_id_fk from product_profile_price PPP where PPP.price_profile_id_fk = '$price_profile_id_fk_copy' AND PPP.is_deleted=0 ) P2 
					SET P1.item_sell_price_per_meter = ".$operation_qry." ,P1.created_by = '".$_SESSION['user_id']."',P1.last_action='$lastaction',P1.last_action_by='".$_SESSION['user_id']."' WHERE P1.price_profile_id_fk='$price_profile_id_fk' AND P1.product_id_fk = P2.product_id_fk";

				}elseif($create_type =='' || $create_type ==NULL){

					$operation_qry ='';
					if($abs_percent == 0){
						$operation_qry = ' ( item_sell_price_per_meter '. $operation_in_de. $price . ' )';
					}elseif($abs_percent == 1){
						$operation_qry = ' ( item_sell_price_per_meter '. $operation_in_de. $price . ' * item_sell_price_per_meter / 100 )';
					}else{
							$op['is_success'] = false;
							$op['data'] 	  = "الرجاء قم بتحديد العملية هل قيمة مطلقة ام نسبة مؤية!!";
							echo json_encode($op);
							exit;
					}

					$sql ="UPDATE product_profile_price SET item_sell_price_per_meter = ".$operation_qry." ,created_by = '".$_SESSION['user_id']."',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE price_profile_id_fk=$price_profile_id_fk";
				}
				
				// echo $sql;
				// exit;

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

		}

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

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

				$sql ="INSERT  INTO product_profile_price (product_id_fk,price_profile_id_fk) select product_id, price_profile_id from price_profile PP, product P WHERE NOT EXISTS(select product_id_fk, price_profile_id_fk from product_profile_price PPP where PP.price_profile_id =PPP.price_profile_id_fk AND PP.is_deleted=0 AND P.is_deleted=0 AND P.product_id =PPP.product_id_fk) AND PP.is_deleted=0 AND P.is_deleted=0 AND P.product_type = 'PVC'";

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