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

class Admin extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(['url', 'form']);
        $this->load->library('form_validation');
        $this->load->model(['Menu_model', 'Layout_config_model']);
    }

    public function menus()
    {
        $data['menus'] = $this->Menu_model->get_admin_list();
        $data['layout'] = $this->Layout_config_model->get_config();
        $this->load->view('admin/menus', $data);
    }

    public function save_menu()
    {
        $payload = $this->input->post();
        $id = $payload['id'] ?? null;
        unset($payload['id']);
        $payload['enabled'] = isset($payload['enabled']) ? 1 : 0;
        $payload['parent_id'] = $payload['parent_id'] ?: null;
        $this->Menu_model->save($payload, $id ? (int) $id : null);
        redirect('admin/menus');
    }

    public function delete_menu($id)
    {
        $this->Menu_model->delete((int) $id);
        redirect('admin/menus');
    }

    public function layout()
    {
        $data['layout'] = $this->Layout_config_model->get_config();
        $this->load->view('admin/layout', $data);
    }

    public function save_layout()
    {
        $brandName = config_item('company_name') ?: (config_item('website_name') ?: (config_item('copyright_name') ?: 'ERP'));
        $payload = [
            'header_label' => $this->input->post('header_label'),
            'sidebar_visible' => $this->input->post('sidebar_visible') ? 1 : 0,
            'header_visible' => $this->input->post('header_visible') ? 1 : 0,
            'footer_visible' => $this->input->post('footer_visible') ? 1 : 0,
            'theme' => $this->input->post('theme') ?: 'dark',
            'primary_color' => $this->input->post('primary_color') ?: '#9c8cff',
            'accent_color' => $this->input->post('accent_color') ?: '#6366f1',
            'logo_text' => $this->input->post('logo_text') ?: $brandName,
        ];
        $this->Layout_config_model->save($payload);
        redirect('admin/layout');
    }
}
