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

class Billing extends CI_Controller {

	function __construct() 
	{
        error_reporting(0);
        parent::__construct();
        $this->load->model('CommonModel');
        $this->load->helper('Security');
        $this->load->library('form_validation');

       
    }

	public function index($type='')
	{ 
		if(isAdmin())
		{ 
			$data['recordSet']=$this->db->where('prd_type',$type)->order_by('billing_id','desc')->get('billing')->result_array();
			$data['content'] = 'billing/billing';
			$this->load->view('layout_home', $data);
		}
	}

	public function new()
	{
		if(isAdmin())
		{
			$data['content'] = 'billing/generate_billing';
			$this->load->view('layout_home', $data);
		}
	}
	public function getData()
	{
		if(isAdmin())
		{
			$input_data = $this->input->post();
            $input_data = $this->security->xss_clean($input_data);
			$search = $input_data['search'];

		    // $query = "SELECT * FROM inventory WHERE item_name like'%".$search."%'";
		    // $result = mysqli_query($con,$query);
		    $result=$this->db->like('item_name', $search)->get('inventory')->result_array();
		    
		    	foreach ($result as $row) {
		    	if($row['available_stock']!=0)
		    	{
		        $response[] = array("label"=>$row['item_name'].'-'.$row['size'],"item_desc"=>$row['item_desc'],"mrp"=>$row['mrp'],"item_code"=>$row['item_code'],"sell_price"=>$row['sell_price'],"inv_id"=>$row['inv_id']);
		    	}
		    }

		    echo json_encode($response);
		}
	}
	public function barcodescan()
	{
		if(isAdmin())
		{
			$input_data = $this->input->post();
            $input_data = $this->security->xss_clean($input_data);
			$search = $input_data['search'];
			$index = $input_data['index'];

		    // $query = "SELECT * FROM inventory WHERE item_name like'%".$search."%'";
		    // $result = mysqli_query($con,$query);
		    $result=$this->db->where('item_code', $search)->get('inventory')->result_array();
		    
		    	foreach ($result as $row) {
		    	$cart_product_data=$this->session->userdata('cart_products');
		    	
		    	
		    	if($row['available_stock']!=0)
		    	{
		    	if (!in_array($row['item_code'], $cart_product_data)) {
		    		$cart_product=array();
			    	$cart_product=$this->session->userdata('cart_products');
			    	$cart_product[]=$row['item_code'];
					$this->session->set_userdata('cart_products',$cart_product);
			        $response[] = array("label"=>$row['item_name'].'-'.$row['size'],"item_desc"=>$row['item_desc'],"mrp"=>$row['mrp'],"item_code"=>$row['item_code'],"sell_price"=>$row['sell_price'],"inv_id"=>$row['inv_id'],"index"=>$index,"duplicate"=>'NO');
		    		}
		    	else
		    	{
		    		$response[] = array("label"=>$row['item_name'].'-'.$row['size'],"item_desc"=>$row['item_desc'],"mrp"=>$row['mrp'],"item_code"=>$row['item_code'],"sell_price"=>$row['sell_price'],"inv_id"=>$row['inv_id'],"index"=>$index,"duplicate"=>'Yes');
		    	}
		    	}
		    }

		    echo json_encode($response);
		}
	}
	public function edit($para1)
	{
		if(isAdmin())
		{
			$data['row']= $this->CommonModel->fetch_a_row('billing_id',$para1,'billing');
            $data['content']  ="billing/edit";
            $this->load->view('layout_home',$data);
		}
	}
	public function liquor_print($para1)
	{
		if(isAdmin())
		{
			$data['row']= $this->CommonModel->fetch_a_row('billing_id',$para1,'billing');
            $data['content']  ="Liquor/print";
            $this->load->view('layout_home',$data);
		}
	}
	public function food_print($para1)
	{
		if(isAdmin())
		{
			$data['row']= $this->CommonModel->fetch_a_row('billing_id',$para1,'billing');
            $data['content']  ="Food/print";
            $this->load->view('layout_home',$data);
		}
	}

