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

class Potong_plano extends CI_Controller
{
    private $menuLink = 'potong-plano';
    private $menuName = 'Potong Plano';
    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', 'Potong Plano | '.$this->title);
        close_session_for_readonly();
        $html = $this->template->load('main/themes', 'potong_plano/index', array(), TRUE);
        output_query_profile_headers('potong-plano');
        $this->output->set_output($html);
    }

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

        $menuLinks = array($this->menuLink, '/'.$this->menuLink);
        $menu = $this->db
            ->select('idmenu, idparent, nama_menu, aktif, id_level')
            ->from('menuadmin')
            ->where_in('link', $menuLinks)
            ->order_by('CASE WHEN idparent > 0 THEN 0 ELSE 1 END', '', FALSE)
            ->limit(1)
            ->get()
            ->row_array();

        if (!empty($menu['idmenu'])) {
            $updates = array();
            $removedDuplicate = FALSE;

            // Jika menu sudah ditempatkan sebagai submenu (mis. di Addon Tools),
            // hapus hanya entri level utama lama yang dibuat otomatis.
            if ((int) $menu['idparent'] > 0) {
                $rootDuplicates = $this->db
                    ->select('idmenu')
                    ->from('menuadmin')
                    ->where('idparent', 0)
                    ->where_in('link', $menuLinks)
                    ->get()
                    ->result_array();

                if (!empty($rootDuplicates)) {
                    $duplicateIds = array_map('intval', array_column($rootDuplicates, 'idmenu'));
                    $this->db->where_in('idmenu', $duplicateIds)->delete('menuadmin');
                    $removedDuplicate = $this->db->affected_rows() > 0;
                }
            }

            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 (!empty($updates)) {
                $this->db
                    ->where('idmenu', (int) $menu['idmenu'])
                    ->update('menuadmin', $updates);
            }

            if (!empty($updates) || $removedDuplicate) {
                $this->syncMenuUsersByLevels();
                $this->clearSidebarMenuCache();
            }

            return (int) $menu['idmenu'];
        }

        $nextOrderRow = $this->db
            ->select_max('urutan')
            ->where('idparent', 0)
            ->get('menuadmin')
            ->row_array();

        $nextOrder = isset($nextOrderRow['urutan']) ? ((int) $nextOrderRow['urutan'] + 1) : 1;

        $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-scissors',
            'aktif' => 'Y',
            'level' => NULL,
            'urutan' => $nextOrder,
        ));

        $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')) {
            return;
        }
        if (!function_exists('atur_menu')) {
            return;
        }

        $publishedLevels = $this->db
            ->select('id_level')
            ->from('hak_akses')
            ->where('publish', 'Y')
            ->get()
            ->result();

        if (empty($publishedLevels)) {
            return;
        }

        foreach ($publishedLevels as $row) {
            $levelId = isset($row->id_level) ? (int) $row->id_level : 0;
            if ($levelId <= 0) {
                continue;
            }

            $menuIds = atur_menu($levelId);
            $this->db
                ->where('id_level', $levelId)
                ->update('tb_users', array('idmenu' => $menuIds));
        }
    }

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