<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Damage extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->database();
		$this->load->library('session');
		$this->load->model('user_model');
		$this->load->model('master_model');
		$this->load->model('report_model');
		$this->load->model('damage_model');
		
		if(!isset($_SESSION['user_logged'])) {
			$this->session->set_flashdata("error", "please login first to view dashboard");
			redirect("Login/login");
		}
	}
    
    //var $master_url='https://gsrgroup.biz/inventory_management';
    var $master_url='https://bigcashew.com/inventory';
    
	public function damageEntry(){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$branch = $_SESSION['branch_name'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		//$data['getCustomer'] = $this->master_model->getCustomer($branch);
		$data['tax'] = $this->master_model->get_Tax();
		$data['items'] = $this->master_model->get_Items($branch_id);
		$this->load->view('Damage/damageCreation',$data);
	}

	public function insertDamage(){
		$damage_date = date("Y-m-d", strtotime($this->input->post('damage_date')));
		$order_time = date("h:i A");
		$lm=date("Y-m-dH:i:s",time());
		$branch_name = $this->input->post('branchname');
		$branch_id =  $this->input->post('branch_id');
		$login_id =  $this->input->post('login_id');
		$uname =  $this->input->post('uname');
		$damage_type = $this->input->post('ret_type');
		$query = $this->db->query("SELECT MAX(dm_no) as dm_no FROM damage_order_creation where branch_id='$branch_id'");
		
		foreach($query->result() as $row)
		$dms_no = $row->dm_no;
		if($dms_no == 0){
			$dm_no = 1;
		}
		else{
			$dm_no = $dms_no+1;
		}
		$damage_no = "DMG"."/".$branch_name."/".$dm_no;
		$item_name= $this->input->post('item_name');
		$unit_measurements= $this->input->post('unit_measurements');
		$prsnt_stk= $this->input->post('prsnt_stk');
		$quantity= $this->input->post('quantity');
		//$item_id= $this->input->post('item_id');
		$item_sid= $this->input->post('item_sid');
		$remarks= $this->input->post('remarks');
		$cat_id= $this->input->post('cat_id');
		$user= $this->input->post('uname');
		$k=0;
		for($j=0;$j<count($quantity);$j++)
		{
			if($quantity[$j]!='0' && $quantity[$j]!='')
			{
				$k=$k+1;
			}
		}
		if($k>0)
		{
		$sql = $this->db->query("insert into damage_order_creation(dm_no,damage_no,damage_date,branchname,user_name,dtime,branch_id) values ('$dm_no','$damage_no','$damage_date','$branch_name','$user','$order_time','$branch_id')");
		    $did = $this->db->insert_id();	
		}	
		if($did)
		{	
			for($i=0;$i<count($item_name),$i<count($item_sid),$i<count($cat_id),$i<count($unit_measurements),$i<count($quantity),$i<count($remarks);$i++) {
				$sql3=$this->db->query("select * from item_creation where item_id='$item_sid[$i]'");
				if($sql3->num_rows() >0)
				{
					foreach($sql3->result() as $res)
					$qty[$i] = $res->stock_item;//opening stock
					$qty1[$i] = $qty[$i] - $quantity[$i];//closing stock
					$itm_id[$i] = $res->itm_id;
				
					$sql3 =  $this->db->query("UPDATE item_creation set stock_item='$qty1[$i]' WHERE  item_id='$item_sid[$i]'");
		
				$sql2 =  $this->db->query("insert into  damage_order_item (damage_item_name,damage_uom,damage_qty,damage_remarks,damage_id,item_id,category_id,itm_id) values ('$item_name[$i]','$unit_measurements[$i]','$quantity[$i]','$remarks[$i]','$did','$item_sid[$i]','$cat_id[$i]','$itm_id[$i]')");
				$sql5 =  $this->db->query("insert into stock_detail(item_name,trans_ref_no,transaction_date,opening_stock,out_qty,closing_stock,last_modified,branchname,item_id,itm_id,category_id,branch_id,trans_type)values('$item_name[$i]','$damage_no','$damage_date','$qty[$i]','$quantity[$i]','$qty1[$i]','$lm','$branch_name','$item_sid[$i]','$itm_id[$i]','$cat_id[$i]','$branch_id','Damage')");
				}
			}
		redirect('Damage/damageReceipt/'.$did);
	}
	else
	{
	    $this->session->set_flashdata('error', 'Something went wrong, please do the entries again');
	    redirect('Damage/damageEntry/');
	}
	}

	public function damageReceipt($did){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['branch_name'] = $_SESSION['branch_name'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['getDamage'] = $this->damage_model->getDamage($did);
		$data['get_damage_item'] = $this->damage_model->get_damage_item($did);
		$this->load->view('Damage/damageReceipt',$data);
	}

	public function damageList()
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['damage'] = $this->damage_model->get_damage_list($branch_id);
		$this->load->view('Damage/damage_list',$data);
	}
	
	public function getDamage($sub_mod_id){
		
		$branch_id = $_SESSION['branch_id'];
		$data = $this->damage_model->get_damage_list($branch_id);
        $count=1;
        $test = array();
        foreach($data as $row)
    	{
    	    
    	    $view = "<a href='$this->master_url/index.php/Damage/viewDamage/$row->damage_id/$sub_mod_id' class=''><i class='ft-eye'></i></a>";
    	    
    	    
    	    $test[] = array(
    	        $count,
    	        $row->damage_no,
    	        $row->damage_date,
                $view
    	   );
    	        
    	        $count++;
    	}
    	$datas = array(
    	    "data" =>$test
    	);
    	
    	echo json_encode($datas);
	}
	
	public function viewDamage($did,$sub_mod_id){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['branch_name'] = $_SESSION['branch_name'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['thead_permission'] = $this->user_model->get_thead_permission($user_id,$sub_mod_id);
		$data['submod_id']=$sub_mod_id;
		$data['getDamage'] = $this->damage_model->getDamage($did);
		$data['get_damage_item'] = $this->damage_model->get_damage_item($did);
		$this->load->view('Damage/viewDamage',$data);
	}
	
	public function dmgEntry()
	{
		//file_put_contents('item_list.json', "");
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['items'] = $this->master_model->get_Items($branch_id);
		$data['rcat'] = $this->damage_model->get_rwCategory();
		$data['pcat'] = $this->damage_model->get_fpCategory();
		$this->load->view('Damage/damage',$data);
	}
	
	public function itemDetails(){
		$branch_id = $this->input->post('branch_id');
				
		$query1 = $this->db->query("SELECT category_id,category_name from category order by category_name");
		//foreach ($query1 as $key => $cat) {
		foreach($query1->result() as $cat){
			//while ($cat = mysqli_fetch_array($query1)) {
			$results = $this->db->query("SELECT T.item_name,T.uom,T.stock_item,T.item_id,T.itm_id,T.category_id FROM item_creation T inner join category C on C.category_id=T.category_id where C.category_id='".$cat->category_id."' and T.branch_id='$branch_id' order by T.item_name");
			
			unset($items);
			//foreach ($results as $key => $result) {
			foreach($results->result() as $result){
				//while ($result= mysqli_fetch_array($results)) {
				$items[] = array(
				'item_name' => $result->item_name,
				'uom' => $result->uom,
				'prsnt_stk' => $result->stock_item,
				'item_id' => $result->item_id,
				'itm_id' => $result->itm_id,
				'cat_id' => $result->category_id
				);
			}
			$category = $cat->category_name;
			$category_id = $cat->category_id;
			
			if(isset($items))
			{
    			$json[] = array(
    			'category' => $category,
    			'category_id' => $category_id,
    			'items' => $items
    			);
			}
		}
		
		$itemarray = array(
		'products' => $json
		);
		echo json_encode($itemarray);
		file_put_contents('item_list.json', json_encode($itemarray));
		
		//Finished product
		$query2 = $this->db->query("SELECT pr_cat_id,pr_cat_name from product_category order by pr_cat_name");
		//foreach ($query1 as $key => $cat) {
		foreach($query2->result() as $pr_cat){
			//while ($cat = mysqli_fetch_array($query1)) {
			
			$results1 = $this->db->query("SELECT R.rname,R.uom,R.production_stock,R.daily_stk_update,R.recipe_id,R.recipe_no,R.pr_cat_id FROM recipe R inner join product_category PC on PC.pr_cat_id=R.pr_cat_id where PC.pr_cat_id='".$pr_cat->pr_cat_id."' and R.branch_id='".$branch_id."' and R.status='Enabled' order by R.rname");
			
			unset($product);
			
			//foreach ($results as $key => $result) {
			foreach($results1->result() as $prod){
				//while ($result= mysqli_fetch_array($results)) {
				$product[] = array(
				'product_name' => $prod->rname,
				'uom' => $prod->uom,
				'prsnt_stk' => $prod->production_stock,
				'cls_stk' => $prod->daily_stk_update,
				'recipe_id' => $prod->recipe_id,
				'recipe_no' => $prod->recipe_no,
				'cat_id' => $prod->pr_cat_id
				);
			}
						
			$prod_cat = $pr_cat->pr_cat_name;
			$pr_cat_id = $pr_cat->pr_cat_id;
		    
		    if(isset($product))
		    {
    			$json1[] = array(
    			'prod_cat' => $prod_cat,
    			'pr_cat_id' => $pr_cat_id,
    			'product' => $product
    			);
		    }
		}
				
		$finished_prod = array(
		'finished_products' => $json1
		);
		
		echo json_encode($finished_prod);
		file_put_contents('product_list.json', json_encode($finished_prod));
	}
	
	public function insertDamageItem(){
		$cur_date = date("Y-m-d");
		$cur_time = date("h:i A");
		$lm=date("Y-m-dH:i:s",time());
		$branch_name = $this->input->post('branch');
		$branch_id =  $this->input->post('branch_id');
		$damage_type = $this->input->post('ret_type');
		$query = $this->db->query("SELECT MAX(dm_no) as dm_no FROM damage_order_creation where branch_id='$branch_id'");
		
		foreach($query->result() as $row)
		$dm_no = $row->dm_no;
		if($dm_no == 0){
			$dm_no = 1;
		}
		else{
			$dm_no = $dm_no+1;
		}
		$damage_no = "DMG"."/".$branch_name."/".$dm_no;
		
		
		$item_type=explode(',', $this->input->post('item_type'));
		$item_name=explode(',', $this->input->post('item_name'));
		$uom=explode(',', $this->input->post('uom'));
		$prsnt_stk=explode(',', $this->input->post('prsnt_stk'));
		$dmg_qty=explode(',', $this->input->post('dmg_qty'));
		$item_id=explode(',', $this->input->post('item_id'));
		$itm_id=explode(',', $this->input->post('itm_id'));
		$cat_id=explode(',', $this->input->post('cat_id'));
		$remarks=explode(',', $this->input->post('remarks'));
		
		$k=0;
		for($j=0;$j<count($dmg_qty);$j++)
		{
			if($dmg_qty[$j]!='0' && $dmg_qty[$j]!='')
			{
				$k=$k+1;
			}
		}
		if($k>0)
		{
		    $sql = $this->db->query("INSERT INTO damage_order_creation(dm_no,damage_no,damage_date,return_type,branchname,dtime,branch_id) values ('$dm_no','$damage_no','$cur_date','$damage_type','$branch_name','$cur_time','$branch_id')");
		    $did = $this->db->insert_id();
		}
		if($did)
		{
		for($i=0;$i<count($item_type),$i<count($item_name),$i<count($item_id),$i<count($uom),$i<count($prsnt_stk),$i<count($dmg_qty);$i++) {
			if($dmg_qty[$i] != '0' and $dmg_qty[$i] != '')
			{				
				if($item_type[$i] == 'Raw Material')
				{
					$sql3=$this->db->query("select * from item_creation where item_id='$item_id[$i]'");
					if($sql3->num_rows() > 0)
					{						
						foreach($sql3->result() as $row)
						$qty[$i] = $row->stock_item;//opening stock
						$qty1[$i] = $qty[$i] - $dmg_qty[$i];//closing stock
						
						$sql3 =  $this->db->query("UPDATE item_creation set stock_item='$qty1[$i]' WHERE  item_id='$item_id[$i]'");
					}
					$sql2 =  $this->db->query("INSERT INTO damage_order_item (item_type,damage_item_name,damage_uom,damage_qty,damage_id,item_id,category_id,itm_id,damage_remarks) values ('$item_type[$i]','$item_name[$i]','$uom[$i]','$dmg_qty[$i]','$did','$item_id[$i]','$cat_id[$i]','$itm_id[$i]','$remarks[$i]')");
					$sql5 = $this->db->query("insert into stock_detail(item_name,trans_ref_no,transaction_date,opening_stock,out_qty,closing_stock,last_modified,branchname,item_id,itm_id,category_id,branch_id,trans_type)values('$item_name[$i]','$damage_no','$cur_date','$qty[$i]','$dmg_qty[$i]','$qty1[$i]','$lm','$branch_name','$item_id[$i]','$itm_id[$i]','$cat_id[$i]','$branch_id','Damage')");
				}
				else
				{
					$sql3=$this->db->query("select * from recipe where recipe_id='$item_id[$i]'");
					if($sql3->num_rows() > 0)
					{
						foreach($sql3->result() as $row)
						$qty[$i] = $row->production_stock;//opening stock
						$qty1[$i] = $qty[$i] - $dmg_qty[$i];//closing stock
										
						$sql3 =  $this->db->query("UPDATE recipe set production_stock='$qty1[$i]' WHERE recipe_id='$item_id[$i]'");
					}
					$sql2 =  $this->db->query("INSERT INTO  damage_order_item (item_type,damage_item_name,damage_uom,damage_qty,damage_id,item_id,category_id,recipe_no,damage_remarks) values ('$item_type[$i]','$item_name[$i]','$uom[$i]','$dmg_qty[$i]','$did','$item_id[$i]','$cat_id[$i]','$itm_id[$i]','$remarks[$i]')");
					$sql5 = $this->db->query("insert into stock_detail(item_name,trans_ref_no,transaction_date,opening_stock,out_qty,closing_stock,last_modified,branchname,item_id,recipe_no,category_id,branch_id,trans_type)values('$item_name[$i]','$damage_no','$cur_date','$qty[$i]','$dmg_qty[$i]','$qty1[$i]','$lm','$branch_name','$item_id[$i]','$itm_id[$i]','$cat_id[$i]','$branch_id','Damage')");
				}
			}
		}
	}
		file_put_contents('item_list.json', '');
		file_put_contents('product_list.json', '');
		if($did)
		//echo "success";
		echo $did;
		
		else
		//echo json_encode(array('reslt' => 'error', 'did' => $did));
		echo "error";
	}

	public function damageWasteReceipt($did){
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['branch_name'] = $_SESSION['branch_name'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['getDamage'] = $this->damage_model->getDamage($did);
		$data['get_damage_item'] = $this->damage_model->get_damage_item($did);
		$this->load->view('Damage/damageWasteReceipt',$data);
	}
	
	public function CdamageList()
	{
		$user_id = $_SESSION['user_id'];
		$branch_id = $_SESSION['branch_id'];
		$data['side_bar_data'] = $this->user_model->get_SideBarData($user_id);
		$data['damage'] = $this->damage_model->get_Cdamage_list();
		$this->load->view('Damage/Cdamage_list',$data);
	}
	
	public function getCDamage($sub_mod_id){
		$data = $this->damage_model->get_Cdamage_list();
        $count=1;
        $test = array();
        foreach($data as $row)
    	{
    	    
    	    $view = "<a href='$this->master_url/index.php/Damage/viewDamage/$row->damage_id/$sub_mod_id' class=''><i class='ft-eye'></i></a>";
    	    
    	    
    	    $test[] = array(
    	        $count,
    	        $row->damage_no,
    	        $row->damage_date,
                $view
    	   );
    	        
    	        $count++;
    	}
    	$datas = array(
    	    "data" =>$test
    	);
    	
    	echo json_encode($datas);
	}
}
?>