<?php

use app\libraries\CommonHelper;
use app\libraries\DateHelper;
use app\libraries\Tenants;
use app\libraries\Userstamp;

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

class Invoice_item_model extends MY_Model
{

	use Tenants;

	//    public $database;
	public $short = "ii";
	public $table;
	public $tbl;

	//    protected $table = 'mas_invoicing_invoice_item';

	public function __construct()
	{
		parent::__construct();
		$this->database = $this->getTenantNo();
		$this->tbl = 'invoicing_invoice_item';
		$this->table = $this->tbl . ' ' . $this->short;
	}

	public function listing()
	{
		$this->tenant();
		return $this->getAll($this->database, $this->tbl);
	}

	public function listing_in_invoice($invoiceId)
	{
		$this->tenant();
		$this->load->model('Invoicing_model');
		$invoice = $this->Invoicing_model->detail($invoiceId);

		$fields = [
			$this->short . '.id',
			$this->short . '.amount',
			$this->short . '.attend_startdate',
			$this->short . '.course_count',
			$this->short . '.date_range',
			$this->short . '.discount',
			$this->short . '.extra_fee',
			$this->short . '.invoice_id',
			$this->short . '.item_name',
			$this->short . '.item_timeslot',
			$this->short . '.period_enddate',
			$this->short . '.period_startdate',
			$this->short . '.qty',
			$this->short . '.remark',
			$this->short . '.status',
			$this->short . '.unit_price',
			'ee.event_id',
			'ee.id as event_enrollment_id',
			's.chi_name',
			's.content1_phone',
			's.id as user_id'
		];
		$joins = [
			$this->table_prefix . 'event_enrollment ee ' => $this->short . '.event_enrollment_id=ee.id',
			$this->table_prefix . 'student s' => 'ee.student_id=s.id',
		];
		$db = $this->load->database($this->database, TRUE);
		$db->distinct();
		$db->select(implode(', ', $fields));
		$db->from($this->table_prefix . $this->table);
		foreach ($joins as $joinTbl => $condition) {
			$db->join($joinTbl, $condition);
		}
//        log_message('debug','invoicestatus:'.$invoice['invoice_status'].';empty code?'.empty($invoice['mergedcode']));
//		log_message('debug','mergedcode:'.$invoice['mergedcode']);
		if ($invoice['user_id']>0 && $invoice['invoice_status']!==InvoiceStatus::merged) {
			$db->where(['invoice_id' => $invoiceId]);
		} else {
			//find the ids of original invoices:
			$mergedcode = $invoice['mergedcode'];
			$invoices = $this->Invoicing_model->getallmerged($mergedcode);
			$ids = [];
			foreach ($invoices as $i) {
//                if ($i['mergedcode'] === $mergedcode) {
				$ids[] = $i['id'];
//                }
			}
			$db->where_in('invoice_id', $ids);
		}
		$data = $db->get()->result_array();
//        log_message('debug','sql:'.$db->last_query());
		$this->load->model('Invoicing_extra_model');//not using join table, as the item may not have any extra.
		foreach ($data as $k => $v) {
//        	log_message('debug','itemid:'.$v['id']);
			$extra = $this->Invoicing_extra_model->allByItemId($v['id']);
//			log_message('debug','empty extra?'.empty($extra));
			$data[$k] = array_merge(['extra' => $extra], $data[$k]);
		}
		return $data;
	}

	public function listing_in_print($invoiceId)
	{
		$this->tenant();
		$this->load->model('Invoicing_model');
		$fields = [
			$this->short . '.id',
			$this->short . '.amount',
			$this->short . '.attend_startdate',
			$this->short . '.course_count',
			$this->short . '.date_range',
			$this->short . '.discount',
			$this->short . '.extra_fee',
			$this->short . '.invoice_id',
			$this->short . '.item_name',
			$this->short . '.item_timeslot',
			$this->short . '.period_enddate',
			$this->short . '.period_startdate',
			$this->short . '.qty',
			$this->short . '.remark',
			$this->short . '.status',
			$this->short . '.unit_price',
			'ee.event_id',
			'ee.id as event_enrollment_id',
			's.chi_name',
			's.content1_phone',
			's.id as user_id'
		];
		$joins = [
			$this->table_prefix . 'event_enrollment ee ' => $this->short . '.event_enrollment_id=ee.id',
			$this->table_prefix . 'student s' => 'ee.student_id=s.id',
		];
		$db = $this->load->database($this->database, TRUE);
		$db->distinct();
		$db->select(implode(', ', $fields));
		$db->from($this->table_prefix . $this->table);
		foreach ($joins as $joinTbl => $condition) {
			$db->join($joinTbl, $condition);
		}

		$db->where(['invoice_id' => $invoiceId]);
		$data = $db->get()->result_array();
//        log_message('debug','sql:'.$db->last_query());
		$this->load->model('Invoicing_extra_model');//not using join table, as the item may not have any extra.
		foreach ($data as $k => $v) {
//        	log_message('debug','itemid:'.$v['id']);
			$extra = $this->Invoicing_extra_model->allByItemId($v['id']);
//			log_message('debug','empty extra?'.empty($extra));
			$data[$k] = array_merge(['extra' => $extra], $data[$k]);
		}
		return $data;
	}

	public function listing_in_event_attendance($eventId, $timeslotId)
	{
		$this->tenant();
		return $this->getAll($this->database, $this->tbl, [], ['event_id' => $eventId, 'event_timeslot_id' => $timeslotId]);
		//        return $this->db->from($this->table)
		//                        ->where('event_id', $eventId)
		//                        ->where('event_timeslot_id', $timeslotId)
		//                        ->get()
		//                        ->result_array();
	}

	public function detail_name($name)
	{
		$this->tenant();
		return $this->getAll($this->database, $this->tbl, [], ['name' => $name]);
		//        return $this->db->from($this->table)->where('name', $name)->get()->result_array();
	}

	public function save($params, $mode, $id = 0)
	{
		if ($mode === 'c') {
			$id = $this->create($params);
		} else {
			$this->update($params, $id);
		}
		return $id;
	}

	public function create($params)
	{
		$this->tenant();
		return $this->insertDB($this->database, $this->tbl, $params);
		//        $this->db->insert($this->table, Userstamp::create($params, 'created_by', 'create_time'));
		//        return $this->db->insert_id();
	}

	public function update($params, $id)
	{
		$this->tenant();
		$this->saveDB($this->database, $this->tbl, $params, $id);
		//        $this->db->update($this->table, Userstamp::update($params, 'updated_by', 'update_time'), ['id' => $id]);
		//        return $id;
	}

	public function getIdsByInvoiceId($invoiceId)
	{
		$this->tenant();
		$result = $this->getAll($this->database, $this->tbl, [], ['invoice_id' => $invoiceId]);
		//        $result = $this->db->from($this->table)->where('invoice_id', $invoiceId)->get()->result();
		$ids = [];
		foreach ($result as $row) {
			$ids[] = $row['id'];
		}
		return $ids;
	}

	public function getItemsByInvoiceId($invoiceId)
	{
		$this->tenant();
		return $this->getAll($this->database, $this->tbl, [], ['invoice_id' => $invoiceId]);
	}

	public function getEnrollmentIdsByInvoiceId($invoiceId){
		$data = $this->getAll($this->database,$this->tbl,['event_enrollment_id'],['invoice_id'=>$invoiceId]);
		$ids = [];
		foreach($data as $d){
			$ids[]=$d['event_enrollment_id'];
		}
		return $ids;
	}

}
