<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\AdminModel;
use CodeIgniter\Config\Config;
use CodeIgniter\Database\Query;
use CodeIgniter\API\ResponseTrait;

class Admin extends BaseController
{
    use ResponseTrait;
    var $admin;
    function __construct()
    {
        $this->admin = new AdminModel();
    }
    public function getIndex()
    {
        return view('admin/auth/admin_list');
    }
    public function getData()
    {
        $request = service('request');

        $draw = $request->getVar('draw');
        $row = (int)$request->getVar('start'); // Pastikan tipe integer
        $rowperpage = (int)$request->getVar('length'); // Pastikan tipe integer

        $columnIndex = $request->getVar('order')[0]['column'];
        $columnName = $request->getVar('columns')[$columnIndex]['data'];
        $columnSortOrder = $request->getVar('order')[0]['dir'];
        $searchValue = $request->getVar('search')['value'];

        // Total Records without Filtering
        $totalRecords = $this->admin->countAll();
        $totalRecordsWithFilter = $this->admin
            ->where('id !=', '0')
            ->like('name', $searchValue)
            ->countAllResults();

        // Fetch Records
        $orderBy = ($columnName == '') ? 'id DESC' : $columnName . ' ' . $columnSortOrder;
        $data = $this->admin
            ->select('*')
            ->where('id !=', '0')
            ->like('name', $searchValue)
            ->orderBy($orderBy)
            ->limit($rowperpage, $row) // Menggunakan nilai yang sudah di-cast ke integer
            ->get()
            ->getResult();

        $response = [
            'draw' => intval($draw),
            'iTotalRecords' => $totalRecordsWithFilter,
            'iTotalDisplayRecords' => $totalRecords,
            'aaData' => $data
        ];

        return $this->response->setJSON($response);
    }
    function getAdd()
    {
        $data['title'] = "Tambah Admin";
        $data['detail'] = [];
        $data['action'] = "add";
        $data['alert'] = "";
        $data['tombol'] = "+ Tambah Admin";
        echo view('admin/auth/admin_add', $data);
    }
    function getEdit($id)
    {
        $data['title'] = "Edit Data Admin";
        $data['detail'] = $this->admin->find($id);
        $data['action'] = "update";
        $data['alert'] = "Kosongkan password jika tidak ingin di ubah";
        $data['tombol'] = "Update Data";

        echo view('admin/auth/admin_add', $data);
    }
    function postData()
    {
        $action = $this->request->getVar('action');
        $rules = [
            'name' => [
                'rules' => 'required',
                'errors' => [
                    'required' => 'Nama harus diisi'
                ]
            ],
            'username' => [
                'rules' => 'required',
                'errors' => [
                    'required' => 'Username harus diisi',
                ]
            ],
            'email' => [
                'rules' => 'required|valid_email',
                'errors' => [
                    'required' => 'Email harus diisi',
                    'email' => 'Email tidak valid',
                ]
            ],
            'picture' => [
                'rules' => 'max_size[picture,2048]|ext_in[picture,png,jpg,jpeg,gif]',
                'errors' => [
                    'max_size' => "Ukuran File Terlalu Besar",
                    'ext_in' => 'Tipe file tidak diizinkan',
                ]
            ]
        ];
        if (!$this->validate($rules)) {
            $errors = $this->validator->getErrors();
            return $this->respond(['errors' => $errors], 400);
        }

        switch ($action) {
            case "add":
                $rulesadd = [
                    'password' => [
                        'rules' => 'required',
                        'errors' => [
                            'required' => 'Password harus diisi'
                        ]
                    ],
                    'username' => [
                        'rules' => 'required|is_unique[admin.username]',
                        'errors' => [
                            'is_unique' => 'Username sudah digunakan',
                        ]
                    ],
                    'email' => [
                        'rules' => 'required|is_unique[admin.email]|valid_email',
                        'errors' => [
                            'required' => 'Email harus diisi',
                            'email' => 'Email tidak valid',
                            'is_unique' => 'Email sudah digunakan',
                        ]
                    ],
                ];
                if (!$this->validate($rulesadd)) {
                    $errorsadd = $this->validator->getErrors();
                    return $this->respond(['errors' => $errorsadd], 400);
                }
                $requestData = array(
                    'name' => $this->request->getVar('name'),
                    'username' => $this->request->getVar('username'),
                    'email' => $this->request->getVar('email'),
                    'role' => $this->request->getVar('role'),
                    'password' => password_hash($this->request->getVar('password'), PASSWORD_BCRYPT)
                );
                $image = $this->request->getFile('picture');
                if ($image->isValid()) {
                    $newName = $image->getRandomName();
                    $image->move(ROOTPATH . 'public/' . getenv('dir.upload.profile'), $newName);
                    $requestData['picture'] = $newName;
                }

                $this->admin->insert($requestData);

                return $this->respond([
                    'status' => 'success',
                    'message' => 'Data inserted successfully'
                ], 200);
            case "update":

                $requestData = array(
                    'name' => $this->request->getVar('name'),
                    'username' => $this->request->getVar('username'),
                    'email' => $this->request->getVar('email'),
                    'role' => $this->request->getVar('role'),
                );
                if ($this->request->getVar('password') != "") {
                    $requestData['password'] = password_hash($this->request->getVar('password'), PASSWORD_BCRYPT);
                }
                $detail = $this->admin->find($this->request->getVar('id'));
                $image = $this->request->getFile('picture');
                if ($image->isValid()) {
                    $newName = $image->getRandomName();
                    $image->move(ROOTPATH . 'public/' . getenv('dir.upload.uploads'), $newName);
                    $requestData['picture'] = $newName;
                    if ($detail['picture']) {
                        $imagePath = ROOTPATH . 'public/' . getenv('dir.upload.uploads') . $detail['picture'];
                        if (file_exists($imagePath)) {
                            unlink($imagePath);
                        }
                    }
                }

                $this->admin->update($detail['id'], $requestData);
                return $this->respond([
                    'status' => 'success',
                    'message' => 'Data updated successfully'
                ], 200);
        }
    }
    function deleteData($id)
    {
        $nameimg = $this->admin->find($id);
        if ($nameimg['picture']) {
            $imagePath = ROOTPATH . 'public/' . getenv('dir.upload.profile') . $nameimg['picture'];
            if (file_exists($imagePath)) {
                unlink($imagePath);
            }
        }
        $deleted = $this->admin->delete($id);
        if ($deleted) {
            return $this->respond([
                'status' => 'success',
                'message' => 'Data deleted successfully'
            ], 200);
        } else {
            return $this->respond([
                'message' => 'Ops! Id tidak valid'
            ], 400);
        }
    }
}
