<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Supplier extends Admin_Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {
        if (!$this->rbac->hasPrivilege('class', 'can_view')) {
            access_denied();
        }
        $this->session->set_userdata('top_menu', 'Suppliers');
        $this->session->set_userdata('sub_menu', 'supplier/index');
        $data['title'] = 'Add Supplier';
        $data['title_list'] = 'Supplier List';

		$this->form_validation->set_rules('supplier_id', 'Supplier Id', 'required');
		$this->form_validation->set_rules('name', 'Supplier Name', 'required');

		
        if ($this->form_validation->run() == FALSE) {
            
        } else {			
			
            $active = 1;
			
            $deprt_array = array(
				'date_captured' => date('Y-m-d'),
				'supplier_id' => $this->input->post('supplier_id'),		
				'name' => $this->input->post('name'),		
				'address' => $this->input->post('address'),		
				'mobile' => $this->input->post('mobile'),		
				'email' => $this->input->post('email'),		
				'currency' => $this->input->post('currency'),								
				'active' => 1				
            );
			$this->supplier_model->add($deprt_array);
            $this->session->set_flashdata('msg', '<div class="alert alert-success text-left">Supplier added successfully</div>');
            redirect('supplier');
        }  
         $data['supplier']=$this->supplier_model->select();  
		 $data['currency']=$this->currencies_model->select();

        $this->load->view('layout/header', $data);
        $this->load->view('supplier/supplierList', $data);
        $this->load->view('layout/footer', $data);
    }    

    function delete($id) {
        if (!$this->rbac->hasPrivilege('class', 'can_delete')) {
            access_denied();
        }
        $data['title'] = 'Supplier';
        $this->supplier_model->remove($id);
        redirect('supplier');
    }

    function edit($id) {
        $this->session->set_userdata('top_menu', 'Suppliers');
        $this->session->set_userdata('sub_menu', 'supplier/index');
		
        $data['supplier']=$this->supplier_model->select(); 
        $data['title'] = 'Edit Supplier';
        $data['id'] = $id;

        $data['supplier'] = $this->supplier_model->update($id);
		$data['currency']=$this->currencies_model->select();
				
		$this->form_validation->set_rules('supplier_id', 'Supplier Id', 'required');
		$this->form_validation->set_rules('name', 'Supplier Name', 'required');
		
        if ($this->form_validation->run() == FALSE) {
			
            $this->load->view('layout/header', $data);
            $this->load->view('supplier/supplierEdit', $data);
            $this->load->view('layout/footer', $data);
			
        } else {
            $data = array(
                'id' => $id,
				'supplier_id' => $this->input->post('supplier_id'),		
				'name' => $this->input->post('name'),		
				'address' => $this->input->post('address'),		
				'mobile' => $this->input->post('mobile'),		
				'email' => $this->input->post('email'),		
				'currency' => $this->input->post('currency'),
            );
            $this->supplier_model->add($data);
            $this->session->set_flashdata('msg', '<div class="alert alert-success">Supplier updated  successfully</div>');
            redirect('supplier/index');
        }
    }

	function supplier_invoice() {
		
        if (!$this->rbac->hasPrivilege('class', 'can_view')) {
            access_denied();
        }
        $this->session->set_userdata('top_menu', 'Supplier Invoice');
        $this->session->set_userdata('sub_menu', 'supplier/index');
        $data['title'] = 'Supplier Invoicing';
        $data['title_list'] = 'Supplier Invoices';
		

		$this->form_validation->set_rules('name', 'Supplier Name', 'required');
		$this->form_validation->set_rules('inv_date', 'Invoice Date', 'required');
		$this->form_validation->set_rules('currency', 'Currency', 'required');
		//$this->form_validation->set_rules('description', 'Description', 'required');
		//$this->form_validation->set_rules('quantity', 'Quantity', 'required');
		$this->form_validation->set_rules('price', 'Price', 'required');
		//$this->form_validation->set_rules('discount', 'Discount', 'required');
		//$this->form_validation->set_rules('account_name', 'Account name', 'required');
		$this->form_validation->set_rules('inv_number', 'Inv_number name', 'required');
		//$this->form_validation->set_rules('originalquantity', 'Originalquantity', 'required');
		
        if ($this->form_validation->run() == FALSE) {
			log_message('debug', 'Validation Errors: ' . validation_errors());
		
        } else {			
            $active = 1;
            $quantity = $this->input->post('quantity');
            $price = $this->input->post('price');
            $discount = $this->input->post('discount');
            $total_discount = ($price)*($discount/100);
			
            $total_amount = ($quantity*$price) - $total_discount;
			
			$debit =0;
						
            $deprt_array = array(
			   'account_name' => $this->input->post('account_name'),
			   'module' => $this->input->post('module'),
				'date_created' => date('Y-m-d'),						
				'name' => $this->input->post('name'),		
				'inv_date' => $this->input->post('inv_date'),		
				'inv_number' => $this->input->post('inv_number'),			
				'currency' => $this->input->post('currency'),		
				'description' => $this->input->post('descriptions'),		
				'warehouse' => $this->input->post('warehouse'),	
				'quantity' => $this->input->post('quantity'),
				'originalqnty' => $this->input->post('originalquantity'),			
				'price' => $this->input->post('price'),								
				'discount' => $this->input->post('discount'),								
				'total_amount' => $total_amount,
                 'mv_expense' => $this->input->post('mv_expense'),				
				'active' => 1				
            );

			$supplier_statement_array = array(
				'account_name' => $this->input->post('account_name'),				
				'supplier' => $this->input->post('name'),				
				'reference' =>  $this->input->post('inv_number'),					
				'description' => $this->input->post('description'),
				'currency' => $this->input->post('currency'),					
				'credit' => $total_amount,								
				'debit' => $debit,							
                'mv_expense' => $this->input->post('mv_expense'),				
				'date' => $this->input->post('inv_date')				
            );

			
			// Get the itemcode and quantity from the form input
			$itemcode = $this->input->post('account_name'); // Ensure this matches the 'itemcode' field in the `uniformitem` table
			$quantity_to_add = $this->input->post('quantity'); // Quantity to be added
			// Load the `uniformitem_model`
			$this->load->model('uniformitem_model');
			// Call the function to update the quantity
			$this->uniformitem_model->update_uniformitem_quantity($itemcode, $quantity_to_add);
			$this->supplier_model->add_supplier_invoice($deprt_array);
			$this->supplier_model->add_supplier_invoicetemp($deprt_array);
			$this->supplier_model->add_to_statement($supplier_statement_array);
            $this->session->set_flashdata('msg', '<div class="alert alert-success text-left">Supplier Invoice created successfully</div>');
            redirect('supplier/supplier_invoice');
			
        }  
		 $data['vehicle_list']=$this->cashbook_model->select_vehicle();
         $data['supplier_invoice']=$this->supplier_model->select_supplier_invoice();  
		 $data['glledger_accounts']= $this->cashbook_model->getGLByModules();
         $data['supplier']=$this->supplier_model->select();  
		 $data['currency']=$this->currencies_model->select();
		 $data['uniformitem']=$this->group_model->select();
		 $data['tempsup_invoice'] = $this->supplier_model->get_tempsup_invoices();
        $this->load->view('layout/header', $data);
        $this->load->view('supplier/supplier_invoice', $data);
        $this->load->view('layout/footer', $data);

	
    }	
	
		
	#empting the tempsup_invoice table to make the refresh button work propperly as expected
	public function delete_temp()
	{
		$this->db->empty_table('tempsup_invoice'); // Clears all records from the table
		echo json_encode(['status' => 'success']); // Send a success response
	}
			
				
	function supplier_receipt() {
		
        if (!$this->rbac->hasPrivilege('class', 'can_view')) {
            access_denied();
        }
        $this->session->set_userdata('top_menu', 'Supplier Invoice');
        $this->session->set_userdata('sub_menu', 'supplier/index');
        $data['title'] = 'Supplier Receipting';
        $data['title_list'] = 'Supplier Receipts';
		
		

		$this->form_validation->set_rules('name', 'Supplier Name', 'required');
		$this->form_validation->set_rules('rec_date', 'Receipt Date', 'required');
		$this->form_validation->set_rules('inv_number', 'Invoice Number', 'required');
		$this->form_validation->set_rules('currency', 'Currency', 'required');
		$this->form_validation->set_rules('description', 'Description', 'required');
		//$this->form_validation->set_rules('quantity', 'Quantity', 'required');
		$this->form_validation->set_rules('price', 'Price', 'required');
		//$this->form_validation->set_rules('discount', 'Discount', 'required');
		$this->form_validation->set_rules('account_name', 'GL Account', 'required');
		
        if ($this->form_validation->run() == FALSE) {
            
        } else {


				//CODE FOR GENERATING RECEIPT NUMBERS AND INSERTING THEM TO THE DATABASE
				$value2='';
				//Query to fetch last inserted invoice number
				$this->db->select('rec_number`');
				$this->db->from('supplier_receipt');
				$query1 = $this->db->get();
				$result1 = $query1->num_rows();    // CODE FOR COUNTING NUMBER OF ROWS IN TOTAL
				//$get_result = $query1->row();		//CODE FOR PULLING THE RECEIPT NUMBERS
				
				if($result1 > 0) {
					
						$value2 =$result1;
						//$value2 = substr($value2, 10, 13);//separating numeric part
						$value2 = $value2 + 1;//Incrementing numeric part
						$value2 = "REC" . sprintf('%04s', $value2);//concatenating incremented value
						$value = $value2; 						
				} 
				else {
					$value2 = "REC0001";
					$value = $value2;
									
				}
							
				$rec_number = $value;			
	
                //CODE FOR GENERATING RECEIPT NUMBERS AND INSERTING THEM TO THE DATABASE
				$value22='';
				//Query to fetch last inserted invoice number
				$this->db->select('reference`');
				$this->db->from('supplier_statement');
				$query12 = $this->db->get();
				$result12 = $query12->num_rows();    // CODE FOR COUNTING NUMBER OF ROWS IN TOTAL
				//$get_result = $query1->row();		//CODE FOR PULLING THE RECEIPT NUMBERS
				
				if($result12 > 0) {
					
						$value22 =$result12;
						//$value2 = substr($value2, 10, 13);//separating numeric part
						$value22 = $value22 + 1;//Incrementing numeric part
						$value22 = "REC" . sprintf('%04s', $value22);//concatenating incremented value
						$value1 = $value22; 						
				} 
				else {
					$value22 = "REC0001";
					$value1 = $value22;
									
				}
							
				$rec_number_st = $value1;	

	
            $active = 1;
            //$quantity = $this->input->post('quantity');
            $price = $this->input->post('price');
            $discount = $this->input->post('discount');
			
            $total_discount = ($price)*($discount/100);
			
            $total_amount = ($price) - $total_discount;
						
			$credit = 0;
			
            $deprt_array = array(
				'account_name' => $this->input->post('account_name'),
				'date_created' => date('Y-m-d'),
				'name' => $this->input->post('name'),		
				'rec_date' => $this->input->post('rec_date'),		
				'rec_number' => $rec_number,		
				'inv_number' => $this->input->post('inv_number'),		
				'currency' => $this->input->post('currency'),		
				'description' => $this->input->post('description'),		
				'quantity' => $this->input->post('quantity'),		
				'price' => $this->input->post('price'),								
				'discount' => $this->input->post('discount'),								
				'total_amount' => $total_amount,								
				'active' => 1				
            );            
			
			$supplier_statement_array = array(
				'account_name' => $this->input->post('account_name'),
				'supplier' => $this->input->post('name'),				
				'reference' => $rec_number_st,						
				'description' => $this->input->post('description'),
				'currency' => $this->input->post('currency'),					
				'debit' => $total_amount,	
				'credit' => $credit,				
				'date' => $this->input->post('rec_date')				
            );
			$this->supplier_model->add_supplier_receipt($deprt_array);
			$this->supplier_model->add_to_statement($supplier_statement_array);
            $this->session->set_flashdata('msg', '<div class="alert alert-success text-left">Supplier Receipt created successfully</div>');
            redirect('supplier/supplier_receipt');
        }  
         $data['supplier_invoice']=$this->supplier_model->select_supplier_invoice();  
         $data['supplier_receipt']=$this->supplier_model->select_supplier_receipt();  
		  $data['glledger_accounts']=$this->glledger_accounts_model->select();
         $data['supplier']=$this->supplier_model->select();  
		 $data['currency']=$this->currencies_model->select();

        $this->load->view('layout/header', $data);
        $this->load->view('supplier/supplier_receipt', $data);
        $this->load->view('layout/footer', $data);
    }
	function supplier_statement() {
		
		 if (!$this->rbac->hasPrivilege('class', 'can_view')) {access_denied();}
		 
				$this->session->set_userdata('top_menu', 'Supplier Statement');
				$this->session->set_userdata('sub_menu', 'supplier/supplier_statement');

				$this->form_validation->set_rules('name', 'Supplier Name', 'required');
				$this->form_validation->set_rules('from', 'Start Date', 'required');
				$this->form_validation->set_rules('to', 'End Date', 'required');

				if ($this->form_validation->run() == FALSE) {
					
									 $data['supplier']=$this->supplier_model->select();   
								
									$this->load->view('layout/header', $data);
									$this->load->view('supplier/supplier_statement', $data);
									$this->load->view('layout/footer', $data);
					
				} else {			

						$name = $this->input->post('name');
						$from = $this->input->post('from');
						$to = $this->input->post('to');
						$search = $this->input->post('search');
												
					if (isset($search)) {

							$resultlist = $this->supplier_model->supplier_search($name, $from, $to);
							$data['supplier_results'] = $resultlist;
							
						 $data['supplier']=$this->supplier_model->select(); 
						 $data['cashbook']=$this->cashbook_model->select();  
						 
						  $data['name']=$name;
						 $data['from']=$from;
						 $data['to']=$to;
						
						$this->load->view('layout/header', $data);
						$this->load->view('supplier/supplier_statement', $data);
						$this->load->view('layout/footer', $data);
					}
					else{
						  echo "PLEASE NOTHING HAS BEEN SUBMITTED TO CASH BOOK FORM";
					}
				}          
    }	
	function printSupplierStatement() {
		
		 if (!$this->rbac->hasPrivilege('class', 'can_view')) {access_denied();}

		        $setting_result = $this->setting_model->get();
                $data['settinglist'] = $setting_result;

						$name = $this->input->post('name');
						$from = $this->input->post('from');
						$to = $this->input->post('to');

						$resultlist = $this->supplier_model->supplier_search($name, $from, $to);
						$data['supplier_results'] = $resultlist;
							
						 $data['supplier']=$this->supplier_model->select(); 
						 $data['cashbook']=$this->cashbook_model->select();  
						 
						 $data['name']=$name;
						 $data['from']=$from;
						 $data['to']=$to;
						
						$this->load->view('print/printSupplierStatement', $data);   
    }

    function printSupplierReceipt() {
	  
        $id = $this->input->post('id');

        $setting_result = $this->setting_model->get();
        $data['settinglist'] = $setting_result;
		
		$this->db->select('*');
		$this->db->from('supplier_receipt');
		$this->db->where('id = ', $id);
		$query = $this->db->get();
        $data['supplierReceipt'] = $query;
        $data['supID'] = $id;


        $this->load->view('print/printSupplierReceipt', $data);

    }
   
   function printSupplierInvoice() {
	  
        $id = $this->input->post('id');

        $setting_result = $this->setting_model->get();
        $data['settinglist'] = $setting_result;
		
		$this->db->select('*');
		$this->db->from('supplier_invoice');
		$this->db->where('id = ', $id);
		$query = $this->db->get();
        $data['supplierInvoice'] = $query;
        $data['supID'] = $id;


        $this->load->view('print/printSupplierInvoice', $data);

    }


    // Function to fetch updated temporary invoice data
    public function getTempInvoices() {
        // Get the data from the model
        

		$data['tempsup_invoice'] = $this->Supplier_Model->getTempInvoices();
    }


}

?>