<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * MenuManagement Controller
 * Versi batch-save — permission dikumpulkan di frontend,
 * dikirim satu request lewat save_matrix().
 */
class MenuManagement extends CI_Controller {

    private $roles = ['admin', 'ketua_rt', 'sekretaris', 'bendahara', 'warga'];

    public function __construct() {
        parent::__construct();
        $this->load->library('session');

        if (!$this->session->userdata('logged_in')) {
            redirect('auth');
        }
        if ($this->session->userdata('role') !== 'admin') {
            $this->session->set_flashdata('error', 'Akses ditolak. Hanya admin yang dapat mengelola menu.');
            redirect('dashboard');
        }

        $this->load->model('Menu_model');
        $this->load->library('form_validation');
    }

    // ═══════════════════════════════════════════════════════════
    // INDEX
    // ═══════════════════════════════════════════════════════════

    public function index() {
        $modules  = $this->Menu_model->get_modules_with_permissions();

        $parents  = [];
        $children = [];
        foreach ($modules as $m) {
            if (is_null($m->parent_id)) {
                $parents[$m->id] = $m;
            } else {
                $children[$m->parent_id][] = $m;
            }
        }

        $stats = [];
        foreach ($this->roles as $role) {
            $stats[$role] = $this->Menu_model->count_accessible_for_role($role);
        }

        $data = [
            'title'         => 'Pengaturan Menu & Hak Akses',
            'parents'       => $parents,
            'children'      => $children,
            'roles'         => $this->roles,
            'stats'         => $stats,
            'total_modules' => $this->Menu_model->count_active_modules(),
        ];

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('menu_management/index', $data);
        $this->load->view('templates/footer');
    }

    // ═══════════════════════════════════════════════════════════
    // SAVE MATRIX — BATCH (endpoint baru, menggantikan save_permission)
    // Menerima JSON: { "matrix": { "module_id": { "role": { "view":1, ... } } } }
    // Hanya berisi module+role yang benar-benar berubah (delta dari frontend).
    // ═══════════════════════════════════════════════════════════

    public function save_matrix() {
        header('Content-Type: application/json');

        /* Baca JSON body */
        $raw  = file_get_contents('php://input');
        $body = json_decode($raw, true);

        if (!$body || !isset($body['matrix']) || !is_array($body['matrix'])) {
            echo json_encode(['status' => 'error', 'msg' => 'Payload tidak valid']);
            return;
        }

        $matrix = $body['matrix'];

        /* Validasi setiap entry */
        foreach ($matrix as $module_id => $roles) {
            if (!is_numeric($module_id)) {
                echo json_encode(['status' => 'error', 'msg' => 'module_id tidak valid: ' . $module_id]);
                return;
            }
            foreach ($roles as $role => $perms) {
                if (!in_array($role, $this->roles)) {
                    echo json_encode(['status' => 'error', 'msg' => 'Role tidak valid: ' . $role]);
                    return;
                }
                $allowed_keys = ['view', 'create', 'edit', 'delete'];
                foreach (array_keys($perms) as $k) {
                    if (!in_array($k, $allowed_keys)) {
                        echo json_encode(['status' => 'error', 'msg' => 'Action tidak valid: ' . $k]);
                        return;
                    }
                }
            }
        }

        /* Bangun format yang diharapkan save_permission_matrix() */
        $normalized = [];
        foreach ($matrix as $module_id => $roles) {
            foreach ($roles as $role => $perms) {
                $normalized[(int)$module_id][$role] = [
                    'view'   => (int)($perms['view']   ?? 0),
                    'create' => (int)($perms['create'] ?? 0),
                    'edit'   => (int)($perms['edit']   ?? 0),
                    'delete' => (int)($perms['delete'] ?? 0),
                ];
            }
        }

        $ok = $this->Menu_model->save_permission_matrix($normalized);

        echo json_encode([
            'status'  => $ok ? 'ok' : 'error',
            'msg'     => $ok ? 'Semua izin tersimpan' : 'Gagal menyimpan ke database',
            'updated' => count($normalized),
        ]);
    }

    // ═══════════════════════════════════════════════════════════
    // TOGGLE MODULE ACTIVE (tetap langsung, bukan batch)
    // ═══════════════════════════════════════════════════════════

    public function toggle_module() {
        header('Content-Type: application/json');
        $id = (int)$this->input->post('id');

        if (!$id) {
            echo json_encode(['status' => 'error', 'msg' => 'ID tidak valid']);
            return;
        }

        $ok  = $this->Menu_model->toggle_active($id);
        $mod = $this->Menu_model->get_module_by_id($id);

        echo json_encode([
            'status'    => $ok ? 'ok' : 'error',
            'is_active' => $mod ? (int)$mod->is_active : 0,
            'msg'       => $ok ? ($mod->is_active ? 'Menu diaktifkan' : 'Menu dinonaktifkan') : 'Gagal',
        ]);
    }

    // ═══════════════════════════════════════════════════════════
    // CRUD MODULE
    // ═══════════════════════════════════════════════════════════

