<?php
namespace App\Controllers;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

use App\Libraries\Pluploadhandler;

use CodeIgniter\API\ResponseTrait;
use App\Models\Produkmodel;

class Produk extends BaseController
{
    use ResponseTrait;

    private $user;

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) 
    {
        parent::initController($request, $response, $logger);
        $this->user = service("user_data");
    }

    private function check_access(){
        $user = service("user_data");
        if($user->data->group != 'admin'){
            return false;
        }else{
            return true;
        }
    }

    public function index(){
        $data['user'] = $this->user->data;
        return view('admin/produk/index',$data);
    }

    public function ajax_dt(){
        $data_post = [
            'draw' => $this->request->getPost('draw'),
            'columns' => $this->request->getPost('columns'),
            'order' => $this->request->getPost('order'),
            'start' => $this->request->getPost('start'),
            'length' => $this->request->getPost('length'),
            'search' => $this->request->getPost('search'),
            'searchBuilder' => $this->request->getPost('searchBuilder'),
        ];
        $DataModel = new Produkmodel();
        return $DataModel->GetDT($data_post,"");
    }

    public function add() {
        $data['user'] = $this->user->data;
        return view('admin/produk/add',$data);
    }

    public function add_save()
    {
        $data = array();
        $data['status'] = 'success';

        $request = [
            'kode_produk' => $this->request->getPost('kode_produk',FILTER_SANITIZE_ADD_SLASHES),
            'nama_produk' => $this->request->getPost('nama_produk',FILTER_SANITIZE_ADD_SLASHES),
            'kategori' => $this->request->getPost('kategori',FILTER_SANITIZE_ADD_SLASHES),
            'satuan' => $this->request->getPost('satuan',FILTER_SANITIZE_ADD_SLASHES),
            'status' => $this->request->getPost('status',FILTER_SANITIZE_ADD_SLASHES),
            'gambar' => $this->request->getPost('gambar',FILTER_SANITIZE_ADD_SLASHES),
        ];

        $validation = \Config\Services::validation();
        $validation->setRule('kode_produk', 'Kode Produk', 'required|is_unique[produk.kode_produk]');
        $validation->setRule('nama_produk', 'Nama Produk', 'required|is_unique[produk.nama_produk]');
        $validation->setRule('kategori', 'Kategori', 'required');
        // $validation->setRule('satuan', 'Satuan', 'required');
        $validation->setRule('status', 'Status', 'required');
        // $validation->setRule('gambar', 'Gambar', 'required');

        if (!$validation->run($request)) {
            return $this->fail($validation->getErrors(),400,null,'input');
        }else{
            $tmodel = new Produkmodel();
            $tmodel->db->transBegin();
            $id = $tmodel->insert($request);
            if($tmodel->db->transStatus() === false){
                $tmodel->db->transRollback();
                return $this->fail($tmodel->errors(),400,null,'db');
            }else{
                $tmodel->db->transCommit();
                $session = session();
                $session->setFlashdata('id_produk', $id);
                return $this->respond($data,200);
            }
        }
    }

    public function upload()
    {
        $session = session();
        $original_name = $this->request->getPost('name',FILTER_SANITIZE_ADD_SLASHES);
        $id_produk = $session->getFlashdata('id_produk');
        $session->setFlashdata('id_produk',$id_produk);

        if(empty($id_produk)){
            return $this->fail(["error" => "Invalid ID"],400,null,'system');
        }

        $ph = new PluploadHandler(array(
            'target_dir' => 'gambar/',
            'allow_extensions' => 'jpg,jpeg,png,gif,bmp'
        ));

        $ph->sendNoCacheHeaders();
        $ph->sendCORSHeaders();

        if ($result = $ph->handleUpload()) {
            if (isset($result['done']))
            {
                $tmodel = new Produkmodel();
                $dok = $tmodel->find($id_produk);
                if(!empty($dok['gambar'])){
                    if(file_exists('gambar/'.$dok['gambar'])){
                        unlink('gambar/'.$dok['gambar']);
                    }
                }

                $update = [
                    "gambar" => $result['name']
                ];
                
                $tmodel->update($id_produk, $update);
                die(json_encode(array(
                    'OK' => 1,
                    'info' => $result
                )));
            }else{
                die(json_encode(array(
                    'OK' => 0,
                    'error' => array(
                        'code' => $ph->getErrorCode(),
                        'message' => $ph->getErrorMessage()
                    )
                )));
            }
        }else{
            die(json_encode(array(
                'OK' => 0,
                'error' => array(
                    'code' => $ph->getErrorCode(),
                    'message' => $ph->getErrorMessage()
                )
            )));
        }
    }

    public function view($id) {
        $data['user'] = $this->user->data;
        $tmodel = new Produkmodel();
        $builder = $tmodel->builder();
        $data['data'] = $builder->where("id_produk",$id)->get()->getRow();

        return view('admin/produk/view',$data);
    }

    public function update()
    {
        $data = array();
        $data['status'] = 'success';

        $id = $this->request->getPost('id',FILTER_SANITIZE_ADD_SLASHES);
        $request = [
            'kode_produk' => $this->request->getPost('kode_produk',FILTER_SANITIZE_ADD_SLASHES),
            'nama_produk' => $this->request->getPost('nama_produk',FILTER_SANITIZE_ADD_SLASHES),
            'kategori' => $this->request->getPost('kategori',FILTER_SANITIZE_ADD_SLASHES),
            'status' => $this->request->getPost('status',FILTER_SANITIZE_ADD_SLASHES),
        ];

        $validation = \Config\Services::validation();
        $validation->setRule('kode_produk', 'Kode Produk', 'required|is_unique[produk.kode_produk,produk.id_produk,'.$id.']');
        $validation->setRule('nama_produk', 'Nama Produk', 'required|is_unique[produk.nama_produk,produk.id_produk,'.$id.']');
        $validation->setRule('kategori', 'Kategori', 'required');
        // $validation->setRule('satuan', 'Satuan', 'required');
        $validation->setRule('status', 'Status', 'required');
        // $validation->setRule('gambar', 'Gambar', 'required');

        if (!$validation->run($request)) {
            return $this->fail($validation->getErrors(),400,null,'input');
        }else{
            $tmodel = new Produkmodel();
            $tmodel->db->transBegin();
            $tmodel->update($id,$request);
            if($tmodel->db->transStatus() === false){
                $tmodel->db->transRollback();
                return $this->fail($tmodel->errors(),400,null,'db');
            }else{
                $tmodel->db->transCommit();
                $session = session();
                $session->setFlashdata('id_produk', $id);
                return $this->respond($data,200);
            }
        }
    }

    public function delete()
    {
        $data = array();
        $data['status'] = 'success';

        $id = $this->request->getPost('id',FILTER_SANITIZE_ADD_SLASHES);

        $tmodel = new Produkmodel();
        $dok = $tmodel->find($id);
        $path = 'gambar/'.$dok['gambar'];
        
        $tmodel->db->transBegin();
        $tmodel->delete($id);
        if ($tmodel->db->transStatus() == true)
        {
            $tmodel->db->transCommit();
            if(file_exists($path)){
                unlink($path);
            }
            return $this->respond($data,200);
        }else{
            $tmodel->db->transRollback();
            return $this->fail(["error" => "Database Error!"],400,null,'db');
        }
    }
}
?>