<?php	
	require_once("../includes/config.php");
	$ac = new DbQuery();
    $ac->checkLogin();
    if(isset($_POST) && $_POST['action']=='get_product_name' )
	{
	   $row = false;
	    if( isset($_POST['pro_name']) && !empty($_POST['pro_name']) ){
	       
	        $pro_name = trim($_POST['pro_name']);
	        $product = (( isset($_POST['product']) && !empty($_POST['product']) )?$_POST['product']:array());
	        
	        
	        /****** POS DB Integration**********/
            define('DB_SERVER','localhost');
            define('DB_USER','pos');
            define('DB_PASS' ,'##1Samir##');
            define('DB_NAME', 'pos');
            $con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
        
        	// Check connection
        	if (mysqli_connect_errno())
        	{
        		echo "Failed to connect to MySQL: " . mysqli_connect_error();
        	}
        	
        	/********** Fetch Products Rows ***************/
        	$products_query='SELECT id, name FROM `products` where is_inactive=0 AND name LIKE "%'.$pro_name.'%" ';
        	$products_result = $con->query($products_query);
        	if(!$products_result) throw new exception(sprintf("Invalid query : %s", $products_query));
            
            $products_rows = array();
            if($products_result->num_rows > 0){
                
               $products_rows = $products_result->fetch_all(MYSQLI_ASSOC); //faster
            }
            $products_html = '';
            if($products_rows){
                foreach($products_rows as $products_row){
                    if(!in_array($products_row['id'],$product)){
                        $products_html .= '<p class="select-product" data-id="'.$products_row['id'].'">'.$products_row['name'].'</p>';
                    }
                }
            }
            
            echo $products_html;
            die;
	    }else{
	        echo false;
	        die;
	    }
	}
    if(isset($_POST) && $_POST['action']=='get_product' )
	{
	   $row = false;
	    if( isset($_POST['pro_name']) && !empty($_POST['pro_name']) ){
	        $pro_name = trim($_POST['pro_name']);
	        
	        
	        /****** POS DB Integration**********/
            define('DB_SERVER','localhost');
            define('DB_USER','pos');
            define('DB_PASS' ,'##1Samir##');
            define('DB_NAME', 'pos');
            $con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
        
        	// Check connection
        	if (mysqli_connect_errno())
        	{
        		echo "Failed to connect to MySQL: " . mysqli_connect_error();
        	}
        	
        	/********** Fetch Products Rows ***************/
        	$products_query='SELECT products.name as name, products.id as id, variations.sell_price_inc_tax as price FROM `products` join variations on products.id=variations.product_id where products.is_inactive=0 AND products.id='.$pro_name;
        	$products_result = $con->query($products_query);
        	if(!$products_result) throw new exception(sprintf("Invalid query : %s", $products_query));
            
            $products_rows = array();
            if($products_result->num_rows > 0){
               $products_rows = $products_result->fetch_all(MYSQLI_ASSOC); //faster
            }
            $products_html = '';
            if($products_rows){
                foreach($products_rows as $products_row){
                    $products_html .= '
                    <tr class="product" data-id="'.$products_row['id'].'">
                         <input type="hidden" name="po['.$products_row['id'].'][product_id]" value="'.$products_row['id'].'">
                        <input type="hidden" name="po['.$products_row['id'].'][name]" value="'.$products_row['name'].'">
                        <input type="hidden" name="po['.$products_row['id'].'][price]" value="'.number_format($products_row['price'], 2).'">
                        <td>'.$products_row['name'].'</td>
                        <td><input type="number" name="po['.$products_row['id'].'][quantity]" value="1" min="1" class="quantity" data-id="'.$products_row['id'].'"></td>
                        <td class="subtotal" data-default="'.number_format($products_row['price'], 2).'" data-id="'.$products_row['id'].'">'.number_format($products_row['price'], 2).'</td>
                        <td><a data-toggle="tooltip" title="Delete" href="javascript:void(0);" class="btn system-red-float-btn remove_product" data-id="'.$products_row['id'].'" data-original-title="Delete"><i class="fa fa-trash"></i></a></td>
                    </tr>';
                }
            }
            
            echo $products_html;
            die;
	    }else{
	        echo false;
	    }
	}
	if(isset($_POST) && $_POST['action']=='save_po_req' )
	{
	    $row = false;
	    $id = '';
	    if(isset($_POST['po'])){
	       
				 $params['table'] = 'po_req';
				 $params['field']['customer'] = $_POST['customer'];
				 $params['field']['sale_date'] = $_POST['sale_date'];
				 $params['field']['amount'] = $_POST['amount'];
				 $params['field']['payment_method'] = $_POST['payment_method'];
				 $params['field']['quantity'] = $_POST['quantity'];
				 
	            if(isset($_POST['id']) && !empty($_POST['id']))
				{
				    $params['where']['ID'] = $_POST['id'];
				    $id = $_POST['id'];
					$row = $ac->update($params);
				}
				else
				{
					$row = $ac->insert($params,'ID');
					$id = $row;
				}
				
	        $param = $params = array();
	        foreach($_POST['po'] as $key=> $value){
	            $param = array(	
					'table' => 'po_manage_req',
					'get'   =>'*',
					'where' => array('product_id'=> $key, 'po_req_id'=> $id),
					'whereOperator' => array('0'=> 'AND')
				);

				$select = $ac->select($param,'get_row');
				 $params['table'] = 'po_manage_req';
				 $params['field']['po_req_id'] = $id;
				 $params['field']['product_id'] = $value['product_id'];
				 $params['field']['name'] = $value['name'];
				 $params['field']['quantity'] = $value['quantity'];
				 $params['field']['price'] = $value['price'];
	            if($select)
				{
				    $params['where']['ID'] = $select['ID'];
					$row = $ac->update($params);
				}
				else
				{
					$row = $ac->insert($params);
				}
	        }
	        
	        if($row){
			$_SESSION['success'] = $ac->getMessage('SUC_MSG');
			header('location:'.ROOT.'po-requests.php');
			die();
    		}
    		else{
    		    $_SESSION['failed'] = $ac->getMessage('INS_ERR_MSG');
    			header('location:'.ROOT.'po-requests.php');
    			die();
    		}
	    }
		else{
		    $_SESSION['failed'] = $ac->getMessage('INS_ERR_MSG');
			header('location:'.$_SERVER['HTTP_REFERER']);
			die();
		}
	}
	if(isset($_POST) && $_POST['action']=='delete_po_product' )
	{
	    $param = array(	
		  'table' => 'po_manage_req',
		  'get'   =>'*',
		  'where' => array('product_id'=>$_POST['product_id'],'po_req_id'=>$_POST['po_req_id']),
		  'whereOperator'=> array('0' => 'AND'),
		);
		
		$select = $ac->select($param,'get_row');
		if($select){
		    
    		$params = array(	
    		  'table' => 'po_manage_req',
    		  'where' => array('ID'=>$select['ID']),
    		);
    		$row = $ac->delete($params);
    		if($row)
    		{
    		     $paramss['table'] = 'po_req';
				 $paramss['field']['amount'] = $_POST['amount'];
				 $paramss['field']['quantity'] = $_POST['quantity'];
				 
	            if(isset($_POST['po_req_id']) && !empty($_POST['po_req_id']))
				{
				    $paramss['where']['ID'] = $_POST['po_req_id'];
					$rows = $ac->update($paramss);
				}
				if($rows){
        		    echo true;
        		    die;
				}else{
				    echo false;
    		        die;
				}
    		}
    		else
    		{
    		    echo false;
    		    die;
    		}
		}
		else
    	{
    		echo false;
    		die;
    	}
	}
	if(isset($_POST) && $_POST['action']=='execute_po' ){
	    
	    define('DB_SERVER','localhost');
        define('DB_USER','pos');
        define('DB_PASS' ,'##1Samir##');
        define('DB_NAME', 'pos');
        $con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
    
    	// Check connection
    	if (mysqli_connect_errno())
    	{
    		echo "Failed to connect to MySQL: " . mysqli_connect_error();
    	}
	
	     $param = array(	
		  'table' => 'sell',
		  'get'   =>'*',
		  'where' => array('view'=>0),
		  'other' => 'ORDER BY ID DESC'
		);
		
		$select = $ac->select($param,'get_data');
		$count = 0;
		$data = '';
		if($select){
		    
		    
		    foreach($select as $val){
		        $params = array();
		     $params = array(	
    		  'table' => 'po_req',
    		  'get'   =>'name, vendor, product, PO_MANAGE_REQ.created_date as created_at',
    		  'joinTable' => array(
    							array('table'=>'po_manage_req',
    								    'join'=>'INNER',
    									'firstTable'=>'PO_REQ.ID',
    									'secondTable'=>'PO_MANAGE_REQ.po_req_id'
									),
									array('table'=>'product',
    								    'join'=>'INNER',
    									'firstTable'=>'PO_MANAGE_REQ.product_id',
    									'secondTable'=>'PRODUCT.product'
									)
								),
    		  'where' => array('PO_REQ.ID'=>$val['calculated_data'], 'status'=>0),
    		  'whereOperator'=>array(0=>'AND'),
    		);
    		
    		$selects = $ac->select($params,'get_data');
    		
    		if($selects){
    		    $count = count($selects);
    		    foreach($selects as $value){
    		        /********** Fetch Vendor Rows ***************/
                	$contacts_query='SELECT * FROM `contacts` where type="supplier" and business_id=1 and id='.$value['vendor'];
                	$contacts_result = $con->query($contacts_query);
                	if(!$contacts_result) throw new exception(sprintf("Invalid query : %s", $contacts_query));
                    
                    $contacts_rows = array();
                    if($contacts_result->num_rows <= 0){
                        echo "no users found !";
                    }
                    else{
                
                        $contacts_rows = $contacts_result->fetch_all(MYSQLI_ASSOC); //faster 
                    }
                    $name = '';
                    if($contacts_rows){
                        foreach($contacts_rows as $contacts_row){
                            $name = $contacts_row['name'];
                        }
                    }
    		       $data .= '
    		       <a href="'.ROOT.'view.php?id='.$ac->mcEncrypt($value['vendor']).'&supplier='.$ac->mcEncrypt($name).'" class="notifi__item">
						<div class="bg-c1 img-cir img-40">
							<i class="zmdi zmdi-email"></i>
						</div>
						<div class="content">
							<p>'.$value['name'].'</p> 
							<span class="date">'.date("M d, Y H:i", strtotime($value['created_at'])).'</span>
						</div>
					</a>
    		       ';
    		    }
    		}
		        $paramss = array();
    		    $paramss['table'] = 'po_req';
				$paramss['field']['status'] = 1;
				$paramss['where']['ID'] = $val['calculated_data'];
				$ac->update($paramss);
				
		    }
		}
		
	    if($count>0){
			echo json_encode(array('count'=>$count,'data'=>$data));
			die;
		}else{
			echo false;
			die;
		}
	}
	if(isset($_POST) && $_POST['action']=='bulk_execute_po' ){
	    
	    define('DB_SERVER','localhost');
        define('DB_USER','pos');
        define('DB_PASS' ,'##1Samir##');
        define('DB_NAME', 'pos');
        $con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
    
    	// Check connection
    	if (mysqli_connect_errno())
    	{
    		echo "Failed to connect to MySQL: " . mysqli_connect_error();
    	}
	
	     $param = array(	
		  'table' => 'sell',
		  'get'   =>'*',
		  'where' => array('view'=>0),
		  'other' => 'ORDER BY ID DESC'
		);
		
		$select = $ac->select($param,'get_data');
		$count = 0;
		$data = '';
		$vender_id = array();
		if($select){
		    
		    
		    foreach($select as $val){
		        $params = array();
		     $params = array(	
    		  'table' => 'po_req',
    		  'get'   =>'name, vendor, product, PO_MANAGE_REQ.created_date as created_at',
    		  'joinTable' => array(
    							array('table'=>'po_manage_req',
    								    'join'=>'INNER',
    									'firstTable'=>'PO_REQ.ID',
    									'secondTable'=>'PO_MANAGE_REQ.po_req_id'
									),
									array('table'=>'product',
    								    'join'=>'INNER',
    									'firstTable'=>'PO_MANAGE_REQ.product_id',
    									'secondTable'=>'PRODUCT.product'
									)
								),
    		  'where' => array('PO_REQ.ID'=>$val['calculated_data'], 'status'=>1),
    		  'whereOperator'=>array(0=>'AND'),
    		);
    		
    		$selects = $ac->select($params,'get_data');
    		
        		if($selects){
        		    $count = count($selects);
        		    foreach($selects as $value){
        		        /********** Fetch Vendor Rows ***************/
                    	$contacts_query='SELECT * FROM `contacts` where type="supplier" and business_id=1 and id='.$value['vendor'];
                    	$contacts_result = $con->query($contacts_query);
                    	if(!$contacts_result) throw new exception(sprintf("Invalid query : %s", $contacts_query));
                        
                        $contacts_rows = array();
                        if($contacts_result->num_rows <= 0){
                            echo "no users found !";
                        }
                        else{
                    
                            $contacts_rows = $contacts_result->fetch_all(MYSQLI_ASSOC); //faster 
                        }
                        $name = '';
                        if($contacts_rows){
                            foreach($contacts_rows as $contacts_row){
                                $name = $contacts_row['name'];
                            }
                        }
        		       $data .= '
        		       <a href="'.ROOT.'view.php?id='.$ac->mcEncrypt($value['vendor']).'&supplier='.$ac->mcEncrypt($name).'" class="notifi__item">
    						<div class="bg-c1 img-cir img-40">
    							<i class="zmdi zmdi-email"></i>
    						</div>
    						<div class="content">
    							<p>'.$value['name'].'</p> 
    							<span class="date">'.date("M d, Y H:i", strtotime($value['created_at'])).'</span>
    						</div>
    					</a>
        		       ';
        		       $vender_id[] = $value['vendor'];
        		    }
        		}
				
		    }
		}
		
	    if($count>0){
			echo json_encode(array('count'=>$count,'data'=>$data, 'vender_id' => $vender_id));
			die;
		}else{
			echo false;
			die;
		}
	}
	
	if(isset($_POST) && $_POST['action']=='remove_alert_count' ){
    
    
         $param = array(	
    	  'table' => 'sell',
    	  'get'   =>  '*',
    	  'where' => array('view'=>0),
    	  'other' => 'ORDER BY ID DESC'
    	);
    	
    	$select = $ac->select($param,'get_data');
    	$count = 0;
    	$result = '';
    	if($select){
    	    //print_r($select);
    	    foreach($select as $key => $val){
    	        $paramss = array();
    		    $paramss['table'] = 'sell';
    			$paramss['field']['view'] = 1;
    			$paramss['where']['ID'] = $val['ID'];
    			
    			$result = $ac->update($paramss);
    	    }

			
			if($result){
			    echo true;
			    die;
			}else{
			    echo false;
			    die;
			}
				
    	}
    }
    
    if(isset($_POST) && $_POST['action']=='add_vendor_executed' ){
    
    
         $param = array(	
    	  'table' => 'product',
    	  'get'   =>  '*',
    	  'where' => array('vendor'=> $_POST['vendor_executed'])
    	);
    	
    	$select = $ac->select($param,'get_data');
    	$count = 0;
    	$result = '';
    	if($select){
    	    //print_r($select);
    	    foreach($select as $selects){
    	                $params = array(	
        					'table' => 'po_manage_req',
        					'get'   =>' SUM(PO_MANAGE_REQ.quantity) as quantity, product_id, name, SUM(price) as price, po_req_id',
        					'joinTable' => array(
    										array('table'=>'po_req',
    												'join'=>'INNER',
    												'firstTable'=>'PO_MANAGE_REQ.po_req_id',
    												'secondTable'=>'PO_REQ.ID'
											)
										),
        					'where' => array('product_id'=> $selects['product'], 'status'=> '1', 'vendor_executed'=> '0'),
        					'whereOperator' => array('0'=>'and', '1'=>'and'),
        					'other' =>'GROUP BY product_id',
        				);
        
        			$products_rows = $ac->select($params,'get_data');
        			if($products_rows){
                        foreach($products_rows as $products_row){
                            $paramss = array();
                		    $paramss['table'] = 'po_req';
                			$paramss['field']['vendor_executed'] = 1;
                			$paramss['where']['ID'] = $products_row['po_req_id'];
                			
                			$result = $ac->update($paramss);
                        }
        			}
    	    }

			
			if($result){
			    echo true;
			    die;
			}else{
			    echo false;
			    die;
			}
				
    	}
    }
    
     if(isset($_POST) && $_POST['action']=='supplier_view' ){
         
         $param = array(	
    	  'table' => 'product',
    	  'get'   =>  '*',
    	  'where' => array('vendor'=> $_POST['supplier_id'])
    	);
    	
    	$select = $ac->select($param,'get_data');
    	$count = 0;
    	$result = '';
    	if($select){
    	   
    	    foreach($select as $selects){
    	                $params = array(	
        					'table' => 'po_manage_req',
        					'get'   =>' SUM(PO_MANAGE_REQ.quantity) as quantity, product_id, name, SUM(price) as price, po_req_id',
        					'joinTable' => array(
    										array('table'=>'po_req',
    												'join'=>'INNER',
    												'firstTable'=>'PO_MANAGE_REQ.po_req_id',
    												'secondTable'=>'PO_REQ.ID'
											)
										),
        					'where' => array('product_id'=> $selects['product'], 'status'=> '1', 'vendor_executed'=> '0'),
        					'whereOperator' => array('0'=>'and', '1'=>'and'),
        					'other' =>'GROUP BY product_id',
        				);
        
        			$products_rows = $ac->select($params,'get_data');
        			if($products_rows){
        			    
                        foreach($products_rows as $products_row){
                            $paramss = array();
                		    $paramss['table'] = 'sell';
                			$paramss['field']['view'] = 1;
                			$paramss['where']['calculated_data'] = $products_row['po_req_id'];
                			
                			$result = $ac->update($paramss);
                        }
        			}
    	    }

			
			if($result){
			    echo true;
			    die;
			}else{
			    echo false;
			    die;
			}
				
    	}
    }
?>