<?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
					expenses_id,
					expenses_name,
					expenses_quantity,
					expenses_unit_price,
					expenses_date,
					expenses_usd_rate,
					expenses_currency,
					expenses_note,
					expenses_group_id_fk,
					(expenses_quantity * expenses_unit_price) AS total_price,
					group_name
				FROM
					expenses E
					LEFT JOIN expenses_group EG ON (E.expenses_group_id_fk = EG.expenses_group_id AND EG.is_deleted=0)
					
				WHERE
					( E.is_deleted = 0 '.$cond.') 
			) AS ALLTBL';
			// Table's primary key
			//echo $table;
			$primaryKey = 'expenses_id';
			$columns = array(
			    array( 'db' => 'expenses_id', 'dt' => 0 ),

			    array( 'db' => 'expenses_name', 'dt' => 1 ),
			    array( 'db' => 'expenses_quantity', 'dt' => 2 ),
			    array( 'db' => 'expenses_unit_price', 'dt' => 3 ),
			    array( 'db' => 'total_price', 'dt' => 4 ),
			    array( 'db' => 'expenses_date', 'dt' => 5 ),
			    array( 'db' => 'group_name', 'dt' => 6 ),
			    array( 'db' => 'expenses_note', 'dt' => 7 ),
					array( 'db' => 'expenses_currency', 'dt' => 8 ),
					array( 'db' => 'expenses_group_id_fk', 'dt' => 9 )

			);
			// 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'];
			$expenses_group_id_fk		=addslashes($_POST["expenses_group_id_fk"]);
			$expenses_name					=addslashes($_POST["expenses_name"]);
			$expenses_quantity			=addslashes($_POST["expenses_quantity"]);
			$expenses_unit_price		=addslashes($_POST["expenses_unit_price"]);
			$expenses_currency			=addslashes($_POST["expenses_currency"]);
			$expenses_date					=addslashes($_POST["expenses_date"]);
			$expenses_note					=addslashes($_POST["expenses_note"]);

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

			

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

			

			

					


			$lastaction = "Update Expenses";
			$update_qry = "UPDATE expenses SET  expenses_name = '$expenses_name', expenses_quantity='$expenses_quantity',expenses_unit_price='$expenses_unit_price',	expenses_date='$expenses_date',expenses_currency='$expenses_currency',expenses_note='$expenses_note',expenses_group_id_fk='$expenses_group_id_fk',
										last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE expenses_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 Expenses";

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

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

			

			

  		$res = $db->query("UPDATE expenses SET is_deleted = 1 ,deleted_at = '$reg_date',last_action='$lastaction',last_action_by='".$_SESSION['user_id']."' WHERE expenses_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") {
      		$expenses_group_id_fk		=addslashes($_POST["expenses_group_id_fk"]);
			$expenses_name					=addslashes($_POST["expenses_name"]);
			$expenses_quantity			=addslashes($_POST["expenses_quantity"]);
			$expenses_unit_price		=addslashes($_POST["expenses_unit_price"]);
			$expenses_currency			=addslashes($_POST["expenses_currency"]);
			$expenses_date					=addslashes($_POST["expenses_date"]);
			$expenses_note					=addslashes($_POST["expenses_note"]);

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

			
				$delete = 0;
				if($expenses_date =='' || $expenses_date == NULL){
					$expenses_date = date("Y-m-d", time());
				}

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

				$sql ="INSERT INTO expenses(expenses_name,expenses_quantity,expenses_unit_price,expenses_date,expenses_usd_rate,expenses_currency,expenses_note,expenses_group_id_fk,created_by,last_action,last_action_by)
				VALUES('$expenses_name','$expenses_quantity','$expenses_unit_price','$expenses_date','".$_SESSION['USD_TO_IQD']."','$expenses_currency','$expenses_note','$expenses_group_id_fk','".$_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;
	}
?>