    public function tambah_module() {
        $data = [
            'title'   => 'Tambah Modul Menu',
            'parents' => $this->Menu_model->get_parent_modules(),
            'mod'     => null,
        ];

        $this->form_validation->set_rules('slug',  'Slug',  'required|is_unique[menu_modules.slug]');
        $this->form_validation->set_rules('label', 'Label', 'required');

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('menu_management/form_module', $data);
            $this->load->view('templates/footer');
        } else {
            $new_id = $this->Menu_model->insert_module([
                'parent_id'  => $this->input->post('parent_id') ?: null,
                'slug'       => $this->input->post('slug'),
                'label'      => $this->input->post('label'),
                'icon'       => $this->input->post('icon') ?: 'bi bi-circle',
                'url'        => $this->input->post('url'),
                'sort_order' => (int)$this->input->post('sort_order'),
                'is_active'  => 1,
                'created_at' => date('Y-m-d H:i:s'),
            ]);

            foreach ($this->roles as $role) {
                $this->Menu_model->save_permission($new_id, $role, [
                    'can_view'   => ($role === 'admin') ? 1 : 0,
                    'can_create' => ($role === 'admin') ? 1 : 0,
                    'can_edit'   => ($role === 'admin') ? 1 : 0,
                    'can_delete' => ($role === 'admin') ? 1 : 0,
                ]);
            }

            $this->session->set_flashdata('success', 'Modul menu berhasil ditambahkan.');
            redirect('menu-management');
        }
    }

    public function edit_module($id) {
        $mod = $this->Menu_model->get_module_by_id($id);
        if (!$mod) {
            $this->session->set_flashdata('error', 'Modul tidak ditemukan.');
            redirect('menu-management');
        }

        $data = [
            'title'   => 'Edit Modul Menu',
            'mod'     => $mod,
            'parents' => $this->Menu_model->get_parent_modules(),
        ];

        $this->form_validation->set_rules('label', 'Label', 'required');

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('menu_management/form_module', $data);
            $this->load->view('templates/footer');
        } else {
            $this->Menu_model->update_module($id, [
                'parent_id'  => $this->input->post('parent_id') ?: null,
                'label'      => $this->input->post('label'),
                'icon'       => $this->input->post('icon') ?: 'bi bi-circle',
                'url'        => $this->input->post('url'),
                'sort_order' => (int)$this->input->post('sort_order'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

            $this->session->set_flashdata('success', 'Modul berhasil diperbarui.');
            redirect('menu-management');
        }
    }

    public function hapus_module($id) {
        $core_slugs = ['dashboard', 'warga', 'iuran', 'kas'];
        $mod = $this->Menu_model->get_module_by_id($id);

        if (!$mod) {
            $this->session->set_flashdata('error', 'Modul tidak ditemukan.');
            redirect('menu-management');
        }

        if (in_array($mod->slug, $core_slugs)) {
            $this->session->set_flashdata('error', 'Modul core tidak dapat dihapus.');
            redirect('menu-management');
        }

        $this->Menu_model->delete_module($id);
        $this->session->set_flashdata('success', 'Modul berhasil dihapus.');
        redirect('menu-management');
    }

    // ═══════════════════════════════════════════════════════════
    // COPY & RESET — tetap ada untuk kemungkinan penggunaan lain
    // (di view sudah diganti ke versi lokal, tapi endpoint ini
    //  masih bisa dipakai jika diperlukan)
    // ═══════════════════════════════════════════════════════════

    public function copy_permission() {
        header('Content-Type: application/json');
        $from = $this->input->post('from_role');
        $to   = $this->input->post('to_role');

        if (!in_array($from, $this->roles) || !in_array($to, $this->roles) || $from === $to) {
            echo json_encode(['status' => 'error', 'msg' => 'Role tidak valid']);
            return;
        }

        $ok = $this->Menu_model->copy_permissions($from, $to);
        echo json_encode([
            'status' => $ok ? 'ok' : 'error',
            'msg'    => $ok ? "Permission disalin dari $from ke $to" : 'Gagal',
        ]);
    }

    public function reset_permission() {
        header('Content-Type: application/json');
        $role = $this->input->post('role');

        if (!in_array($role, $this->roles)) {
            echo json_encode(['status' => 'error', 'msg' => 'Role tidak valid']);
            return;
        }

        $ok = $this->Menu_model->reset_role_permissions($role);
        echo json_encode([
            'status' => $ok ? 'ok' : 'error',
            'msg'    => $ok ? "Permission $role direset ke 0" : 'Gagal',
        ]);
    }

    // ═══════════════════════════════════════════════════════════
    // API: get permissions for role (tidak berubah)
    // ═══════════════════════════════════════════════════════════

    public function get_role_permissions($role = null) {
        header('Content-Type: application/json');

        if (!$role || !in_array($role, $this->roles)) {
            echo json_encode(['status' => 'error']);
            return;
        }

        $perms = $this->Menu_model->get_permissions_for_role($role);
        echo json_encode(['status' => 'ok', 'permissions' => $perms]);
    }
}