<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\PackageModel;
use App\Models\CustomerModel;

class Package extends BaseController
{


    private $PackageModel;
    private $CustomerModel;

    public function __construct()
    {

        $this->PackageModel      = new PackageModel();   
        $this->CustomerModel      = new CustomerModel();   
    }

    public function index()
    {
        

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

        $data   = [
            'title' => "Paket Internet",
        ];

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

    }

    public function add()
    {


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

        $data = [
            'title' => "Tambah Paket Internet"
        ];

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


    public function detail($id = null)
    {


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


        $this->GoodModel->select('tbl_good.*, tbl_area.name AS area_name');
        $this->GoodModel->join('tbl_area','tbl_area.id=tbl_good.area_id');
        $row = $this->GoodModel->find($id);


        $data = [
            'title' => "Detail Barang",
            'code'  => $row->unique_id
        ];

        return  view('app/good/detail-qrcode/detail-qrcode-css', $data) .
        view('app/good/detail-qrcode/detail-qrcode', $data) .
        view('app/good/detail-qrcode/detail-qrcode-js', $data);
    }

    public function save()
    {


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

        $request    = json_decode(json_encode($this->request->getPOST()));
        $rules = [
            'name' => [
                'rules' => 'required|min_length[3]|max_length[256]',
                'errors' => [
                    'required'   => 'Nama wajib diisi',
                    'min_length' => 'Nama minimal 3 karakter',
                    'max_length' => 'Nama tidak boleh lebih dari 256 karakter',
                ]
            ],
            'price' => [
                'rules' => 'required|numeric|greater_than_equal_to[1]',
                'errors' => [
                    'required' => 'Harga wajib diisi',
                    'numeric' => 'Harga harus berupa angka',
                    'greater_than_equal_to' => 'Harga tidak boleh negatif atau 0'
                ]
            ],
            // 'description' => [
            //     'rules' => 'required|min_length[3]|max_length[1000]',
            //     'errors' => [
            //         'required' => 'Keterangan wajib diisi',
            //         'min_length' => 'Keterangan minimal 3 karakter',
            //         'max_length' => 'Keterangan maksimal 1000 karakter'
            //     ]
            // ]
        ];


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

            

        $data = [
            'name'          => $request->name,
            'price'         => $request->price,
            'description'   => !empty($request->description) ? $request->description : "-",
            'created_by'    => session()->get('id'),
            'created_at'    => date('Y-m-d H:i:s'),
        ];

        if(!$this->PackageModel->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("Package","Create","User $nameUser berhasil membuat data paket internet $request->name ",$userId);

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


    }


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

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

    public function delete()
    {


        haveAccess(3,"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->CustomerModel->where('package_id',$request->id);
        $isExitsPac = $this->CustomerModel->first();
        if(!empty((array)$isExitsPac)){
            
            return $this->response->setJSON([
                'code'      => 200,
                'success'   => false,
                'message'   => "Data desa tidak bisa dihapus dikarenakan sudah digunakan di beberapa pelanggan"
            ]);            
        }


        $this->PackageModel->where('id', $request->id);
        if(!$this->PackageModel->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("Package","Delete","User $nameUser berhasil menghapus data paket internet",$userId);

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

    }


    public function edit($id = null)
    {


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

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

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

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



    public function update()
    {


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

        $request    = json_decode(json_encode($this->request->getPOST()));
        $rules = [
            'name' => [
                'rules' => 'required|min_length[3]|max_length[256]',
                'errors' => [
                    'required'   => 'Nama wajib diisi',
                    'min_length' => 'Nama minimal 3 karakter',
                    'max_length' => 'Nama tidak boleh lebih dari 256 karakter',
                ]
            ],
            'price' => [
                'rules' => 'required|numeric|greater_than_equal_to[1]',
                'errors' => [
                    'required' => 'Harga wajib diisi',
                    'numeric' => 'Harga harus berupa angka',
                    'greater_than_equal_to' => 'Harga tidak boleh negatif atau 0'
                ]
            ],
            // 'description' => [
            //     'rules' => 'required|min_length[3]|max_length[1000]',
            //     'errors' => [
            //         'required' => 'Keterangan wajib diisi',
            //         'min_length' => 'Keterangan minimal 3 karakter',
            //         'max_length' => 'Keterangan maksimal 1000 karakter'
            //     ]
            // ]
        ];


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

        
        $data = [
            'name'               => $request->name,
            'price'              => $request->price,
            'description'        => !empty($request->description) ? $request->description : "-",
            'updated_by'         => session()->get('id'),
            'updated_at'         => date('Y-m-d H:i:s'),
        ];

        if(!$this->PackageModel->update($request->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("Package","Update","User $nameUser berhasil mengubah data paket internet $request->name ",$userId);

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


    }



    public function getAllPackageName()
    {
        $page  = $this->request->getPOST('page') ? $this->request->getPOST('page') - 1 : 0;
        $limit = $this->request->getPOST('limit') ? $this->request->getPOST('limit') : 30;

        $this->PackageModel->name          = $this->request->getPOST('name');
        $this->PackageModel->limit         = $limit;
        $this->PackageModel->start         = ($page * $limit);

        echo $this->PackageModel->getAllPackageName();
    }



}

