<?php namespace App\Controllers;
/**
 * File			: Trx.php
 * Description  : Controller untuk halaman transaksi
 * Created By	: Hendi
 * Created Date : 7 Apr 2021
 * Last Update  : 14 Apr 2021
**/
use App\Models\TrxModel;
use App\Models\MenuModel;
use CodeIgniter\Config\Services;

class Trx extends MyBaseController
{
	private $TrxModel;
	public function __construct()
	{
		parent::__construct();
		// Modelnya diload langsung di construct
		// agar create object hanya sekali saja
		$this->TrxModel = new TrxModel();
	}
	
    public function index()
	{
        //
    }
    
	public function addData()
	{
	    # kosongkan 
	    //$this->hideAntrian();
		# fn isLoggedIn di MyBaseController
		if (!$this->isLoggedIn()) return redirect()->to(base_url('login'));
		# jika sudah menu dinamis diisi dari array hasil query
		$data_sidebar = []; 
		# jika dibutuhkan data untuk konten
		$data_content = [
			'mod' => 'transaksi',
            'sts' => 'add',
			'menu_data' => (new MenuModel())->get()->getResultArray()
		];
		$data = [
			'title' => 'Transaksi',
			'sidebar' => view('contents/sidebar', $data_sidebar),
			'content' => view('contents/transaksi/transaksi_form', $data_content),
		];
		return view('templates/index', $data);
	}
	
	public function saveData()
    {
		# rc = result code, rd = result description
		# jika pakai AJAK POST sertakan token csrf baru dalam respon agar tidak error saat submit
		# jika diaktifkan csrfnya di Config/Filters.php
		if (!$this->isLoggedIn()) return json_encode(['rc' => '0', 'rd' => 'Transaksi gagal disimpan. Anda belum login.', 'csrf_name' => 'X-CSRF-TOKEN', 'csrf_content' => (Services::security())->getCSRFHash()]); 
        
		# agar cepat, pakai metode foreach.
		$post = [];
		foreach($_POST as $k => $v) $post[$k] = $this->request->getPost($k);
			
		# roles 'transaksi' sudah didefinisikan di Config/Validation.php
		if ($this->form_validation->run($post, 'transaksi') === FALSE) 
		{
		    # pesan error validasi disimpan di respon json karena pake ajax
			return json_encode(['rc' => '0', 'rd' => 'Transaksi gagal disimpan. ', 'errors' => $this->form_validation->getErrors(), 'csrf_name' => 'X-CSRF-TOKEN', 'csrf_content' => (Services::security())->getCSRFHash()]); 
		}
		else
		{
			$sts = $post['sts'];
			$id = $post['transaction_id'];
			$post['date'] = date('Y-m-d H:i:s');
			$post['user_id'] = $this->session->get('user_id');
            $detail_trx = json_decode($post['detail_trx'], true);
            # tidak disertakan dalam validasi / penyimpanan
			unset($post['sts']);
            unset($post['detail_trx']);
			//unset($post['csrf_token_name']);
						
			# jika satu baris saja boleh tanpa tanda {}
			if ($sts == 'add') 
			{
				# mendapatkan no antrian baru
				$post['queue_number'] = $this->TrxModel->getNoAntrianBaru();  
				# agar bisa mendapatkan id harus pake insert
                # $returnID = false, agar nilai kembalian bukan user_id tapi result boolean
                $res = $this->TrxModel->insert($post, false); # (data, returnID) 
                $id = $this->TrxModel->getInsertID();
			}
			else 
            {
				$res = $this->TrxModel->update($id, $post);
                 # hapus detail
                $this->TrxModel->deleteDetaiTrx($id);
			}

            foreach ($detail_trx as $v) 
            {
                $data = array(
    				'transaction_id' => $id,
    				'menu_id' => $v['menu_id'],
    				'qty' => $v['qty'],
    				'price' => $v['price'],
    				'subtotal' => $v['subtotal']
    			);
                $res = $this->TrxModel->saveDetaiTrx($data);
            }
                                             	
			# memberikan pesan, pake ul jadi pake []
			if ($res) #true
                # ada tambahan id transaksi dan no antrian di respon sukses
                # untuk mengisi inputan no transaksi dan no atrian di view setelah simpan data
				return json_encode(['rc' => '1', 'rd' => 'Transaksi berhasil disimpan.', 'transaction_id' => $id, 'queue_number' => $post['queue_number'], 'csrf_name' => 'X-CSRF-TOKEN', 'csrf_content' => (Services::security())->getCSRFHash()]); 
			else
				return json_encode(['rc' => '0', 'rd' => 'Transaksi gagal disimpan.', 'csrf_name' => 'X-CSRF-TOKEN', 'csrf_content' => (Services::security())->getCSRFHash()]); 
		}
	}
	