	public function save()
	{
		if(isAdmin())
		{
			$input_data = $this->input->post();
            $input_data = $this->security->xss_clean($input_data);
            $state_code = substr($input_data['gst'], 0, 2);
            
        	$insert_data['bill_no'] = $input_data['bill_no'];
        	$insert_data['cus_name'] = $input_data['cus_name'];
        	$insert_data['cus_phone'] = $input_data['cus_phone'];
        	$insert_data['cus_email'] = $input_data['cus_email'];
        	$insert_data['cus_address'] = $input_data['cus_address'];
        	$insert_data['delivery_mode'] = $input_data['delivery_mode'];
        	$insert_data['supply_reff'] = $input_data['supply_reff'];
        	$insert_data['oth_reff'] = $input_data['oth_reff'];
        	$insert_data['tax_type'] = $input_data['tax_type'];
        	$insert_data['gst'] = $input_data['gst'];
        	$insert_data['state'] = $input_data['state'];
        	$insert_data['city'] = $input_data['city'];
        	$insert_data['pin'] = $input_data['pin'];
        	$insert_data['dispath_documence'] = $input_data['dispath_documence'];
        	$insert_data['document_through'] = $input_data['document_through'];
        	$insert_data['delivery_note'] = $input_data['delivery_note'];
        	$insert_data['state_code'] = $state_code;
        	$insert_data['date'] = date('Y-m-d');
            $this->db->insert('billing',$insert_data);
            $last_id=$this->db->insert_id();
            foreach ($input_data['itemName'] as $key => $rate_data) {
            	$insert_bill_data['billing_id'] = $last_id;
            	$insert_bill_data['inv_id'] = $input_data['inv_id'][$key];
	        	$insert_bill_data['item_name'] = $input_data['itemName'][$key];
	        	$insert_bill_data['sl_no'] = $input_data['slno'][$key];
	        	$insert_bill_data['mrp'] = $input_data['mrp'][$key];
	        	$insert_bill_data['price'] = $input_data['price'][$key];
	        	$insert_bill_data['hsn'] = $input_data['hsn'][$key];
	        	$insert_bill_data['quantity'] = $input_data['qty'][$key];
	        	$insert_bill_data['description'] = $input_data['des'][$key];
	            $this->db->insert('billing_data',$insert_bill_data);
            $q=$input_data['qty'][$key];
            $upd="UPDATE `inventory` SET `available_stock` = `available_stock`-$q WHERE `inv_id` = '".$input_data['inv_id'][$key]."' ";
            $query = $this->db->query($upd);
            $upd="UPDATE `product` SET `p_quantity` = `p_quantity`-$q WHERE `prd_id` = '".$input_data['prd_id'][$key]."' ";
            $query = $this->db->query($upd);
            }
		}
	}

