<?php namespace App\Models;
/**
 * File			: TrxModel.php
 * Description  : Model untuk halaman transaksi
 * Created By	: Hendi
 * Created Date : 7 April 2021
 * Last Update  : 12 April 2021
**/
use CodeIgniter\Model;
 
class TrxModel extends Model
{
    protected $table = 'transaction';
	protected $primaryKey = 'transaction_id';
    protected $allowedFields = ['date', 'queue_number', 'total', 'tax', 'total_paid', 'cash', 'change', 'note', 'user_id', 'created_at', 'updated_at', 'deleted_at'];
	# bukan hapus data permanen tapi saat call method delete hanya ngisi deleted_at saja
	protected $useSoftDeletes = true;
	# field created_at, updated_at, deleted_at akan diisi otomatis saat call method insert, update, delete
	protected $useTimestamps = true;
	protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';
	
	# fungsi untuk mendapatkan no antrian baru
    # cek (tanggal && no antrian && menu) tidak boleh sama pada hari yang sama, tidak pake is_unique di validation
	public function getNoAntrianBaru() 
    {
        $now = date('Y-m-d');
		$sql = "
				SELECT IFNULL(MAX(queue_number), 0) + 1 AS no_antrian FROM transaction
				WHERE DATE_FORMAT(date, '%Y-%m-%d') = '".$now."'
			   ";
		return $this->db->query($sql)->getRow()->no_antrian;
	}
    # fungsi untuk mendapatkan no trx baru
	public function getNoTrxBaru() 
    {
		$sql = "
                SELECT LPAD(IFNULL(MAX(transaction_id), 0) + 1, 8, '0') AS no_trx
                FROM transaction
               ";
		return $this->db->query($sql)->getRow()->no_trx;
	}
    # fungsi menghapus detail transaksi
    public function deleteDetaiTrx($id) 
    {
        $sql = "DELETE FROM transaction_detail WHERE transaction_id = ".$id;
	    $this->db->query($sql);
        return $this->db->affectedRows();
    }
    # fungsi menyimpan detail transaksi
    public function saveDetaiTrx($data) 
    {
        $sql = "
                INSERT INTO transaction_detail (transaction_id, menu_id, qty, price, subtotal) 
                VALUES (".$data['transaction_id'].",'".$data['menu_id']."',".$data['qty'].",".$data['price'].",".$data['subtotal'].")
               ";
	    $this->db->query($sql);
        return $this->db->affectedRows();
    }
    # 
    public function getDetailTrx($id)
    {
        $sql = "
                SELECT a.*, b.menu_name
                FROM transaction_detail a
                INNER JOIN menu b ON a.menu_id = b.menu_id
                WHERE a.transaction_id = $id
                ORDER BY b.menu_name
               ";
        return $this->db->query($sql)->getResultArray();
    }
}
