<?php
namespace App\Controllers;

use App\Controllers\BaseController;
use Config\Database;

class Setting extends BaseController
{
    public function roles()
    {
        $db = Database::connect();

        $data['roles'] = $db->table('roles')->get()->getResult();

        return view('setting/roles', $data);
    }

    public function menus()
    {
        $db = \Config\Database::connect();

        $data['menus'] = $db->table('menus')
            ->orderBy('parent_id')
            ->orderBy('sort_order')
            ->get()
            ->getResult();

        return view('setting/menus', $data);
    }

    public function access($role_id  = null)
    {
        $db = Database::connect();

        // Ambil role
        $data['role'] = $db->table('roles')
            ->where('id', $role_id)
            ->get()
            ->getRow();

        // Ambil semua menu
        $data['menus'] = $db->table('menus')
            ->orderBy('parent_id')
            ->orderBy('sort_order')
            ->get()
            ->getResult();

        // Ambil akses role
        $accessRaw = $db->table('menu_roles')
            ->where('role_id', $role_id)
            ->get()
            ->getResult();

        // Convert jadi array: menu_id => object
        $access = [];
        foreach ($accessRaw as $a) {
            $access[$a->menu_id] = $a;
        }

        $data['access'] = $access;

        return view('setting/access', $data);
    }

    public function saveAccess()
    {
        $db = Database::connect();

        $role_id = $this->request->getPost('role_id');
        $menus = $this->request->getPost('menus');

        // Hapus akses lama dulu
        $db->table('menu_roles')->where('role_id', $role_id)->delete();

        // Simpan ulang
        if ($menus) {
            foreach ($menus as $menu_id => $perm) {

                $db->table('menu_roles')->insert([
                    'role_id' => $role_id,
                    'menu_id' => $menu_id,
                    'can_view' => isset($perm['view']) ? 1 : 0,
                    'can_create' => isset($perm['create']) ? 1 : 0,
                    'can_update' => isset($perm['update']) ? 1 : 0,
                    'can_delete' => isset($perm['delete']) ? 1 : 0,
                ]);
            }
        }

        return redirect()->to(site_url('setting/roles'))->with('success', 'Akses berhasil disimpan');
    }

    public function menusData()
    {
        $db = \Config\Database::connect();

        $data = $db->query("
        SELECT m.*,
               p.title AS parent_title
        FROM menus m
        LEFT JOIN menus p ON p.id = m.parent_id
        ORDER BY m.parent_id, m.sort_order
    ")->getResult();

        return $this->response->setJSON([
            'data' => $data
        ]);
    }
    public function editMenu($id)
    {
        $db = \Config\Database::connect();

        // Ambil data menu
        $menu = $db->table('menus')->where('id', $id)->get()->getRow();

        if (!$menu) {
            return redirect()->to(site_url('setting/menus'))->with('error', 'Menu tidak ditemukan');
        }

        // Ambil semua parent menu
        $parents = $db->table('menus')
            ->where('parent_id', 0)
            ->orWhere('parent_id', null)
            ->get()
            ->getResult();

        return view('setting/menu_edit', [
            'menu' => $menu,
            'parents' => $parents
        ]);
    }

    public function updateMenu()
    {
        $db = \Config\Database::connect();

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

        $data = [
            'title' => $this->request->getPost('title'),
            'url' => $this->request->getPost('url'),
            'icon' => $this->request->getPost('icon'),
            'parent_id' => $this->request->getPost('parent_id'),
            'sort_order' => $this->request->getPost('sort_order'),
            'is_active' => $this->request->getPost('is_active')
        ];

        $db->table('menus')->where('id', $id)->update($data);

        return redirect()->to(site_url('setting/menus'))->with('success', 'Menu berhasil diperbarui');
    }

    public function createMenu()
    {
        $db = \Config\Database::connect();

        // Ambil parent menu (hanya root)
        $data['parents'] = $db->table('menus')->where('parent_id', null)->get()->getResult();

        return view('setting/create_menu', $data);
    }


    public function storeMenu()
    {
        $db = \Config\Database::connect();

        $data = [
            'title' => $this->request->getPost('title'),
            'url' => $this->request->getPost('url'),
            'icon' => $this->request->getPost('icon'),
            'parent_id' => $this->request->getPost('parent_id') ?: null,
            'sort_order' => $this->request->getPost('sort_order'),
            'is_active' => $this->request->getPost('is_active'),
        ];

        $db->table('menus')->insert($data);

        return redirect()->to(site_url('setting/menus'))->with('success', 'Menu berhasil ditambahkan');
    }

    public function deleteMenu($id)
    {
        $db = \Config\Database::connect();

        // Cek data dulu
        $menu = $db->table('menus')->where('id', $id)->get()->getRow();

        if (!$menu) {
            return redirect()->to(site_url('setting/menus'))
                ->with('error', 'Menu tidak ditemukan');
        }

        // Hapus menu role yang terkait
        $db->table('menu_roles')->where('menu_id', $id)->delete();

        // Hapus menu itu sendiri
        $db->table('menus')->where('id', $id)->delete();

        return redirect()->to(site_url('setting/menus'))
            ->with('success', 'Menu berhasil dihapus');
    }

}
