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

class cheques extends CI_Controller
{

	var $main_menu_name = "cheques";
	var $sub_menu_name = "";

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


		$this->load->model('Cheques_Model');
		$this->load->model('Warehouse_Model');
		$this->load->model('Bank_Model');
		$this->load->model('Common_Model');
		$this->load->model('Customer_Model');
		$this->load->model('Menu_Model');
		$this->load->model('User_Model');
		$this->load->model('System_Settings_Model');
		$this->load->model('Unit_Model');
		$this->load->model('Menu_Items_List_Model');
		$this->load->model('Loan_Payment_Received_Model');
		date_default_timezone_set('asia/colombo');
	}

	//undifine index
	public function index()
	{
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = $this->sub_menu_name;
		$this->load->view('loan', $data);
	}

	// -------------------------------------------------------------------------------------

	public function cheque_manage()
	{
		$this->load->model('Route_Model');
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = "cheque_manage";
		$data['routes_list'] = $this->Route_Model->get_all_active_routes();
		$data['customer_list'] = $this->Customer_Model->get_all_customer();
		$this->load->view('cheques/cheque_manage', $data);
	}

	public function update_cheque_status()
	{

		$response = array(
			'status' => 'error',
			'message' => 'Unknown error'
		);

		$term_id = $this->input->post('term_id', TRUE);
		$status  = $this->input->post('status', TRUE);

		if (empty($term_id) || !is_numeric($term_id)) {
			$response['message'] = 'Invalid cheque reference';
			echo json_encode($response);
			return;
		}

		// allowed statuses
		$allowed = array('Bank', 'Realized', 'Returned');

		if (!in_array($status, $allowed)) {
			$response['message'] = 'Invalid cheque status';
			echo json_encode($response);
			return;
		}

		// get loan term
		$this->db->where('term_id', $term_id);
		$term = $this->db->get('loan_terms')->row();

		if (!$term) {
			$response['message'] = 'Cheque record not found';
			echo json_encode($response);
			return;
		}

		// prevent duplicate realize
		if ($term->check_realize_status == 'Realized') {
			$response['message'] = 'Cheque already realized';
			echo json_encode($response);
			return;
		}

		$this->db->trans_start(); // transaction start

		/*
    ---------------------------------------------------
    UPDATE STATUS
    ---------------------------------------------------
    */

		$update = array(
			'check_realize_status' => $status,
			'status' => 'Paid',
			'paid_amount' => $term->term_amount,
			'payment_date' => date('Y-m-d H:i:s'),
			'updated_at' => date('Y-m-d H:i:s')
		);

		if ($status == 'Realized') {
			$update['realized_date'] = date('Y-m-d');
		}

		$this->db->where('term_id', $term_id);
		$this->db->update('loan_terms', $update);

		/*
    ---------------------------------------------------
    ADD PAYMENT WHEN REALIZED
    ---------------------------------------------------
    */

		if ($status == 'Realized') {

			$amount = $term->term_amount;

			$paymentData = [
				'loan_id' => $term->loan_id,
				'pymnt_ref_no' => time(),
				'pymnt_paying_by' => 'Cheque',
				'pymnt_amount' => $amount,
				'paymnt_cash' => 0,
				'paymnt_balance' => 0,
				'pymnt_date_time' => date('Y-m-d'),
				'user_id' => $this->session->userdata('user_id'),
				'pymnt_added_date_time' => date('Y-m-d H:i:s'),
				'pymnt_note' => 'Cheque realized',
				'cus_id' => 0,
				'warehouse_id' => 1,
				'loan_received' => $amount,
				'payment_type' => 'cheque',
				'payment_term' => $term_id
			];

			// model insert
			$payment_id = $this->Loan_Payment_Received_Model->insert_payment($paymentData);

			if (!$payment_id) {
				$this->db->trans_rollback();
				$response['message'] = 'Payment insert failed';
				echo json_encode($response);
				return;
			}

			/*
			-----------------------------------------
			UPDATE loan_terms.paymnt_id
			-----------------------------------------
			*/

			$this->db->where('term_id', $term_id);
			$this->db->update('loan_terms', array(
				'paymnt_id' => $payment_id
			));
		}

		$this->db->trans_complete();

		if ($this->db->trans_status() === FALSE) {
			$response['message'] = 'Database transaction failed';
		} else {
			$response['status'] = 'success';
			$response['message'] = 'Cheque status updated successfully';
		}

		echo json_encode($response);
	}



	public function get_all_pending_cheques()
	{
		$route = $this->input->get('route');
		$cus_id = $this->input->get('cus_id');
		$srh_to_date = '';
		$srh_from_date = '';
		$srh_warehouse_id = $this->input->get('srh_warehouse_id');
		if ($this->input->get('srh_to_date')) {
			$srh_to_date = date('Y-m-d', strtotime($this->input->get('srh_to_date')));
		}
		if ($this->input->get('srh_from_date')) {
			$srh_from_date = date('Y-m-d', strtotime($this->input->get('srh_from_date')));
		}

		$wareh_id = '';
		if ($this->session->userdata('ss_group_id') == 2) {
		} else {
			$wareh_id = $this->session->userdata('ss_warehouse_id');
		}
		$values = $this->Cheques_Model->get_all_not_realize_cheques($route, $cus_id, $srh_from_date, $srh_to_date);

		$columns = array();
		$data = array();
		if (!empty($values)) {
			foreach ($values as $users) {
				$row = array();
				$row[] = $users['pymnt_cheque_date'];
				$row[] = $users['pymnt_cheque_no'];
				$row[] = $users['pymnt_amount'];
				$row[] = $users['bank_code'];
				$row[] = $users['pymnt_branch'];
				$row[] = $users['loan_ref'];
				$row[] = $users['business_name'];
				$status = $users['check_realize_status'];

				if ($status == 'Pending') {
					$status_label = '<span class="label label-warning">Pending</span>';
				} elseif ($status == 'Bank') {
					$status_label = '<span class="label label-primary">Bank</span>';
				} elseif ($status == 'Realized') {
					$status_label = '<span class="label label-success">Realized</span>';
				} elseif ($status == 'Returned') {
					$status_label = '<span class="label label-danger">Returned</span>';
				} else {
					$status_label = '<span class="label label-default">' . $status . '</span>';
				}
				$row[] = $status_label;
				$actions = [];

				if ($users['check_realize_status'] == 'Pending') {
					$actions[] = '<li><a href="javascript:void(0)" onclick="updateChequeStatus(' . $users['term_id'] . ',\'Bank\')">
                    <i class="fa fa-bank text-primary"></i> Deposit to Bank</a></li>';
					$actions[] = '<li><a href="javascript:void(0)" onclick="updateChequeStatus(' . $users['term_id'] . ',\'Realized\')">
                    <i class="fa fa-check text-success"></i> Realize</a></li>';
					$actions[] = '<li><a href="javascript:void(0)" onclick="updateChequeStatus(' . $users['term_id'] . ',\'Returned\')">
                    <i class="fa fa-times text-danger"></i> Return</a></li>';
				} elseif ($users['check_realize_status'] == 'Bank') {
					$actions[] = '<li><a href="javascript:void(0)" onclick="updateChequeStatus(' . $users['term_id'] . ',\'Realized\')">
                    <i class="fa fa-check text-success"></i> Realize</a></li>';
					$actions[] = '<li><a href="javascript:void(0)" onclick="updateChequeStatus(' . $users['term_id'] . ',\'Returned\')">
                    <i class="fa fa-times text-danger"></i> Return</a></li>';
				} elseif ($users['check_realize_status'] == 'Returned') {
					// Only “Add Cheque” option
					$actions[] = '<li><a href="javascript:void(0)" onclick="showAddChequeSection(' . $users['term_id'] . ')">
									<i class="fa fa-plus text-warning"></i> Add Cheque</a></li>';
				}

				$action_dropdown = '<div class="btn-group">
                        <button type="button" class="btn btn-primary btn-xs dropdown-toggle" data-toggle="dropdown">
                            Action <span class="caret"></span>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-right">
                            ' . implode("", $actions) . '
                        </ul>
                    </div>';

				$row[] = $action_dropdown;
				$data[] = $row;
			}
			$output = array('data' => $data);
			echo json_encode($output);
		} else {
			$output = array('data' => '');
			echo json_encode($output);
		}
	}
	//-------------------------------------------------------------


	function update_deposit()
	{
		$pay_id = $this->input->post('pay_id');
		$data = array(
			'pymnt_deposited' => 1,
		);
		$result1 = $this->Cheque_Manage_Model->update_cheque_status($pay_id, $data);
	}

	function update_realize()
	{
		$pay_id = $this->input->post('pay_id');
		$data = array(
			'pymnt_realize' => 1,
		);
		$result1 = $this->Cheque_Manage_Model->update_cheque_status($pay_id, $data);
	}

	function update_reject()
	{
		$pay_id = $this->input->post('pay_id');
		$data = array(
			'pymnt_returned' => 1,
		);
		$result1 = $this->Cheque_Manage_Model->update_cheque_status($pay_id, $data);
	}
}
