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

class POS extends CI_Controller {

	/**
	 * Class constructor and validate authenticate user
	 *
	 * @return  void
	 */
	public function __construct() {
		parent::__construct();
		//$this->output->enable_profiler(TRUE);
		if (  ! $this->session->user_id ) {
			redirect( '', 'refresh' );
		}
		$this->privileges = $this->MUser_privileges->get_by_ref_user( $this->session->user_id );
	}

	/**
	 * POS home page. Show the full interface
	 */
	public function index() {
		$data['title']     = 'POS - ERP Online';
		$data['menu']      = 'pos';
		$data['content']   = 'admin/pos/home';
		$data['items']     = $this->MItems->get_all();
		$data['customers'] = $this->MCustomers->get_all();
		/** For the add new customer popup, need optimization using JS */
		$customer = $this->MCustomers->get_latest();
		if ( count( $customer ) > 0 ) {
			$data['code'] = (int) $customer['code'] + 1;
		} else {
			$data['code'] = 1001;
		}
		$settings           = $this->MSettings->get_by_company_id( $this->session->user_company );
		$data['tax_rate']   = $settings['tax_rate'];
		$data['privileges'] = $this->privileges;

		$this->load->view( 'admin/template', $data );
	}

	/**
	 * Search product by barcode/name
	 *
	 * @param  $by string/NULL
	 *
	 * @return $response json_string
	 */
	public function search_product( $by = NULL ) {
		$barcode_search = $this->input->post( 'barcode_search' );
		if ( $by == "name" ) {
			$items = $this->MItems->get_like_name( $barcode_search );
		} else {
			$items = $this->MItems->get_by_code( $barcode_search );
		}
		if ( count( $items ) > 0 ) {
			$response['type']  = 'success';
			$response['items'] = $items;
		} else {
			$response['type']  = 'error';
			$response['items'] = NULL;
		}

		echo json_encode( $response );
	}

	/**
	 * Complete sales entry with accounts journal entry
	 *
	 * @return $response json_string
	 */
	public function sales_complete() {
		$last_sales = $this->MSales_master->get_last_sales_no();
		if ( count( $last_sales ) > 0 ) {
			$sales_no = (int) $last_sales['sales_no'] + 1;
		} else {
			$sales_no = 1001;
		}
		$received_amount = $this->input->post( 'received_amount' );
		$paying_amount   = $this->input->post( 'paying_amount' );
		$customer_id     = $this->input->post( 'customer_id' );
		$tax_percent     = $this->input->post( 'tax_percent' );
		$tax_amount      = $this->input->post( 'tax_amount' );
		$discount        = $this->input->post( 'discount' );
		$type            = $this->input->post( 'payment_type' );
		$notes           = $this->input->post( 'payment_notes' );
		$payment_status  = $this->input->post( 'payment_status' );
		$cart            = json_decode( $this->input->post( 'cart' ) );

		/** Sales Master Entry */
		$this->MSales_master->create_by_pos( $sales_no, $customer_id, $tax_percent, $tax_amount, $discount, $type, $notes, $payment_status );

		/** Sales Details Entry */
		foreach ( $cart as $key => $value ) {
			$item             = $this->MItems->get_by_id( $value->id );
			$item_total_price = $item['min_sale_price'] * (int) $value->qty;
			$item_total_cogs  = $item['avco_price'] * (int) $value->qty;

			$this->MSales_details->create_by_pos( $sales_no, $value->id, $item['min_sale_price'], $value->qty, $item_total_price, $item_total_cogs );
		}

		/** Sales Journal Master Entry */
		$sales_journal_no = $this->MAc_journal_master->get_journal_number();
		$this->MAc_journal_master->create_by_pos( $sales_journal_no, $sales_no );

		/** Sales Journal Details Entry */
		$settings    = $this->MSettings->get_by_company_id( $this->session->user_company );
		$total_price = $this->MSales_details->get_total_price_by_sales_no( $sales_no );
		$total_cogs  = $this->MSales_details->get_total_cogs( $sales_no );

		if ( $paying_amount <= $received_amount ) {
			/** Cash debit (gross amount) */
			$this->MAc_journal_details->create_by_inventory( $sales_journal_no, $settings['ac_cash'], $paying_amount );
			/** Sales revenue credit (net sale amount) */
			$this->MAc_journal_details->create_by_inventory( $sales_journal_no, $settings['ac_sales'], NULL, $total_price );
			/** Tax payable credit (tax amount) */
			if ( $tax_amount > 0 ) {
				$this->MAc_journal_details->create_by_inventory( $sales_journal_no, $settings['ac_tax'], NULL, $tax_amount );
			}
		} else {
			/** Calculate dues */
			$dues = (float) $paying_amount - (float) $received_amount;
			/** Accounts receivable / Customer account debit (dues amount) */
			$customer = $this->MCustomers->get_by_id( $customer_id );
			$this->MAc_journal_details->create_by_inventory( $sales_journal_no, $customer['ac_id'], $dues );
			/** Cash debit (paid amount if any) */
			if ( (float) $received_amount != 0 ) {
				$this->MAc_journal_details->create_by_inventory( $sales_journal_no, $settings['ac_cash'], $received_amount );
			}
			/** Sales revenue credit (net sale amount) */
			$this->MAc_journal_details->create_by_inventory( $sales_journal_no, $settings['ac_sales'], NULL, $total_price );
			/** Tax payable credit (tax amount) */
			if ( $tax_amount > 0 ) {
				$this->MAc_journal_details->create_by_inventory( $sales_journal_no, $settings['ac_tax'], NULL, $tax_amount );
			}
		}

		/** Expense Journal Master Entry */
		$expense_journal_no = $this->MAc_journal_master->get_journal_number();
		$sales_date         = date( "Y/m/d" );
		$this->MAc_journal_master->create_by_doc( $expense_journal_no, $sales_date, 'POS Sales', 'Expense', $sales_no );

		/** Expense Journal Details Entry */
		$this->MAc_journal_details->create_by_inventory( $expense_journal_no, $settings['ac_cogs'], $total_cogs );
		$this->MAc_journal_details->create_by_inventory( $expense_journal_no, $settings['ac_inventory'], NULL, $total_cogs );

		/** Money Receipt Entry if partial or full cash paid */
		if ( (float) $received_amount != 0 ) {
			$mr = $this->MAc_money_receipts->get_latest();
			if ( count( $mr ) > 0 ) {
				$mr_no = (int) $mr['mr_no'] + 1;
			} else {
				$mr_no = 1001;
			}

			if ( $paying_amount <= $received_amount ) {
				$total_paid = $paying_amount;
			} else {
				$total_paid = $received_amount;
			}
			$this->MAc_money_receipts->create_by_pos( $mr_no, $total_paid, $sales_no );
		}

		$response['type']     = 'success';
		$response['sales_no'] = $sales_no;

		echo json_encode( $response );
	}

	/**
	 * Print the invoice when complete sales
	 *
	 * @param $sales_no integer
	 */
	public function print_invoice( $sales_no ) {
		$data['title']      = 'Print Invoice - ERP Online';
		$data['master']     = $this->MSales_master->get_by_sales_no( $sales_no );
		$data['details']    = $this->MSales_details->get_by_sales_no( $sales_no );
		$data['company']    = $this->MCompanies->get_by_id( $data['master'][0]['company_id'] );
		$data['privileges'] = $this->privileges;
		$this->load->view( 'admin/pos/print', $data );
	}

}