    public function printStruk($id) 
    {
        $trx =  $this->TrxModel->where('transaction_id', $id)->first();
        if (count($trx) < 1) return 'Transaksi tidak ditemukan';
        
        $html = '<html>
                    <head>
                        <title>Cetak Struk No. Transaksi '.$id.'</title>
                    </head>
                    <body>
                        RESTORAN SEDERHANA<br>
                        Jl. Ahmad Yani No. 20<br>
                        KOTA SORONG<br>
                        ===============================<br>
                        <table border=0 cellpadding=0 cellspacing=0 width=100%>
                            <tr>
                                <td colspan=3 align=right><b>No. Antian: '.$trx['queue_number'].'</b></td>
                            </tr>';
                        $detail = $this->TrxModel->getDetailTrx($id);
                        $no = 0;
                        $total = 0;
                        foreach($detail as $v)
                        {
                            $total += $v['subtotal'];
                            $html .= '
                                      <tr>
                                          <!--<td width=10% align=left>'.++$no.'.</td>-->
                                          <td colspan=3>'.strtoupper($v['menu_name']).'</td>
                                      </tr>  
                                      <tr>
                                          <td width=10% align=left>&nbsp;</td>
                                          <td>'.$v['qty'].' X '.number_format($v['price'], 0, ',', '.').'</td>
                                          <td width=25% align=right>'.number_format($v['subtotal'], 0, ',', '.').'</td>
                                      </tr>
                                     ';
                        }
        
        $html .= '    </table>
                       ===============================<br>
                       <table border=0 cellpadding=0 cellspacing=0 width=100%>
                            <tr>
                                <td colspan=2>TOTAL</td>
                                <td width=25% align=right>'.number_format($trx['total'], 0, ',', '.').'</td>
                            </tr>
                            <tr>
                                <td colspan=2>PAJAK (10%)</td>
                                <td width=25% align=right>'.number_format($trx['tax'], 0, ',', '.').'</td>
                            </tr>
                            <tr>
                                <td colspan=2>TOTAL BAYAR</td>
                                <td width=25% align=right>'.number_format($trx['total_paid'], 0, ',', '.').'</td>
                            </tr>
                            <tr>
                                <td colspan=2>UANG BAYAR</td>
                                <td width=25% align=right>'.number_format($trx['cash'], 0, ',', '.').'</td>
                            </tr>
                            <tr>
                                <td colspan=2>KEMBALI</td>
                                <td width=25% align=right>'.number_format($trx['change'], 0, ',', '.').'</td>
                            </tr>
                            <tr>
                                <td colspan=3>&nbsp;</td>
                            </tr>
                            <tr>
                                <td colspan=2>'.$trx['date'].'</td>
                                <td width=25% align=right>'.str_pad($trx['transaction_id'], 8, '0', STR_PAD_LEFT).'</td>
                            </tr>
                            <tr>
                                <td colspan=3>'.strtoupper($trx['user_id']).'</td>
                            </tr>
                       </table>
                       <script>window.print()</script>
                    </body>
                </html>';
        return $html;
    }
	public function deleteData()
    {
		if (!$this->isLoggedIn()) return 'Anda belum login';
		$post = [];
		foreach($_POST as $k => $v) $post[$k] = $this->request->getPost($k);
		
		# cek jika sudah ada turunannya jangan dihapus
		$cek = $this->TrxModel->cekParentData($post['id']);
		if ($cek > 0)
			return json_encode(['rc' => '0', 'rd' => 'Data gagal dihapus. Kategori tersebut sudah ada '.$cek.' turunannya. Silakan hapus dulu turunannya.']); 
		# rc = result code, rd = result description
		if ($this->TrxModel->delete($post['id'])) 
			return json_encode(['rc' => '1', 'rd' => 'Data berhasil dihapus.']); 
		else 
			return json_encode(['rc' => '0', 'rd' => 'Data gagal dihapus']);
	}
	
