<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\OutModel;

class Out extends BaseController
{


    private $OutModel;

    public function __construct()
    {

        $this->OutModel      = new OutModel();   
    }

    public function index()
    {
    

        haveAccess(8,"is_read", session()->get('role_id'));

        $data   = [
            'title' => "Pengeluaran",
        ];

        return  view('app/out/main/out-main-css', $data) .
        view('app/out/main/out-main', $data) .
        view('app/out/main/out-main-js', $data);

    }

    public function add()
    {


        haveAccess(8,"is_create", session()->get('role_id'));

        $data = [
            'title' => "Tambah Pengeluaran"
        ];

        return  view('app/out/add/out-add-css', $data) .
        view('app/out/add/out-add', $data) .
        view('app/out/add/out-add-js', $data);
    }

    public function save()
    {


        haveAccess(8,"is_create", session()->get('role_id'));

        $request    = json_decode(json_encode($this->request->getPOST()));

        $rules = [
            'date' => [
                'rules' => 'required',
                'errors' => [
                    'required' => 'Tanggal wajib diisi',
                ]
            ],
            'description' => [
                'rules' => 'required|min_length[6]',
                'errors' => [
                    'required' => 'Keterangan wajib diisi.',
                    'min_length' => 'Panjang Keterangan minimal 3 karakter.'
                ]
            ],
            'type' => [
                'rules' => 'required',
                'errors' => [
                    'required' => 'Tipe wajib dipilih',
                ]
            ],
            'total' => [
                'rules' => 'required|numeric',
                'errors' => [
                    'required' => 'Total harus diisi',
                    'numeric' => 'Total harus berupa angka',
                ]
            ]
        ];


        if (!$this->validate($rules)) {
            $message = $this->validator->getErrors();
            return $this->response->setJSON(['code' => 200, 'success' => false, 'message' => $message]);
        }
    

        if(empty($request->image)){
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Bukti gambar tidak boleh kosong"
            ]);
        }


        $data = [
            'date'    => $request->date,
            'type'    => $request->type,
            'total'    => $request->total,
            'description'    => $request->description,
            'created_by'    => session()->get('id'),
            'created_at'    => date('Y-m-d H:i:s'),
        ];


        preg_match("/^data:(image\/[a-zA-Z]+);base64,/", $request->image, $matches);
        $mime = $matches[1];
        $ext = explode('/', $mime)[1]; 
        $image = 'evidance-buy-' . date('Ymd_His') . '.' . $ext;

        $upload_dir = './uploads/evidance-buy/';        

        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }

        $img = str_replace(['data:image/'.$ext.';base64,', ' '], ['', '+'], $request->image);
        $dataImg = base64_decode($img);
        if ($dataImg === false) {
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Image yang anda kirimkan gagal disimpan. pastikan anda terkoneksi dengan internet"
            ]);
        }

        $file = $upload_dir . $image;
        file_put_contents($file, $dataImg);

        $data['evidance'] = $image;



        if(!$this->OutModel->insert($data)){
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Data gagal disimpan. pastikan anda terkoneksi dengan internet"
            ]);
        }


        $userId = session()->get('id');
        $nameUser = session()->get('name');
        insertLog("Out","Create","User $nameUser berhasil membuat data pengeluaran $request->type ",$userId);

        return $this->response->setJSON([
            'code'      => 200,
            'success'   => true,
            'message'   => "Data berhasil disimpan"
        ]);





    }


    // private function _uploadImage($upload_dir = './uploads/goods/', $image = 'default.png', $request)
    // {

    //     if ($image === 'default.png') {
    //         return false;
    //     }


    //     if (!is_dir($upload_dir)) {
    //         mkdir($upload_dir, 0777, true);
    //     }

    //     preg_match("/^data:(image\/[a-zA-Z]+);base64,/", $request->image, $matches);
    //     $mime = $matches[1];
    //     $ext = explode('/', $mime)[1]; 

    //     $img = str_replace(['data:image/'.$ext.';base64,', ' '], ['', '+'], $request->image);
    //     $data = base64_decode($img);

    //     if ($data === false) {
    //         return false;
    //     }

    //     // Tentukan lokasi file dan simpan data
    //     $file = $upload_dir . $image;

    //     return file_put_contents($file, $data) !== false;

    // }


    public function getAllData()
    {
        
        $this->OutModel->draw     = $this->request->getPOST('draw');
        $this->OutModel->start    = $this->request->getPOST('start');
        $this->OutModel->limit    = $this->request->getPOST('length');
        $this->OutModel->search   = $this->request->getPOST('search')['value'];
        $this->OutModel->columns  = $this->request->getPOST('columns');
        $this->OutModel->order    = $this->request->getPOST('order');

        echo $this->OutModel->getAllData();
    }

    public function delete()
    {


        haveAccess(8,"is_delete", session()->get('role_id'));

        $request;
        if ($this->request->hasHeader('Content-Type') && strpos($this->request->getHeaderLine('Content-Type'), 'application/json') !== false) {
            $request    = $this->request->getJSON();
        }else{
            $request    = $this->request->getPOST();
        }

        $request = json_decode(json_encode($request));


        $this->OutModel->where('id', $request->id);
        if(!$this->OutModel->delete()){

            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Data gagal dihapus. pastikan anda terkoneksi dengan internet"
            ]);
        }


        $userId = session()->get('id');
        $nameUser = session()->get('name');
        insertLog("User","Delete","User $nameUser berhasil menghapus data user",$userId);

        return $this->response->setJSON([
            'code'      => 200,
            'success'   => true,
            'message'   => "Data berhasil dihapus"
        ]);

    }


    public function edit($id = null)
    {


        haveAccess(8,"is_update", session()->get('role_id'));

        $row = $this->OutModel->find($id);

        $data = [
            'title' => "Edit Pengeluaran",
            'row'   => $row
        ];

        return  view('app/out/edit/out-edit-css', $data) .
        view('app/out/edit/out-edit', $data) .
        view('app/out/edit/out-edit-js', $data);
        
    }



    public function update()
    {

        haveAccess(8,"is_update", session()->get('role_id'));

        $request    = json_decode(json_encode($this->request->getPOST()));

        $rules = [
            'date' => [
                'rules' => 'required',
                'errors' => [
                    'required' => 'Tanggal wajib diisi',
                ]
            ],
            'description' => [
                'rules' => 'required|min_length[6]',
                'errors' => [
                    'required' => 'Keterangan wajib diisi.',
                    'min_length' => 'Panjang Keterangan minimal 3 karakter.'
                ]
            ],
            'type' => [
                'rules' => 'required',
                'errors' => [
                    'required' => 'Tipe wajib dipilih',
                ]
            ],
            'total' => [
                'rules' => 'required|numeric',
                'errors' => [
                    'required' => 'Total harus diisi',
                    'numeric' => 'Total harus berupa angka',
                ]
            ]
        ];


        if (!$this->validate($rules)) {
            $message = $this->validator->getErrors();
            return $this->response->setJSON(['code' => 200, 'success' => false, 'message' => $message]);
        }
    

        if(empty($request->image)){
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Bukti gambar tidak boleh kosong"
            ]);
        }

        $oldData = $this->OutModel->find($request->hide_id);

        $data = [
            'date'    => $request->date,
            'type'    => $request->type,
            'total'    => $request->total,
            'description'    => $request->description,
            'updated_by'    => session()->get('id'),
            'updated_at'    => date('Y-m-d H:i:s'),
        ];

        if($oldData->evidance!=$request->image){

            preg_match("/^data:(image\/[a-zA-Z]+);base64,/", $request->image, $matches);
            $mime = $matches[1];
            $ext = explode('/', $mime)[1]; 
            $image = 'evidance-buy-' . date('Ymd_His') . '.' . $ext;

            $upload_dir = './uploads/evidance-buy/';

            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }

            $img = str_replace(['data:image/'.$ext.';base64,', ' '], ['', '+'], $request->image);
            $dataImg = base64_decode($img);
            if ($dataImg === false) {
                return $this->response->setJSON([
                    'code'      => 200,
                    'success'   => false,
                    'message'   => "Image yang anda kirimkan gagal disimpan. pastikan anda terkoneksi dengan internet"
                ]);
            }

            $file = $upload_dir . $image;
            file_put_contents($file, $dataImg);

            $data['evidance'] = $image;

            try {
                 $imagePath = './uploads/evidance-buy/' . $oldData->evidance;

                 if (is_file($imagePath) && strtolower($oldData->evidance) !== 'default.png') {
                    
                     if (!unlink($imagePath)) {
                     }
                 }
            } catch (Exception $e) {

            }

        }


        if(!$this->OutModel->update($request->hide_id,$data)){
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Data gagal disimpan. pastikan anda terkoneksi dengan internet"
            ]);
        }


        $userId = session()->get('id');
        $nameUser = session()->get('name');
        insertLog("Out","update","User $nameUser berhasil mengubah data pengeluaran $request->type ",$userId);

        return $this->response->setJSON([
            'code'      => 200,
            'success'   => true,
            'message'   => "Data berhasil disimpan"
        ]);



    }



}

