<?php

use app\libraries\CommonHelper;

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

/**
 * @property Receipt_model $Receipt_model
 */
class Invoicing_checkout extends CI_Controller
{

	use \app\libraries\Json;

	public function __construct()
	{
		parent::__construct();
		$this->load->model('Invoice_model');
		$this->load->model('Receipt_model');
		$this->load->model('Student_credit_model');
		$this->load->model('Payment_type_model');
	}

	public function index($invoiceId)
	{
		$invoice = $this->Invoice_model->detail($invoiceId);
		if ($params = $this->input->post()) {
			$this->Receipt_model->create_in_checkout($params, $invoiceId);

			return $this->json_response([
				'error' => false,
				'success' => true,
				'message' => 'The request has been performed sucessfully.',
				'data' => null
			]);
		}
		$_types = $this->Payment_type_model->listing();
		$types = [];

		foreach ($_types as $_type) {
			$types[$_type['id']] = $_type['name'];
		}

		return $this->json_response([
			'error' => false,
			'success' => true,
			'message' => 'The request has been performed sucessfully.',
			'data' => [
				'paymentForm' => [
					'net_amount_payable' => CommonHelper::money($invoice['net_amount_payable']),
					'payment_type_id' => $types,
					'cash_amount' => 0,
					'cheque_amount' => 0,
					'cheque_bank_name' => null,
					'cheque_no' => null,
					'remark' => null,
				],
				'cannotPay' => in_array($invoice['invoice_status'], ['void', 'paid'])
			]
		]);
	}

	public function all()
	{
		$request = $this->input->get();
		$data = $this->Course_subcategory_model->all($request['course_category_id']);
		echo json_encode(['course_subcategory' => $data], JSON_UNESCAPED_UNICODE);
	}

	public function checkout()
	{
		if (! ($params = $this->input->get())) {
			return $this->json_response([
				'error' => true,
				'success' => false,
				'message' => 'The request has been performed sucessfully.',
				'checkout' => true,
				'data' => null
			]);
		}
	
		
        
        $maxId = $this->Receipt_model->get_max_id();

		$invoiceIds = $params['invoiceId'];
	
		if (count($invoiceIds) == 1) {
			$invoiceId = $invoiceIds[0];
			if ($params = $this->input->get()) {
				//deduct the credit:
				if (!empty($params['use_credits'])) {
					$invoice = $this->Invoice_model->detail($invoiceId);
					$last = $this->Student_credit_model->detail_in_last_credit($invoice['user_id']);
					$newcreditamt = floatval($last['credit_amount']) - floatval($params['use_credits']);
					$this->Student_credit_model->create(['student_id' => $invoice['user_id'], 'invoice_id' => $invoiceId, 'use_credits' => $params['use_credits'], 'credit_amount' => $newcreditamt, 'next_id' => $last['id']]);
				}
				
				$this->Receipt_model->create_in_checkout($params, $invoiceId);
			}
		}
		else {
			$this->Receipt_model->create_in_multiple_checkout($params);
		}
        $this->Receipt_model->trigger_push_notification($maxId);
		return $this->json_response([
			'error' => false,
			'success' => true,
			'message' => 'The request has been performed sucessfully.',
			'checkout' => true,
			'data' => null
		]);
	}

	public function checkout_init()
	{
		$invoiceIds = $this->input->get('invoiceId');
		
		$data = [];
		$totalPayAmount = 0;
		foreach ($invoiceIds as $invoiceId) {
		
			$invoice = $this->Invoice_model->detail($invoiceId);
			//var_dump($invoice);
			$mergedcode = $invoice['mergedcode'];
			$isinvoiceinmerge = CommonHelper::checkIfIsInvoiceInMerge($invoice);
			$creditamt = 0;
			if ($isinvoiceinmerge) {
				//find original invoices:
				$invoices = $this->Invoicing_model->getallmerged($mergedcode);
				$amounttopay = 0;
				$amountpaid = 0;
				foreach ($invoices as $i) {
					$credit = $this->Student_credit_model->detail_in_last_credit($i['user_id']);
					if (!empty($credit)) {
						$creditamt += floatval($credit['credit_amount']);
					}
					$amounttopay += floatval(trim($i['amounttopay']));
					$amountpaid += floatval(trim($i['amountpaid']));
				}
				$net_amount_payable = $amounttopay - $amountpaid;
			} else {
				$credit = $this->Student_credit_model->detail_in_last_credit($invoice['user_id']);
				if (!empty($credit)) {
					$creditamt = floatval($credit['credit_amount']);
				}
				$net_amount_payable = floatval(trim($invoice['amount_to_pay'])) - floatval(trim($invoice['amount_paid']));
			}

			$_types = $this->Payment_type_model->listing();
			$types = [];
			foreach ($_types as $_type) {
				$types[$_type['id']] = $_type['name'];
			}
			$totalPayAmount += $net_amount_payable;
			$data[] = [
				'invoice_id' => $invoice['id'],
				'invoice_number' => $invoice['issued_name'],
				'user_id' => $invoice['user_id'],
				'net_amount_payable' => $net_amount_payable,
				'creditstxt' => $creditamt,
				'credits' => $creditamt,
				'cannotPay' => $invoice['payment_status'] == PaymentStatus::paid
			];
		}

		return $this->json_response([
			'error' => false,
			'success' => true,
			'message' => 'The request has been performed sucessfully.',
			'checkoutinit' => true,
			'data' => [
				'paymentForm' => [
					'net_amount_payable' => $totalPayAmount,
//					'creditstxt' => $creditamt,
//					'credits' => $creditamt,
					'payment_type_id' => $types,
					'cash_amount' => 0,
					'cheque_amount' => 0,
					'cheque_no' => null,
					'bankcode' => null,
					'cheque_bank_name' => null,
					'remark' => null,
					'internal_remark' => null,
				],
				'invoices' => $data,
//				'cannotPay' => $invoice['payment_status'] == PaymentStatus::paid
			],
		]);
	}
}
