<?php

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

class Customer extends Admin_Controller {

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

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

		$this->form_validation->set_rules('customer_id', 'Customer Id', 'required');
		$this->form_validation->set_rules('name', 'Customer Name', 'required');

		
        if ($this->form_validation->run() == FALSE) {
            
        } else {			
			
            $active = 1;
			
            $deprt_array = array(
				'date_captured' => date('Y-m-d'),
				'customer_id' => $this->input->post('customer_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->customer_model->add($deprt_array);
            $this->session->set_flashdata('msg', '<div class="alert alert-success text-left">Customer added successfully</div>');
            redirect('customer');
        }  
         $data['customer']=$this->customer_model->select();  
		 $data['currency']=$this->currencies_model->select();

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

	public function customer_invoice() {
		if (!$this->rbac->hasPrivilege('class', 'can_view')) {
			access_denied();
		}
	
		// Set menu and titles
		$this->session->set_userdata('top_menu', 'Customer Invoice');
		$this->session->set_userdata('sub_menu', 'customer/index');
		$data['title']      = 'Customer Invoicing';
		$data['title_list'] = 'Customer Invoices';
	
		//
		// Generate next invoice number (INV0001, INV0002, ...)
		//
		$countInv = $this->db->count_all('customer_invoice');
		if ($countInv > 0) {
			$seq = $countInv + 1;
			$data['inv'] = 'INV' . sprintf('%04d', $seq);
		} else {
			$data['inv'] = 'INV0001';
		}
	
		// Validation rules
		$this->form_validation->set_rules('name',        'Customer 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('price',       'Price',         'required');
		$this->form_validation->set_rules('gl_account',  'GL Account',    'required');
	
		if ($this->form_validation->run() !== FALSE) {
			//
			// Generate the "customer_statement" reference number
			//
			$countStmt = $this->db->count_all('customer_statement');
			if ($countStmt > 0) {
				$seqStmt = $countStmt + 1;
				$inv_number_st = 'INV' . sprintf('%04d', $seqStmt);
			} else {
				$inv_number_st = 'INV0001';
			}
	
			// Calculate amounts
			$price       = (float)$this->input->post('price');
			$discount    = (float)$this->input->post('discount');
			$total_discount = $price * ($discount / 100);
			$total_amount   = $price - $total_discount;
			$credit         = 0;
	
			// Build invoice array
			$deprt_array = [
				'gl_account'      => $this->input->post('gl_account'),
				'date_created'    => date('Y-m-d'),
				'name'            => $this->input->post('name'),
				'inv_date'        => $this->input->post('inv_date'),
				'inv_number'      => $inv_number_st,
				'currency'        => $this->input->post('currency'),
				'description'     => $this->input->post('description'),
				'quantity'        => $this->input->post('quantity'),
				'price'           => $price,
				'discount'        => $discount,
				'total_amount'    => $total_amount,
				'active'          => 1
			];
	
			// Build statement array
			$customer_statement_array = [
				'gl_account'   => $this->input->post('gl_account'),
				'customer'     => $this->input->post('name'),
				'reference'    => $data['inv'],
				'description'  => $this->input->post('description'),
				'currency'     => $this->input->post('currency'),
				'debit'        => $total_amount,
				'credit'       => $credit,
				'date'         => $this->input->post('inv_date')
			];
	
			// Insert into DB
			$this->customer_model->add_customer_invoice($deprt_array);
			$this->customer_model->add_to_statement($customer_statement_array);
	
			// Flash and redirect
			$this->session->set_flashdata(
				'msg',
				'<div class="alert alert-success text-left">Customer Invoice created successfully</div>'
			);
			redirect('customer/customer_invoice');
		}
	
		// Load data for view
		$data['customer_invoice']  = $this->customer_model->select_customer_invoice();
		$data['glledger_accounts'] = $this->glledger_accounts_model->select();
		$data['customer']          = $this->customer_model->select();
		$data['currency']          = $this->currencies_model->select();
	
		// Render views
		$this->load->view('layout/header', $data);
		$this->load->view('customer/customer_invoice', $data);
		$this->load->view('layout/footer', $data);
	}
	
	
	function customer_receipt() {
		
        if (!$this->rbac->hasPrivilege('class', 'can_view')) {
            access_denied();
        }
        $this->session->set_userdata('top_menu', 'Customer Invoice');
        $this->session->set_userdata('sub_menu', 'customer/index');
        $data['title'] = 'Customer Receipting';
        $data['title_list'] = 'Customer Receipts';
		
		

		$this->form_validation->set_rules('name', 'Customer 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('gl_account', '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('customer_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('customer_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;
			$debit =0;			
            $deprt_array = array(
			   'gl_account' => $this->input->post('gl_account'),
				'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				
            );            
			
			$customer_statement_array = array(
			    'gl_account' => $this->input->post('gl_account'),
				'customer' => $this->input->post('name'),				
				'reference' => $rec_number_st,						
				'description' => $this->input->post('description'),
				'currency' => $this->input->post('currency'),					
				'debit' => $debit,
				'credit' => $total_amount,								
				'date' => $this->input->post('rec_date')				
            );
			$this->customer_model->add_customer_receipt($deprt_array);
			$this->customer_model->add_to_statement($customer_statement_array);
            $this->session->set_flashdata('msg', '<div class="alert alert-success text-left">Customer Receipt created successfully</div>');
            redirect('customer/customer_receipt');
        }  
         $data['customer_invoice']=$this->customer_model->select_customer_invoice();  
         $data['customer_receipt']=$this->customer_model->select_customer_receipt();  
		 $data['glledger_accounts']=$this->glledger_accounts_model->select();
         $data['customer']=$this->customer_model->select();  
		 $data['currency']=$this->currencies_model->select();

        $this->load->view('layout/header', $data);
        $this->load->view('customer/customer_receipt', $data);
        $this->load->view('layout/footer', $data);
    }
 function unifstatement() {
       	 if (!$this->rbac->hasPrivilege('class', 'can_view')) {access_denied();}
		 
				$this->session->set_userdata('top_menu', 'Customer Statement');
				$this->session->set_userdata('sub_menu', 'customer/unifstatement');

				$this->form_validation->set_rules('name', 'Customer 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['customer']=$this->customer_model->select();   

									$this->load->view('layout/header', $data);
									$this->load->view('uniformpos/uniformstatement', $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->customer_model->customer_search($name, $from, $to);
							$data['customer_results'] = $resultlist;
							
						$data['customer']=$this->customer_model->select(); 
						  $data['name']=$name;
						 $data['from']=$from;
						 $data['to']=$to;						
						$this->load->view('layout/header', $data);
						$this->load->view('uniformpos/uniformstatement', $data);
						$this->load->view('layout/footer', $data);
					}
					else{
						  echo "PLEASE NOTHING HAS BEEN SUBMITTED TO CASH BOOK FORM";
					}
				}          
    }	
	function customer_statement() {
		
		 if (!$this->rbac->hasPrivilege('class', 'can_view')) {access_denied();}
		 
				$this->session->set_userdata('top_menu', 'Customer Statement');
				$this->session->set_userdata('sub_menu', 'customer/customer_statement');

				$this->form_validation->set_rules('name', 'Customer 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['customer']=$this->customer_model->select();   

									$this->load->view('layout/header', $data);
									$this->load->view('customer/customer_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->customer_model->customer_search($name, $from, $to);
							$data['customer_results'] = $resultlist;
							
						$data['customer']=$this->customer_model->select(); 
						  $data['name']=$name;
						 $data['from']=$from;
						 $data['to']=$to;						
						$this->load->view('layout/header', $data);
						$this->load->view('customer/customer_statement', $data);
						$this->load->view('layout/footer', $data);
					}
					else{
						  echo "PLEASE NOTHING HAS BEEN SUBMITTED TO CASH BOOK FORM";
					}
				}          
    }	
	function printCustomerStatement() {
		
		 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->customer_model->customer_search($name, $from, $to);
							$data['customer_results'] = $resultlist;
							
						$data['customer']=$this->customer_model->select(); 
						  $data['name']=$name;
						 $data['from']=$from;
						 $data['to']=$to;						
						$this->load->view('print/printCustomerStatement', $data);        
    }
    function edit($id) {
        $this->session->set_userdata('top_menu', 'Customer');
        $this->session->set_userdata('sub_menu', 'customer/index');
		
        $data['customer']=$this->customer_model->select(); 
        $data['title'] = 'Edit Customer';
        $data['id'] = $id;

        $data['customer'] = $this->customer_model->update($id);
		$data['currency']=$this->currencies_model->select();
				
		$this->form_validation->set_rules('customer_id', 'Customer Id', 'required');
		$this->form_validation->set_rules('name', 'Customer Name', 'required');

		
        if ($this->form_validation->run() == FALSE) {
			
            $this->load->view('layout/header', $data);
            $this->load->view('customer/customerEdit', $data);
            $this->load->view('layout/footer', $data);
			
        } else {
            $data = array(
                'id' => $id,
				'customer_id' => $this->input->post('customer_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->customer_model->add($data);
            $this->session->set_flashdata('msg', '<div class="alert alert-success">Customer updated  successfully</div>');
            redirect('customer/index');
        }
    }
    function printCustomerReceipt() {
	  
        $id = $this->input->post('id');

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


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

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

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


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

    }

}

?>