<?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 ($_POST['type']=="get_sell_date") {

			//$user_id = $_POST['cusid'];

			$res = $db->query("SELECT *
				FROM sell_item WHERE is_deleted = 0 ORDER BY created_at ASC LIMIT 1");
			if ($res) {				
				$op  = array();
				while ($row = $res->fetch_assoc()) {				   
						$result[0]  = $row['created_at'];						
						//array_push($op,$result);
						$dStart = new DateTime($row['created_at']);
				}

				$res = $db->query("SELECT *
				FROM sell_item WHERE is_deleted = 0 ORDER BY created_at DESC LIMIT 1");
				while ($row = $res->fetch_assoc()) {				   
						//$result[1]  = $row['created_at'];	
						$dEnd 			= new DateTime($row['created_at']);			
						//array_push($op,$result);
				}

				$dDiff = $dStart->diff($dEnd);
   			//echo $dDiff->format('%R'); // use for point out relation: smaller/greater
				$months = $dDiff->m;
				$day = $dDiff->d;
   			if($months == 0){
   					$op[0] = date('Y-m-d',strtotime($result[0]));
   			}else{
   				for($i=0;$i<$months;$i++){
   					$op[$i] = date('Y-m-d', strtotime("+".$i." months", strtotime($result[0])));
   				}
   			}
   			

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

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

			$cond_y = (isset($_POST['yy']) && $_POST['yy'] !='not')? ' AND YEAR(P.purchase_date)  	='.$_POST['yy']:'';
			$cond_m = (isset($_POST['mm']) && $_POST['mm'] !='not')? ' AND MONTH(P.purchase_date) 	='.$_POST['mm']:'';
			$cond_d = (isset($_POST['dd']) && $_POST['dd'] !='not')? ' AND DAY(P.purchase_date) 	='.$_POST['dd']:'';

			$cond   = $cond_y . ' ' . $cond_m . ' ' . $cond_d;


			$res = $db->query("SELECT					
									sum(cost_expenses * purchase_quantity) AS total_price
					
					 			FROM purchase_item PP
					 	 		
					 	 		LEFT JOIN purchase P ON (PP.purchase_id_fk = P.purchase_id)
					 	 
								WHERE 
								(P.is_deleted = 0 AND PP.is_deleted = 0 AND P.purchase_transaction='Purchase' $cond ) "); // all type
			
			if ($res) {				
				$op  = array();
				$row = $res->fetch_assoc();

				$result['total_price']  			= $row['total_price'];
					
				

				array_push($op,$result);

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


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

			$cond_y = (isset($_POST['yy']) && $_POST['yy'] !='not')? ' AND YEAR(E.expenses_date)  	='.$_POST['yy']:'';
			$cond_m = (isset($_POST['mm']) && $_POST['mm'] !='not')? ' AND MONTH(E.expenses_date) 	='.$_POST['mm']:'';
			$cond_d = (isset($_POST['dd']) && $_POST['dd'] !='not')? ' AND DAY(E.expenses_date) 	='.$_POST['dd']:'';

			$cond   = $cond_y . ' ' . $cond_m . ' ' . $cond_d;


			$res = $db->query("SELECT sum(expenses_unit_price )  AS total_price
								FROM expenses E 

								WHERE E.is_deleted =0  $cond "); // all type
			
			if ($res) {				
				$op  = array();
				$row = $res->fetch_assoc();

				$result['total_price']  			= $row['total_price'];
					
				

				array_push($op,$result);

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


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

			$cond_y = (isset($_POST['yy']) && $_POST['yy'] !='not')? ' AND YEAR(SF.date_of_add)  	='.$_POST['yy']:'';
			$cond_m = (isset($_POST['mm']) && $_POST['mm'] !='not')? ' AND MONTH(SF.date_of_add) 	='.$_POST['mm']:'';
			$cond_d = (isset($_POST['dd']) && $_POST['dd'] !='not')? ' AND DAY(SF.date_of_add) 	='.$_POST['dd']:'';

			$cond   = $cond_y . ' ' . $cond_m . ' ' . $cond_d;


			$res = $db->query("SELECT
									
									
									
									(SELECT sum(safe_amount) FROM safe SF  WHERE SF.is_deleted =0 AND transaction_type =1 $cond) AS total_amount,

									(SELECT sum(safe_amount) FROM safe SF  WHERE SF.is_deleted =0 AND transaction_type =2 $cond) AS total_subtract
								FROM
									safe SF
									
									
								WHERE
									SF.is_deleted = 0 $cond ");

			
			if ($res) {				
				$op  = array();
				$row = $res->fetch_assoc();

				$result['total_amount_in']  			= $row['total_amount'];
				$result['total_amount_out']  			= $row['total_subtract'];
				$result['total_avilable']  				= $row['total_amount'] - $row['total_subtract'];
					
				

				array_push($op,$result);

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


		

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

			$cond_y = (isset($_POST['yy']) && $_POST['yy'] !='not')? ' AND YEAR(PSK.transaction_date)  	='.$_POST['yy']:'';
			$cond_m = (isset($_POST['mm']) && $_POST['mm'] !='not')? ' AND MONTH(PSK.transaction_date) 	='.$_POST['mm']:'';
			$cond_d = (isset($_POST['dd']) && $_POST['dd'] !='not')? ' AND DAY(PSK.transaction_date) 	='.$_POST['dd']:'';

			$cond   = $cond_y . ' ' . $cond_m . ' ' . $cond_d;

			
			
			
			
			$cond_sub = $cond ;


			$res = $db->query('SELECT
					
					

							(

								(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
								        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Purchase"  '.$cond_sub.'),0)
								) 
								+
								(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
								        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Initial"  '.$cond_sub.'),0)
								) 
								+
								(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
								        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Return"  '.$cond_sub.'),0)
								) 
								+

								(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
								        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Moved In"  '.$cond_sub.'),0)
								) 
								-
								(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
								        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Invoice"  '.$cond_sub.'),0)
								) 
								-
								(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
								        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Damage"  '.$cond_sub.'),0)
								) 

								
								-
								(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
								        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Moved Out"  '.$cond_sub.'),0)
								) 
								-
								(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
								        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Used"  '.$cond_sub.'),0)
								) 
								-
								(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
								        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Offer"  '.$cond_sub.'),0)
								) 
								-
								(COALESCE((SELECT sum(recieved_quantity) FROM product_stock PSK  	
								        	WHERE PSK.product_id_fk = P.product_id AND  PSK.is_deleted =0 AND PSK.stock_id_fk = S.stock_id AND PSK.stock_transaction = "Expired"  '.$cond_sub.'),0)
								) 


							) AS on_hand_quantity,

							(SELECT cost_expenses FROM `purchase_item` PI WHERE P.product_id =PI.product_id_fk ORDER BY purchase_item_id DESC LIMIT 1) as cost_expenses,

							stock_id,
							stock_name,
							product_id,
							product_name,
							P.sell_price
							
						FROM
							product  P
							LEFT JOIN stock S ON (S.is_deleted=0)
							
							
						WHERE
							( P.is_deleted = 0 '.$cond.')
					');

			if ($res) {
				$op  = array('total_on_hand'=>0,'total_cost'=>0, 'total_sell'=>0);

				$total_on_hand 	= 0;
				$total_cost 	= 0;
				$total_sell 	= 0;

				while ($row = $res->fetch_assoc()) {
				    
				    $total_on_hand 	= $total_on_hand + $row['on_hand_quantity'];
				    $total_cost 	= $total_cost + ($row['on_hand_quantity'] * $row['cost_expenses']);
				    $total_sell 	= $total_sell + ($row['on_hand_quantity']* $row['sell_price']);

						
				}

				$op['total_on_hand']=$total_on_hand;
				$op['total_cost']=$total_cost;
				$op['total_sell']=$total_sell;

				echo json_encode($op);
				exit;
			}else{
				echo $db->error;
				exit;
			}
		}


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

			$cond_y = (isset($_POST['yy']) && $_POST['yy'] !='not')? ' AND YEAR(C.date_of_add)  	='.$_POST['yy']:'';
			$cond_m = (isset($_POST['mm']) && $_POST['mm'] !='not')? ' AND MONTH(C.date_of_add) 	='.$_POST['mm']:'';
			$cond_d = (isset($_POST['dd']) && $_POST['dd'] !='not')? ' AND DAY(C.date_of_add) 	='.$_POST['dd']:'';

			$cond   = $cond_y . ' ' . $cond_m . ' ' . $cond_d;


			$res = $db->query("SELECT sum(capital_amount) AS total_price 
							   FROM capital C  
							   WHERE C.is_deleted =0 AND C.capital_transaction='Add Capital Amount'   $cond "); // all type
			
			if ($res) {				
				$op  = array();
				$row = $res->fetch_assoc();

				$result['total_price']  			= $row['total_price'];
					
				

				array_push($op,$result);

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


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

			$cond_y = (isset($_POST['yy']) && $_POST['yy'] !='not')? ' AND YEAR(C.date_of_add)  	='.$_POST['yy']:'';
			$cond_m = (isset($_POST['mm']) && $_POST['mm'] !='not')? ' AND MONTH(C.date_of_add) 	='.$_POST['mm']:'';
			$cond_d = (isset($_POST['dd']) && $_POST['dd'] !='not')? ' AND DAY(C.date_of_add) 	='.$_POST['dd']:'';

			$cond   = $cond_y . ' ' . $cond_m . ' ' . $cond_d;


			$res = $db->query("SELECT sum(capital_amount) AS total_price 
							   FROM capital C  
							   WHERE C.is_deleted =0 AND C.capital_transaction='Withdraw'   $cond  "); // all type
			
			if ($res) {				
				$op  = array();
				$row = $res->fetch_assoc();

				$result['total_price']  			= $row['total_price'];
					
				

				array_push($op,$result);

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


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

			$cond_y = (isset($_POST['yy']) && $_POST['yy'] !='not')? ' AND YEAR(Inv.invoice_date)  	='.$_POST['yy']:'';
			$cond_m = (isset($_POST['mm']) && $_POST['mm'] !='not')? ' AND MONTH(Inv.invoice_date) 	='.$_POST['mm']:'';
			$cond_d = (isset($_POST['dd']) && $_POST['dd'] !='not')? ' AND DAY(Inv.invoice_date) 	='.$_POST['dd']:'';

			$cond   = $cond_y . ' ' . $cond_m . ' ' . $cond_d;


			$res = $db->query("SELECT
					



									sum((invoice_total_net_balance)) AS total_price
											
						
								 FROM
								 invoice Inv
								 
								 
							WHERE
								(Inv.is_deleted = 0 AND Inv.invoice_status <3 AND Inv.is_returned =0  AND Inv.invoice_transaction ='Invoice' $cond )"); // all type
			
			if ($res) {				
				$op  = array();
				$row = $res->fetch_assoc();

				$result['total_price']  			= $row['total_price'];
					
				

				array_push($op,$result);

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


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

			$cond_y = (isset($_POST['yy']) && $_POST['yy'] !='not')? ' AND YEAR(PY.paid_date)  	='.$_POST['yy']:'';
			$cond_m = (isset($_POST['mm']) && $_POST['mm'] !='not')? ' AND MONTH(PY.paid_date) 	='.$_POST['mm']:'';
			$cond_d = (isset($_POST['dd']) && $_POST['dd'] !='not')? ' AND DAY(PY.paid_date) 	='.$_POST['dd']:'';

			$cond   = $cond_y . ' ' . $cond_m . ' ' . $cond_d;


			$res = $db->query("
								SELECT sum(paid_amount) AS total_price  
								FROM payments PY  
								WHERE PY.is_deleted =0 AND PY.payment_transaction ='Payment' $cond

							  "); // all type

			$res2 = $db->query("
								SELECT sum(paid_amount) AS total_price  
								FROM payments PY  
								WHERE PY.is_deleted =0 AND PY.payment_transaction ='Return' $cond

							  "); // all type
			
			if ($res && $res2) {				
				$op  = array();
				$row = $res->fetch_assoc();
				$row2 = $res2->fetch_assoc();

				$result['total_price']  			= $row['total_price'] - $row2['total_price'];
					
				

				array_push($op,$result);

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

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

			$cond_y = (isset($_POST['yy']) && $_POST['yy'] !='not')? ' AND YEAR(Inv.invoice_date)  	='.$_POST['yy']:'';
			$cond_m = (isset($_POST['mm']) && $_POST['mm'] !='not')? ' AND MONTH(Inv.invoice_date) 	='.$_POST['mm']:'';
			$cond_d = (isset($_POST['dd']) && $_POST['dd'] !='not')? ' AND DAY(Inv.invoice_date) 	='.$_POST['dd']:'';

			$cond   = $cond_y . ' ' . $cond_m . ' ' . $cond_d;



			$cond_y1 = (isset($_POST['yy']) && $_POST['yy'] !='not')? ' AND YEAR(PY.paid_date)  	='.$_POST['yy']:'';
			$cond_m1 = (isset($_POST['mm']) && $_POST['mm'] !='not')? ' AND MONTH(PY.paid_date) 	='.$_POST['mm']:'';
			$cond_d1 = (isset($_POST['dd']) && $_POST['dd'] !='not')? ' AND DAY(PY.paid_date) 	='.$_POST['dd']:'';

			$cond1   = $cond_y1 . ' ' . $cond_m1 . ' ' . $cond_d1;




			$res = $db->query("SELECT
					

									(
                    
					                    COALESCE((SELECT sum(paid_amount) AS total_price  
													FROM payments PY  
													WHERE PY.is_deleted =0 AND PY.payment_transaction ='Payment' $cond1),0)
					                        +
					                    COALESCE((SELECT sum(paid_amount) AS total_price  
													FROM payments PY  
													WHERE PY.is_deleted =0 AND PY.payment_transaction ='Discount' $cond1),0)    
					                        -
					                      COALESCE((SELECT sum(paid_amount) AS total_price  
													FROM payments PY  
													WHERE PY.is_deleted =0 AND PY.payment_transaction ='Return' $cond1),0)  
					                    
					                    ) AS total_paid,


									sum(invoice_total_net_balance) AS total_price
											
						
								 FROM
								 invoice Inv
								 
								 
							WHERE
								(Inv.is_deleted = 0  AND Inv.invoice_transaction ='Invoice' $cond )"); // all type
			
			if ($res) {				
				$op  = array();
				$row = $res->fetch_assoc();

				$result['total_price']  			= $row['total_price'] - $row['total_paid'];
					
				

				array_push($op,$result);

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





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

			if(isset($_POST['yy']) && $_POST['yy'] !='not'){

				$yr_id = $_POST['yy'] - 2014;
				$cond_y = ' AND WH1.year_id_fk  	='.$yr_id;
			}else{
				$cond_y = '';
			}

			
			$cond_m = (isset($_POST['mm']) && $_POST['mm'] !='not')? ' AND WH1.month_id_fk 	='.$_POST['mm']:'';
			$cond_d = (isset($_POST['dd']) && $_POST['dd'] !='not')? ' AND WH1.day_id_fk 	='.$_POST['dd']:'';

			$cond   = $cond_y . ' ' . $cond_m . ' ' . $cond_d;


			$res = $db->query("SELECT
					
									sum(hours) AS total_price
								FROM work_hours WH1  	
					        	WHERE   WH1.is_deleted =0  AND WH1.hour_transaction = 'Loan' 

								 $cond "); // all type
			// echo $cond;
			if ($res) {				
				$op  = array();
				$row = $res->fetch_assoc();

				$result['total_price']  			= $row['total_price'];
					
				

				array_push($op,$result);

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



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

			if(isset($_POST['yy']) && $_POST['yy'] !='not'){

				$yr_id = $_POST['yy'] - 2014;
				$cond_y = ' AND WH1.year_id_fk  	='.$yr_id;
			}else{
				$cond_y = '';
			}

			
			$cond_m = (isset($_POST['mm']) && $_POST['mm'] !='not')? ' AND WH1.month_id_fk 	='.$_POST['mm']:'';
			$cond_d = (isset($_POST['dd']) && $_POST['dd'] !='not')? ' AND WH1.day_id_fk 	='.$_POST['dd']:'';

			$cond   = $cond_y . ' ' . $cond_m . ' ' . $cond_d;


			$res = $db->query("SELECT
					
									sum(hours) AS total_price
								FROM work_hours WH1  	
					        	WHERE   WH1.is_deleted =0  AND WH1.hour_transaction = 'Refund' 

								 $cond "); // all type
			// echo $cond;
			if ($res) {				
				$op  = array();
				$row = $res->fetch_assoc();

				$result['total_price']  			= $row['total_price'];
					
				

				array_push($op,$result);

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



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

			if(isset($_POST['yy']) && $_POST['yy'] !='not'){

				$yr_id = $_POST['yy'] - 2014;
				$cond_y = ' AND WH1.year_id_fk  	='.$yr_id;
			}else{
				$cond_y = '';
			}

			
			$cond_m = (isset($_POST['mm']) && $_POST['mm'] !='not')? ' AND WH1.month_id_fk 	='.$_POST['mm']:'';
			$cond_d = (isset($_POST['dd']) && $_POST['dd'] !='not')? ' AND WH1.day_id_fk 	='.$_POST['dd']:'';

			$cond   = $cond_y . ' ' . $cond_m . ' ' . $cond_d;


			$res = $db->query("SELECT
					
									sum(hours) AS total_price
								FROM work_hours WH1  	
					        	WHERE   WH1.is_deleted =0  AND WH1.hour_transaction = 'Reward' 

								 $cond "); // all type
			// echo $cond;
			if ($res) {				
				$op  = array();
				$row = $res->fetch_assoc();

				$result['total_price']  			= $row['total_price'];
					
				

				array_push($op,$result);

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


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

			if(isset($_POST['yy']) && $_POST['yy'] !='not'){

				$yr_id = $_POST['yy'] - 2014;
				$cond_y = ' AND WH1.year_id_fk  	='.$yr_id;
			}else{
				$cond_y = '';
			}

			
			$cond_m = (isset($_POST['mm']) && $_POST['mm'] !='not')? ' AND WH1.month_id_fk 	='.$_POST['mm']:'';
			$cond_d = (isset($_POST['dd']) && $_POST['dd'] !='not')? ' AND WH1.day_id_fk 	='.$_POST['dd']:'';

			$cond   = $cond_y . ' ' . $cond_m . ' ' . $cond_d;


			$res = $db->query("SELECT
					
									sum(hours) AS total_price
								FROM work_hours WH1  	
					        	WHERE   WH1.is_deleted =0  AND WH1.hour_transaction = 'Penalty' 

								 $cond "); // all type
			// echo $cond;
			if ($res) {				
				$op  = array();
				$row = $res->fetch_assoc();

				$result['total_price']  			= $row['total_price'];
					
				

				array_push($op,$result);

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



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

			$cond_y = (isset($_POST['yy']) && $_POST['yy'] !='not')? ' AND YEAR(Inv.invoice_date)  	='.$_POST['yy']:'';
			$cond_m = (isset($_POST['mm']) && $_POST['mm'] !='not')? ' AND MONTH(Inv.invoice_date) 	='.$_POST['mm']:'';
			$cond_d = (isset($_POST['dd']) && $_POST['dd'] !='not')? ' AND DAY(Inv.invoice_date) 	='.$_POST['dd']:'';

			$cond   = $cond_y . ' ' . $cond_m . ' ' . $cond_d;


			

			$resI = $db->query("SELECT
					

									sum((invoice_total_net_balance)) AS total_price
											
						
								 FROM
								 invoice Inv
								 
								 
							WHERE
								(Inv.is_deleted = 0 AND Inv.invoice_status <3 AND Inv.is_returned =0  AND Inv.invoice_transaction ='Invoice' $cond )"); // all type

			$resR = $db->query("SELECT
					

									sum((invoice_total_net_balance)) AS total_invoice_return
											
						
								 FROM
								 invoice Inv
								 
								 
							WHERE
								(Inv.is_deleted = 0 AND Inv.invoice_status <3 AND Inv.is_returned =1  AND Inv.invoice_transaction ='Invoice' $cond )"); // all type

			$resIC = $db->query("SELECT
					



									sum((sell_item_quantity * item_buy_price_per_unit) ) AS total_cost
											
						
								 FROM
								 invoice Inv

								 LEFT JOIN sell_item SI ON (SI.invoice_id_fk = Inv.invoice_id)
								 
								 
							WHERE
								(Inv.is_deleted = 0 AND Inv.invoice_status <3 AND Inv.is_returned =0 AND Inv.invoice_transaction ='Invoice' $cond )"); // all type

			$resRC = $db->query("SELECT
					



									sum((sell_item_quantity * item_buy_price_per_unit) ) AS total_return_cost
											
						
								 FROM
								 invoice Inv

								 LEFT JOIN sell_item SI ON (SI.invoice_id_fk = Inv.invoice_id)
								 
								 
							WHERE
								(Inv.is_deleted = 0 AND Inv.invoice_status <3 AND Inv.is_returned =1 AND Inv.invoice_transaction ='Invoice' $cond )"); // all type


			$cond_y = (isset($_POST['yy']) && $_POST['yy'] !='not')? ' AND YEAR(E.expenses_date)  	='.$_POST['yy']:'';
			$cond_m = (isset($_POST['mm']) && $_POST['mm'] !='not')? ' AND MONTH(E.expenses_date) 	='.$_POST['mm']:'';
			$cond_d = (isset($_POST['dd']) && $_POST['dd'] !='not')? ' AND DAY(E.expenses_date) 	='.$_POST['dd']:'';

			$cond   = $cond_y . ' ' . $cond_m . ' ' . $cond_d;


			$resE = $db->query("SELECT sum(expenses_unit_price )  AS total_expenses
								FROM expenses E 

								WHERE E.is_deleted =0  $cond "); // all type
			
			


			if ($resI && $resIC && $resR  && $resRC && $resE) {				
				$op  	= array();
				
				$rowI 	= $resI->fetch_assoc();

				$rowR 	= $resR->fetch_assoc();
				$rowIC 	= $resIC->fetch_assoc();
				$rowRC 	= $resRC->fetch_assoc();
				
				$rowE 	= $resE->fetch_assoc();

				$result['a1']  				= $rowI['total_price'] - $rowIC['total_cost'];
				$result['a2']  				= -1* $rowR['total_invoice_return'] - $rowRC['total_return_cost'];
				$result['total_price']  	= $result['a1'] - $result['a2'] - $rowE['total_expenses'];

				// $result['total_price']  			= $row['total_cost'] - $row1['total_return_cost'] - $row2['total_price'];
					
				

				array_push($op,$result);

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



		if ($_POST['type']=="get_profit_expenses") {
			$current_year = date("Y");
			$res = $db->query("SELECT sum(purchase_quantity * buy_price) as total_expenses_price , YEAR(Pr.purchase_date) As Years, MONTH(Pr.purchase_date) AS Months  FROM
					 		purchase Pr, product P
					 		LEFT JOIN category C ON (P.category_id_fk=C.category_id) WHERE
							 Pr.product_id_fk=P.product_id AND Pr.is_deleted = 0  AND C.category_type =1 AND YEAR(Pr.purchase_date) = $current_year GROUP BY YEAR(Pr.purchase_date), MONTH(Pr.purchase_date) ORDER BY YEAR(Pr.purchase_date) DESC, MONTH(Pr.purchase_date) ASC
						"); // all type

			$res1 = $db->query("				
						SELECT sum((sell_unit_price - sell_avg_price) * sell_quantity -sell_discount )  as total_profit, YEAR(sell_date) As Years, MONTH(sell_date) AS Months from sell_item where is_deleted=0 AND YEAR(sell_date) = $current_year GROUP BY YEAR(sell_date), MONTH(sell_date) ORDER BY YEAR(sell_date) DESC, MONTH(sell_date) ASC
						"); // all type
			if ($res && $res1) {				
				$op  = array('is_success'=>false, 'profit' => array(), 'expenses'=>array());
				
				while ($row = $res->fetch_assoc()) {				   
						$result[0]  = $row['total_expenses_price'];	
						$result[1]  = $row['Years'];	
						$result[2]  = $row['Months'];						
						array_push($op['expenses'],$result);
				}

				while ($row = $res1->fetch_assoc()) {				   
						$result[0]  = $row['total_profit'];	
						$result[1]  = $row['Years'];	
						$result[2]  = $row['Months'];						
						array_push($op['profit'],$result);
				}
				
				$op['is_success'] = true;
				echo json_encode($op);
				exit;
			}else{
				
				echo 0;
				exit;
			}
		}

	
		if ($_POST['type']=="get_daily_sells") {
			$reg_date = date("Y-m-d", time());

			$res = $db->query("SELECT S.*, P.product_name  from sell_item S LEFT JOIN product P ON (S.product_id_fk = P.product_id) where S.is_deleted = 0 AND S.sell_date >= '$reg_date' "); // all type
			if ($res) {				
				$op  = array();


				while ($row = $res->fetch_assoc()) {				   
						$result[0]  = $row['item_sell_price_per_unit'];
						$result[1]  = $row['sell_item_quantity'];
						$result[2]  = $row['sell_item_barcode'];

						$dt = new DateTime($row['sell_date']);
						$time = $dt->format('h:i A');

						$result[3]  = $time;				
						$result[4]  = $row['product_name'];				
						array_push($op,$result);
				}

				echo json_encode($op);
				exit;
			}else{
				
				echo $db->error;
				exit;
			}
		}


		

		if ($_POST['type']=="get_daily_invoice") {
			
			$reg_date = date("Y-m-d", time());
			// $reg_date = date( '2018-05-01');

			$res = $db->query("SELECT

									invoice_number,
									invoice_date,
									Inv.actual_discount,
									invoice_total_net_balance,
									customer_id_fk,
									customer_full_name AS name,
									customer_email AS email,
									customer_phone AS phone,
									invoice_transaction,
									Inv.created_at,  
						

									(invoice_total_net_balance) AS final_price
											
						
								FROM
								 invoice Inv
								 LEFT JOIN customer Cus ON (Inv.customer_id_fk=Cus.customer_id) 
								 
							WHERE
								(Inv.is_deleted = 0  AND Inv.invoice_status <3  AND Inv.invoice_date >= '$reg_date') ORDER BY invoice_id DESC

					 "); // all type
			if ($res) {				
				$op  = array();

				
				while ($row = $res->fetch_assoc()) {				   
						$result['invoice_number']  		= $row['invoice_number'];
						$result['final_price']  		= $row['final_price'];
						$result['actual_discount']  	= $row['actual_discount'];

						$dt 							= new DateTime($row['created_at']);
						$time 							= $dt->format('h:i A');

						$result['time']  				= $time;				
						$result['name']  				= $row['name'];
						$result['email']  				= $row['email'];
						$result['phone']  				= $row['phone'];
						$result['customer_id_fk']  		= $row['customer_id_fk'];
						$result['invoice_transaction']  = $row['invoice_transaction'];					
						array_push($op,$result);
				}

				echo json_encode($op);
				exit;
			}else{
				
				echo $db->error;
				exit;
			}
		}


		if ($_POST['type']=="get_daily_expenses") {
			$reg_date = date("Y-m-d", time());
			// $reg_date = date( '2018-05-01');

			

			$res = $db->query("SELECT 
										expenses_name, 
										expenses_date,
										bill_number,
										attach_bill,
										created_at,
										(expenses_unit_price ) as total_expenses
						    	from expenses 
						    	WHERE expenses_date >= '$reg_date' AND is_deleted=0 "); // all type
			if ($res) {				
				$op  = array();
	
				while ($row = $res->fetch_assoc()) {				   
						$result['expenses_name']  	= $row['expenses_name'];
						$result['bill_number']  	= $row['bill_number'];
						$result['attach_bill']  	= $row['attach_bill'];

						$dt 						= new DateTime($row['created_at']);
						$time 						= $dt->format('h:i A');

						$result['time']  			= $time;
						$result['total_expenses']  	= $row['total_expenses'];

						array_push($op,$result);
				}

				echo json_encode($op);
				exit;
			}else{
				
				echo $db->error;
				exit;
			}
		}


		if ($_POST['type']=="get_purchase") {
			$reg_date = date("Y-m-d", time());
			

			$cond_y = (isset($_POST['yy']) && $_POST['yy'] !='not')? ' AND YEAR(P.purchase_date)  	='.$_POST['yy']:'';
			$cond_m = (isset($_POST['mm']) && $_POST['mm'] !='not')? ' AND MONTH(P.purchase_date) 	='.$_POST['mm']:'';
			$cond_d = (isset($_POST['dd']) && $_POST['dd'] !='not')? ' AND DAY(P.purchase_date) 	='.$_POST['dd']:'';

			$cond   = $cond_y . ' ' . $cond_m . ' ' . $cond_d;

			if(strlen($cond) < 15){

				$limits = 'LIMIT 15';

			}else{
				$limits = '';

			}

			
			$res = $db->query("SELECT
					purchase_id,
					purchase_number,
					purchase_auto_number,
					purchase_date,
					purchase_note,
					purchase_sequence_no,
					purchase_transaction,
					supplier_id_fk,
					supplier_full_name,
					P.stock_id_fk,
					purchase_item_id,
					purchase_quantity,
					
					stock_name,
					P.created_at,
					sum(cost_expenses * purchase_quantity) AS total_price
					
					 FROM
					 	 purchase P
					 	 LEFT JOIN stock S ON (S.stock_id = P.stock_id_fk)
					 	 LEFT JOIN suppliers SU ON (SU.supplier_id = P.supplier_id_fk)
					 	 , purchase_item PP 
					WHERE 
					(PP.purchase_id_fk = P.purchase_id AND P.is_deleted = 0 AND PP.is_deleted = 0 	$cond  ) GROUP BY PP.purchase_id_fk ORDER BY purchase_id DESC  $limits "); // all type
			if ($res) {				
				$op  = array();
	
				while ($row = $res->fetch_assoc()) {				   
					$result['purchase_auto_number'] 	= $row['purchase_auto_number'];
					$result['supplier_full_name']  		= $row['supplier_full_name'];
					$result['purchase_transaction']  	= $row['purchase_transaction'];

					$dt 								= new DateTime($row['purchase_date']);
					$time 								= $dt->format('Y-m-d');

					$result['time']  					= $time;
					$result['total_price']  			= $row['total_price'];
													
					array_push($op,$result);
				}

				echo json_encode($op);
				exit;
			}else{
				
				echo $db->error;
				exit;
			}
		}




		if ($_POST['type']=="get_pie_order") {
			
			$reg_date = date("Y", time());
			

			$cond_y = (isset($_POST['yy']) && $_POST['yy'] !='not')? ' AND YEAR(Inv.invoice_date)  	='.$_POST['yy']:'';
			

			$cond   = $cond_y ;

			if(strlen($cond) < 15){

				$cond = ' AND YEAR(Inv.invoice_date)  ='.$reg_date;
			
				$yyr 	= 	$reg_date;

			}else{
				$yyr 	= 	$_POST['yy'];

			}

			
			$res = $db->query("SELECT

									count(*) AS no_of_orders,
									MONTH(Inv.invoice_date) AS montn_no,
									MONTHNAME(Inv.invoice_date) AS month_name
											
						
								FROM
								 invoice Inv
								
								 
							WHERE
								(Inv.is_deleted = 0  $cond )  GROUP BY MONTH(Inv.invoice_date)

					 "); // all type

			
			if ($res) {				
				$op  = array();
	
				while ($row = $res->fetch_assoc()) {				   
					$result['no_of_orders'] 			= $row['no_of_orders'];
					$result['montn_no']  				= $row['montn_no'];
					$result['month_name']  				= $row['month_name'];
					$result['year']  					= $yyr;								
					array_push($op,$result);
				}

				echo json_encode($op);
				exit;
			}else{
				
				echo $db->error;
				exit;
			}
		}



		if ($_POST['type']=="get_pie_sells") {
			
			$reg_date = date("Y", time());
			

			$cond_y = (isset($_POST['yy']) && $_POST['yy'] !='not')? ' AND YEAR(Inv.invoice_date)  	='.$_POST['yy']:'';
			

			$cond   = $cond_y ;

			if(strlen($cond) < 15){

				$cond = ' AND YEAR(Inv.invoice_date)  ='.$reg_date;
			
				$yyr 	= 	$reg_date;

			}else{
				$yyr 	= 	$_POST['yy'];

			}

			
			$res = $db->query("SELECT

									count(*) AS no_of_orders,
									MONTH(Inv.invoice_date) AS montn_no,
									MONTHNAME(Inv.invoice_date) AS month_name,

									sum(invoice_total_net_balance) AS final_price
											
						
								FROM
								 invoice Inv
								
								 
							WHERE
								(Inv.is_deleted = 0 AND Inv.invoice_status <3  $cond )  GROUP BY MONTH(Inv.invoice_date)

					 "); // all type

			// echo $cond;
			if ($res) {				
				$op  = array();
	
				while ($row = $res->fetch_assoc()) {				   
					$result['no_of_orders'] 			= $row['no_of_orders'];
					$result['montn_no']  				= $row['montn_no'];
					$result['month_name']  				= $row['month_name'];
					$result['final_price']  			= round($row['final_price'],2);
					$result['year']  					= $yyr;								
					array_push($op,$result);
				}

				echo json_encode($op);
				exit;
			}else{
				
				echo $db->error;
				exit;
			}
		}




		if ($_POST['type']=="get_pie_expenses") {
			
			$reg_date = date("Y", time());
			

			$cond_y = (isset($_POST['yy']) && $_POST['yy'] !='not')? ' AND YEAR(E.expenses_date)  	='.$_POST['yy']:'';
			

			$cond   = $cond_y ;

			if(strlen($cond) < 15){

				$cond = ' AND YEAR(E.expenses_date)  ='.$reg_date;
			
				$yyr 	= 	$reg_date;

			}else{
				$yyr 	= 	$_POST['yy'];

			}

			
			$res = $db->query("SELECT

									count(*) AS no_of_orders,
									MONTH(E.expenses_date) AS montn_no,
									MONTHNAME(E.expenses_date) AS month_name,

									sum(expenses_unit_price ) AS final_price
											
						
								FROM
								 expenses E
								
								 
							WHERE
								(E.is_deleted = 0  $cond )  GROUP BY MONTH(E.expenses_date)

					 "); // all type

			// echo $cond;
			if ($res) {				
				$op  = array();
	
				while ($row = $res->fetch_assoc()) {				   
					$result['no_of_orders'] 			= $row['no_of_orders'];
					$result['montn_no']  				= $row['montn_no'];
					$result['month_name']  				= $row['month_name'];
					$result['final_price']  			= round($row['final_price'],2);
					$result['year']  					= $yyr;								
					array_push($op,$result);
				}

				echo json_encode($op);
				exit;
			}else{
				
				echo $db->error;
				exit;
			}
		}



		if ($_POST['type']=="get_pie_purchase") {
			
			$reg_date = date("Y", time());
			

			$cond_y = (isset($_POST['yy']) && $_POST['yy'] !='not')? ' AND YEAR(P.purchase_date)  	='.$_POST['yy']:'';
			

			$cond   = $cond_y ;

			if(strlen($cond) < 15){

				$cond = ' AND YEAR(P.purchase_date)  ='.$reg_date;
			
				$yyr 	= 	$reg_date;

			}else{
				$yyr 	= 	$_POST['yy'];

			}

			
			$res = $db->query("SELECT

									count(*) AS no_of_orders,
									MONTH(P.purchase_date) AS montn_no,
									MONTHNAME(P.purchase_date) AS month_name,

									sum(cost_expenses * purchase_quantity) AS final_price
											
						
								FROM
								 purchase P , purchase_item PP
								
								 
							WHERE
								(PP.purchase_id_fk = P.purchase_id AND P.is_deleted = 0 AND PP.is_deleted = 0  $cond )  GROUP BY MONTH(P.purchase_date)

					 "); // all type

			// echo $cond;
			if ($res) {				
				$op  = array();
	
				while ($row = $res->fetch_assoc()) {				   
					$result['no_of_orders'] 			= $row['no_of_orders'];
					$result['montn_no']  				= $row['montn_no'];
					$result['month_name']  				= $row['month_name'];
					$result['final_price']  			= round($row['final_price'],2);
					$result['year']  					= $yyr;								
					array_push($op,$result);
				}

				echo json_encode($op);
				exit;
			}else{
				
				echo $db->error;
				exit;
			}
		}





		if ($_POST['type']=="get_user_sells") {
			$reg_date  =  date("Y-m-d", time());
			$yesterday = date('Y-m-d',strtotime("-1 days"));

			$res = $db->query("Select *   from  (SELECT sum(sell_item_quantity) as qty , sum(sell_item_quantity * item_sell_price_per_unit) AS total_price,sell_item.created_by,sell_date, staff.username, staff.full_name,profile_img  FROM sell_item LEFT JOIN staff ON (staff.staff_id = sell_item.created_by) where sell_item.is_deleted = 0 AND sell_date >= '$reg_date' GROUP By sell_item.created_by)  AS tmp ORDER By qty DESC
			 "); // all type

			$res1 = $db->query("Select *   from  (SELECT sum(sell_item_quantity) as qty , sum(sell_item_quantity * item_sell_price_per_unit) AS total_price,sell_item.created_by,sell_date, staff.username, staff.full_name,profile_img  FROM sell_item LEFT JOIN staff ON (staff.staff_id = sell_item.created_by) where sell_item.is_deleted = 0 AND sell_date >= '$yesterday' AND sell_date < '$reg_date' GROUP By sell_item.created_by)  AS tmp ORDER By qty DESC
			 "); // all type
			if ($res) {				
				$op  = array();


				while ($row = $res->fetch_assoc()) {				   
						$result[0]  = $row['qty'];
						$result[1]  = $row['total_price'];
						$result[2]  = $row['full_name'];
						$result[3]  = $row['username'];
						$result[4]  = $row['profile_img'];
						$result[5]  = '0';					
						array_push($op,$result);
				}

				while ($row = $res1->fetch_assoc()) {				   
						$result[0]  = $row['qty'];
						$result[1]  = $row['total_price'];
						$result[2]  = $row['full_name'];
						$result[3]  = $row['username'];
						$result[4]  = $row['profile_img'];
						$result[5]  = '1';					
						array_push($op,$result);
				}

				echo json_encode($op);
				exit;
			}else{
				
				echo $db->error;
				exit;
			}
		}










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

			//$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 AND C.category_type=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;
			}
		}



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