<?php namespace App\Controllers;

class Superadmin extends BaseController {
    protected $db;

    public function __construct() {
        $this->db = \Config\Database::connect();
    }

    public function dashboard() {
        $data['total_user'] = $this->db->table('users')->countAll();
        $data['total_menu'] = $this->db->table('menus')->countAll();
        $data['total_prestasi'] = $this->db->table('prestasi')->countAll();
        return view('superadmin/dashboard', $data);
    }

    // --- MANAJEMEN MENU DINAMIS ---
    public function menu_index() {
        $data['menus'] = $this->db->table('menus')->orderBy('urutan', 'ASC')->get()->getResultArray();
        return view('superadmin/menu_manager', $data);
    }

    public function menu_store() {
        $rules = [
            'nama_menu' => 'required|alpha_numeric_space',
            'url_rute'  => 'required',
            'role_akses'=> 'required' // Array dari form checklist
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->with('error', 'Validasi form menu gagal.');
        }

        $roles = implode(',', $this->request->getPost('role_akses'));

        $this->db->table('menus')->insert([
            'nama_menu'  => esc($this->request->getPost('nama_menu')),
            'url_rute'   => esc($this->request->getPost('url_rute')),
            'ikon'       => esc($this->request->getPost('ikon')),
            'role_akses' => $roles,
            'urutan'     => esc($this->request->getPost('urutan'))
        ]);

        return redirect()->to('/superadmin/menu')->with('success', 'Menu Baru Berhasil Di-inject ke dalam Sistem.');
    }

    public function menu_delete($id) {
        $this->db->table('menus')->delete(['id' => $id]);
        return redirect()->to('/superadmin/menu')->with('success', 'Menu sukses dihapus.');
    }

    // --- KONFIGURASI WEB GLOBAL ---
    public function konfig_index() {
        $data['konfig'] = $this->db->table('konfig_sistem')->get()->getResultArray();
        return view('superadmin/konfig_manager', $data);
    }

    public function konfig_update() {
        $inputs = $this->request->getPost('konfig'); // Ambil array input key-value
        foreach ($inputs as $key => $value) {
            $this->db->table('konfig_sistem')
                     ->where('meta_key', $key)
                     ->update(['meta_value' => esc($value)]);
        }
        return redirect()->to('/superadmin/konfig')->with('success', 'Konfigurasi global diperbarui.');
    }
}