<?php

class Customization extends Cf_Controller
{
    public function __construct()
    {
        $this->load->model('customization_model');
        parent::__construct();
    }

    /**
     * @rbacName Customization
     * @rbacGroup Settings
     * @rbacAlias customization
     */
    public function index()
    {
        $requiredjs = [['customization.js']];
        $this->carabiner->js($requiredjs, $requiredjs, $combine = true, $minify = false);

        $data = $this->customization_model->getSettings();
        $data['title'] = 'Customization - Mission Portal';

        $data['company_logo'] = getCustomLogoFile();
        $this->template->load('template', 'appsetting/customization', $data);
    }

    /**
     * @rbacName Customization
     * @rbacGroup Settings
     * @rbacAlias customization
     */
    public function update()
    {
        try {
            $data = ['logo_on_pdf' => 0, 'logo_on_login' => 0, 'logo_on_header' => 0];
            $data = array_merge($data, $this->input->post());

            if (isset($data['removeLogo']) && $data['removeLogo'] == 1) {
                $this->customization_model->removeLogo(
                    $this->config->item('company_logo_file_name'),
                    $this->config->item('company_logo_path'),
                );
                $data['company_logo'] = '';
            }

            if (isset($_FILES['company_logo']['name']) && !empty($_FILES['company_logo']['name'])) {
                $fileName = $this->customization_model->uploadLogo($this->config->item('company_logo_path'));
                $data['company_logo'] = $fileName;
            }

            $this->customization_model->updateSettings($data);
        } catch (Exception $exception) {
            $this->session->set_flashdata('error', $exception->getMessage());
            log_message('error', 'Error updating customization: ' . $exception->getTraceAsString());
        }
        redirect('/settings/customization');
    }
}
