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

class Kalkulator_huruf_timbul extends CI_Controller
{
    private $menuLink = 'kalkulator-huruf-timbul';
    private $menuName = 'Kalkulator Huruf Timbul';
    private $menuLevels = '1,2,3,4,5,6';

    public function __construct()
    {
        parent::__construct();
        cek_session_login();
        $this->title = info()['title'];
        $this->ensureMenuEntry();
    }

    public function index()
    {
        cek_menu_akses();
        $this->template->set('title', $this->menuName.' | '.$this->title);
        close_session_for_readonly();
        $html = $this->template->load('main/themes', 'kalkulator_huruf_timbul/index', array(), TRUE);
        output_query_profile_headers('kalkulator-huruf-timbul');
        $this->output->set_output($html);
    }

    private function ensureMenuEntry()
    {
        if (!$this->db->table_exists('menuadmin')) {
            return 0;
        }

        $menu = $this->db
            ->select('idmenu, nama_menu, aktif, id_level')
            ->where_in('link', array($this->menuLink, '/'.$this->menuLink))
            ->limit(1)
            ->get('menuadmin')
            ->row_array();

        if (!empty($menu['idmenu'])) {
            $updates = array();
            if ((string) $menu['nama_menu'] !== $this->menuName) $updates['nama_menu'] = $this->menuName;
            if ((string) $menu['aktif'] !== 'Y') $updates['aktif'] = 'Y';
            if ((string) $menu['id_level'] !== $this->menuLevels) $updates['id_level'] = $this->menuLevels;
            if ($updates) {
                $this->db->where('idmenu', (int) $menu['idmenu'])->update('menuadmin', $updates);
                $this->syncMenuUsersByLevels();
                $this->clearSidebarMenuCache();
            }
            return (int) $menu['idmenu'];
        }

        $order = $this->db->select_max('urutan')->where('idparent', 0)->get('menuadmin')->row_array();
        $this->db->insert('menuadmin', array(
            'idparent' => 0,
            'id_level' => $this->menuLevels,
            'nama_menu' => $this->menuName,
            'link' => $this->menuLink,
            'target' => '_self',
            'link_on' => 'N',
            'treeview' => '',
            'classes' => '',
            'classicon' => 'Y',
            'icon' => 'fa-font',
            'aktif' => 'Y',
            'level' => NULL,
            'urutan' => isset($order['urutan']) ? ((int) $order['urutan'] + 1) : 1,
        ));

        $menuId = (int) $this->db->insert_id();
        if ($menuId > 0) {
            $this->syncMenuUsersByLevels();
            $this->clearSidebarMenuCache();
        }
        return $menuId;
    }

    private function syncMenuUsersByLevels()
    {
        if (!$this->db->table_exists('tb_users') || !$this->db->table_exists('hak_akses') || !function_exists('atur_menu')) return;
        foreach ($this->db->select('id_level')->where('publish', 'Y')->get('hak_akses')->result() as $row) {
            $levelId = isset($row->id_level) ? (int) $row->id_level : 0;
            if ($levelId > 0) $this->db->where('id_level', $levelId)->update('tb_users', array('idmenu' => atur_menu($levelId)));
        }
    }

    private function clearSidebarMenuCache()
    {
        foreach (glob(APPPATH.'cache'.DIRECTORY_SEPARATOR.'sidebar_menu_*') ?: array() as $file) {
            if (is_file($file)) @unlink($file);
        }
    }
}
