<?php

use app\libraries\Tenants;

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

class Student_credit_model extends MY_Model
{

	use Tenants;

	public $database;
	public $short = "sc";
	public $table;
	public $tbl;

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

	public function detail_in_last_credit($studentId)
	{
		$db = $this->load->database($this->database, TRUE);
		$db->order_by('id', 'DESC');
		$db->limit(1);
		$db->where(['student_id' => $studentId]);
		return $db->from($this->table_prefix . $this->tbl)->get()->row_array();
	}

	public function getByStudentIdReceiptId($studentId,$receiptId){
		$db = $this->load->database($this->database, TRUE);
		$db->where(['student_id' => $studentId,'receipt_id'=>$receiptId]);
		return $db->from($this->table_prefix . $this->tbl)->get()->row_array();
	}

	public function detail_in_checkout($studentId, $invoiceId)
	{
		$this->tenant();
		return $this->db->from($this->table_prefix . $this->table)
			->where('student_id', $studentId)
			->where('invoice_id', $invoiceId)
			->get()->row_array();
	}

	public function create($params)
	{
		$params['id']=$this->insertDB($this->database,$this->tbl, $params);
		return $params;
	}

	public function update($params, $id)
	{
		$this->saveDB($this->database, $this->tbl, $params, $id);
	}

	public function getAddUseCreditsForPrint($studentId,$invoiceId){
		$sql = "select max(t.use_credits) as use_credits,max(t.add_credits) as add_credits from 
(SELECT MAX(CASE WHEN use_credits IS NOT NULL THEN id END) AS use_id,
  MAX(CASE WHEN add_credits IS NOT NULL THEN id END) AS add_id
FROM `mas_student_credit`
 WHERE student_id=? and invoice_id=?) as X
 join mas_student_credit t on t.id in (use_id,add_id) ";
		$db=$this->load->database($this->database,TRUE);
		return $db->query($sql,[$studentId,$invoiceId])->row_array();
	}
}