	public function Edit_data()
	{
	    if(isAdmin())
	    {  
        	$input_data = $this->input->post();
            $input_data = $this->security->xss_clean($input_data);
            //////////////////////Delete Old Data/////////////////////////////
            $this->db->select('*');
			$this->db->from('billing_data');
			$this->db->join('inventory', 'billing_data.inv_id = inventory.inv_id', 'left');
			$this->db->where('billing_data.billing_id', $input_data['billing_id']);
			$query = $this->db->get();

			$result = $query->result_array();
            foreach ($result as $row) {
            	$q=$row['quantity'];
            $upd_inventory="UPDATE `inventory` SET `available_stock` = `available_stock`+$q WHERE `inv_id` = '".$row['inv_id']."' ";
            $query = $this->db->query($upd_inventory);
            $upd_product="UPDATE `product` SET `p_quantity` = `p_quantity`+$q WHERE `prd_id` = '".$row['prd_id']."' ";
            $query = $this->db->query($upd_product);
            $this->db->where('billing_data_id', $row['billing_data_id']);
			$this->db->delete('billing_data');	
            }
            
			/////////////////////////////////////////////////////////////////
			//////////////////////Update////////////////////////////////////
            $edit_data['bill_no'] = $input_data['bill_no'];
        	$edit_data['cus_name'] = $input_data['cus_name'];
        	$edit_data['cus_phone'] = $input_data['cus_phone'];
        	$edit_data['cus_email'] = $input_data['cus_email'];
        	$edit_data['cus_address'] = $input_data['cus_address'];
            $this->db->where('billing_id',$input_data['billing_id']);
            $this->db->update('billing',$edit_data);
            foreach ($input_data['itemName'] as $key => $rate_data) {
            	$insert_bill_data['billing_id'] = $input_data['billing_id'];
            	$insert_bill_data['inv_id'] = $input_data['inv_id'][$key];
	        	$insert_bill_data['item_name'] = $input_data['itemName'][$key];
	        	$insert_bill_data['sl_no'] = $input_data['slno'][$key];
	        	$insert_bill_data['price'] = $input_data['price'][$key];
	        	$insert_bill_data['hsn'] = $input_data['hsn'][$key];
	        	$insert_bill_data['quantity'] = $input_data['qty'][$key];
	        	$insert_bill_data['description'] = $input_data['des'][$key];
	            $this->db->insert('billing_data',$insert_bill_data);
            $q=$input_data['qty'][$key];
            $result_inv=$this->db->where('inv_id', $input_data['inv_id'][$key])->get('inventory')->result_array();

            $upd_product="UPDATE `product` SET `p_quantity` = `p_quantity`-$q WHERE `prd_id` = '".$result_inv[0]['prd_id']."' ";
            $query = $this->db->query($upd_product);
            $upd="UPDATE `inventory` SET `available_stock` = `available_stock`-$q WHERE `inv_id` = '".$input_data['inv_id'][$key]."' ";
            $query = $this->db->query($upd);
            }
	    }      
	}
	public function status_change()
	{
	    if(isAdmin())
	    {  
	        	$input_data = $this->input->post();
	            $input_data = $this->security->xss_clean($input_data);
	            $edit_data['mobile_status'] = $input_data['new_status'];
	        	
	            $this->db->where('m_id',$input_data['id']);
	            $this->db->update('mobile_list',$edit_data);
	            echo 'success';
	    }      
	}
	public function Delete()
    {
        if(isAdmin())
        {
        	$input_data = $this->input->post();
        	$this->db->where('billing_id', $input_data['id']);
			$this->db->delete('billing');
        	$this->db->where('billing_id', $input_data['id']);
			$this->db->delete('billing_data');
        }
    }

    public function export()
	{
		if(isAdmin())
		{ 
			$project_array=$this->db->get('mobile_list')->result_array();
			header("Content-type: application/csv");
		    header("Content-Disposition: attachment; filename=\"project-".date('d-m-Y').".csv\"");
		    header("Pragma: no-cache");
		    header("Expires: 0");

		     $handle = fopen('php://output', 'w');
			$excel_heding=array();
			array_push($excel_heding, 'SL', 'Mobile ID', 'Mobile Number',  'Status','Date');
			fputcsv($handle, $excel_heding);
			foreach ($project_array as $key => $project_data) {
			$export_req = array();
			if ($project_data['mobile_status']=='1') {
			$status='Active';
			}
			else
			{
			$status='Inactive';
			}
			array_push($export_req, $key+1, $project_data['mobile_id'], $project_data['mobile_number'], $status, $project_data['date']);

			//print_r($call_det);die;
			fputcsv($handle, $export_req);
			} 
			 fclose($handle);
		     exit;
		
		}
	}
	public function import(){

        $data = array();

        $memData = array();

                $insertCount = $updateCount = $rowCount = $notAddCount = 0;

                if(is_uploaded_file($_FILES['import_data']['tmp_name'])){

                    $this->load->library('CSVReader');

                    $csvData = $this->csvreader->parse_csv($_FILES['import_data']['tmp_name']);

                    if(!empty($csvData)){

                        foreach($csvData as $row){ 
                        	$rowCount++;
                        	
							$insert_data['mobile_id'] = $row['Mobile ID'];
							$insert_data['mobile_number'] = $row['Mobile Number'];
							$insert_data['mobile_status'] = $row['Status'];
							$insert_data['date'] = date('Y-m-d');
							
							$this->db->insert('mobile_list',$insert_data);						
							
                          $insertCount++;  

                        }
                        $notAddCount = ($rowCount - ($insertCount + $updateCount));
                    }
                }

    }

}