	public function updateStatus()
    {
        # rc = result code, rd = result description
		# jika pakai AJAK POST sertakan token csrf baru dalam respon agar tidak error saat submit
		# jika diaktifkan csrfnya di Config/Filters.php
		if (!$this->isLoggedIn()) return json_encode(['rc' => '0', 'rd' => 'Update Status Antrian Gagal. Anda belum login.', 'csrf_name' => 'X-CSRF-TOKEN', 'csrf_content' => (Services::security())->getCSRFHash()]); 
        
		# agar cepat, pakai metode foreach.
		$post = [];
		foreach($_POST as $k => $v) $post[$k] = $this->request->getPost($k);
		
		# harusnya ini ditaro di model
		$id = $post['id'];
		$status = $post['status'];
		$sekarang = date('Y-m-d H:i:s');
		
		if ($status == '0') 
		{
		    $sql = "UPDATE antrian SET status = ".$status.", start = null, finish = null, updated_at = '".$sekarang."' WHERE antrian_id IN (".$id.")";
		}
		elseif ($status == '1') 
		{
		    $sql = "UPDATE antrian SET status = ".$status.", start = '".$sekarang."', updated_at = '".$sekarang."' WHERE antrian_id IN (".$id.")";
		}
		elseif($status == '2')
		{
		    $sql = "UPDATE antrian SET status = ".$status.", finish = '".$sekarang."', updated_at = '".$sekarang."' WHERE antrian_id IN (".$id.")";
		}
		elseif($status == '3')
		{
		    $sql = "UPDATE antrian SET status = ".$status.", updated_at = '".$sekarang."' WHERE antrian_id IN (".$id.")";
        }
	
	    # tidak disertakan dalam validasi / penyimpanan
		unset($post['csrf_token_name']);
					
		$res = $this->TrxModel->db->query($sql);
			
		# memberikan pesan, pake ul jadi pake []
		if ($res) #true
			return json_encode(['rc' => '1', 'rd' => 'Update Status Antrian Berhasil.', 'csrf_name' => 'X-CSRF-TOKEN', 'csrf_content' => (Services::security())->getCSRFHash()]); 
		else
			return json_encode(['rc' => '0', 'rd' => 'Update Status Antrian Gagal.', 'csrf_name' => 'X-CSRF-TOKEN', 'csrf_content' => (Services::security())->getCSRFHash()]); 
	}
	# hilangkan dari monitor otomatis jika out/finish lebih dari 30 detik
	function hideAntrian()
	{
	    $sekarang = date('Y-m-d H:i:s');
	    $sql = "
	            UPDATE antrian SET status = 3, updated_at = '".$sekarang."'
	            WHERE status = 2 AND TIME_TO_SEC(TIMEDIFF(STR_TO_DATE('".$sekarang."', '%Y-%m-%d %H:%i:%s'), finish)) > 30
	           ";
	    $this->TrxModel->db->query($sql);
	}
}
