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

class Authority extends CI_Controller {

    public function __construct() {
        parent::__construct();
        ini_set('display_error',1);
        $this->load->model('Authority_model');
        $this->load->library('form_validation');
    }
     public function index($company_id = null) {
        error_reporting(1);
        //echo "Authority Controller Works!";
        //exit;
        ini_set('display_error',1);
        
        // Check login
        $login_id = $this->session->userdata('id');
        if (empty($login_id)) {
            redirect('login');
        }
        
        $role_id = $this->session->userdata('role_id');
        
        // For User role (3), only show assigned authorities
        if ($role_id == '3') {
            $allowed_authorities = get_allowed_authorities();
            if (!empty($allowed_authorities)) {
                $data['authorities'] = $this->Authority_model->get_by_ids($allowed_authorities);
            } else {
                $data['authorities'] = [];
            }
        } else {
            // Super Admin and Admin can see all
            $data['authorities'] = $this->Authority_model->get_all();
        }
        
        // Get company_id from URL parameter first, then fall back to session
        if (!empty($company_id)) {
            // Update session with the new company_id from URL
            $this->session->set_userdata('company_id', $company_id);
        } else {
            $company_id = $this->session->userdata('company_id');
        }
 
        $data['company_id'] = $company_id;
        $data['company_authority_status'] = [];
        
        if (!empty($company_id)) {
            // Get all company_authorities for selected company
            $ca_query = $this->db->query(
                "SELECT authority_id, is_enabled FROM company_authorities WHERE company_id = ?", 
                array($company_id)
            );

            $data['authority_has_uploads'] = [];
            foreach ($ca_query->result() as $row) {
                $data['company_authority_status'][$row->authority_id] = $row->is_enabled;
                $data['authority_has_uploads'][$row->authority_id] = $this->id_exists('sub_type', $row->authority_id);
                 //Check is authoiry is mapped with any type and user
                /*if ($this->id_exists('sub_type', $row->authority_id)) {
                    $data['has_uploads']=1;
                }*/
            }
            
            // Get company name for display
            $company = $this->db->get_where('company', ['id' => $company_id])->row();
            $data['company_name'] = $company ? $company->company_name : '';
        }

        //print_r($data); exit;
       
        $this->load->view('templates/header');
        $this->load->view('authority/index', $data);
        $this->load->view('layout/footer');
    }

    /*public function create() {
        // Permission check - manage authorities
        require_permission('authority.manage');

        $authority_name = trim($this->input->post('authority_name'));
        $normalized_name = $this->normalize_authority_name($authority_name);

        //$authority_name = trim($this->input->post('authority_name'));
        $alias = trim($this->input->post('alias'));

        $exists = $this->Authority_model->isAuthorityExistsNormalized($normalized_name);

        if ($exists) {
            $data['error_message'] = 'Authority name already exists!';
            $this->load->view('templates/header');
            $this->load->view('authority/create', $data);
            $this->load->view('layout/footer');
            return;
        }

        // Mandatory field
        $this->form_validation->set_rules('authority_name', 'Authority Name', 'required|trim',
            array('required' => 'The %s field is mandatory.')
        );

        // Non-mandatory field (no 'required' rule)
        $this->form_validation->set_rules('alias', 'Alias', 'trim');
        //$this->form_validation->set_rules('authority_name', 'authority_name', 'required|callback_alpha_num_space_apo');
        $this->form_validation->set_rules(
            'authority_name',
            'Authority Name',
            'required|trim|callback_valid_authority_name'
        );

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header');
            $this->load->view('authority/create');
            $this->load->view('layout/footer');
        } else {
            if ($this->input->post()) {  
                // Check if authority name already exists
                $exists = $this->Authority_model->isAuthorityExists($authority_name);

                if ($exists) {
                    $data['error_message'] = 'Authority name already exists!';
                    $this->load->view('templates/header');
                    $this->load->view('authority/create', $data);
                    $this->load->view('layout/footer');
                    return;
                }

                $this->Authority_model->insert([
                    'authority_name' => $this->input->post('authority_name'),
                    'alias_name' => $this->input->post('alias'),
                    'status' => '1',
                    'is_delete' => 0,
                    'created_date' => date('Y-m-d')
                ]);

                // Get the inserted authority ID
                $authority_id = $this->db->insert_id();
                $current_company_id = $this->session->userdata('company_id');

                // Auto-copy to company_authorities for ALL companies
                // Enabled only for the creating company, disabled for others
                $companies = $this->db->select('id')->where('status', '1')->get('company')->result();
                foreach ($companies as $company) {
                    $this->db->insert('company_authorities', [
                        'company_id' => $company->id,
                        'authority_id' => $authority_id,
                        'is_enabled' => ($company->id == $current_company_id) ? true : false,
                        'created_at' => date('Y-m-d H:i:s')
                    ]);
                }

                $this->session->set_flashdata('message_type', 'success');
                $this->session->set_flashdata('message_name', 'Authority added successfully!');
                redirect('authority');
            }
        }
    }*/

    public function create()
    {
        // Permission check
        require_permission('authority.manage');
        require_edit_permission('authority');

        // Validation rules
        $this->form_validation->set_rules(
            'authority_name',
            'Authority Name',
            'required|trim|callback_valid_authority_name',
            ['required' => 'The %s field is mandatory.']
        );
        $this->form_validation->set_rules('alias', 'Alias', 'trim');

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header');
            $this->load->view('authority/create');
            $this->load->view('layout/footer');
            return;
        }

        // ---------- AFTER VALIDATION ----------
        $authority_name = trim($this->input->post('authority_name'));
        $alias          = trim($this->input->post('alias'));

        // Normalize for duplicate check
        $normalized_name = $this->normalize_authority_name($authority_name);

        // SINGLE duplicate check (normalized)
        if ($this->Authority_model->isAuthorityExistsNormalized($normalized_name)) {
            $data['error_message'] = 'Authority name already exists!';
            $this->load->view('templates/header');
            $this->load->view('authority/create', $data);
            $this->load->view('layout/footer');
            return;
        }
        
        // Check for duplicate alias name
        if (!empty($alias) && check_duplicate_name('authority', 'alias_name', $alias, null, ['status' => '1'])) {
            $data['error_message'] = 'Alias name already exists!';
            $this->load->view('templates/header');
            $this->load->view('authority/create', $data);
            $this->load->view('layout/footer');
            return;
        }

        // Insert authority
        $this->Authority_model->insert([
            'authority_name' => $authority_name,
            'alias_name'     => $alias,
            'status'         => '1',
            'is_delete'      => 0,
            'created_date'  => date('Y-m-d')
        ]);

        $authority_id = $this->db->insert_id();
        $current_company_id = $this->session->userdata('company_id');

        // Auto-map authority to all companies
        $companies = $this->db->select('id')->where('status', '1')->get('company')->result();
        foreach ($companies as $company) {
            $this->db->insert('company_authorities', [
                'company_id'   => $company->id,
                'authority_id' => $authority_id,
                'is_enabled'   => ($company->id == $current_company_id),
                'created_at'   => date('Y-m-d H:i:s')
            ]);
        }

        $this->session->set_flashdata('message_type', 'success');
        $this->session->set_flashdata('message_name', 'Authority added successfully!');
        redirect('authority');
    }


    public function edit($id) {
        // Permission check - manage authorities
        require_permission('authority.manage');
        require_edit_permission('authority');
        
        //Check is authoiry is mapped with any type and user
        if ($this->id_exists('sub_type', $id)) {
            $this->session->set_flashdata('message_type', 'error');
            $this->session->set_flashdata('message_name', 'Edit not allowed — Authority in use.');
            redirect('authority');
            return;
        }

        $data['authority'] = $this->Authority_model->get($id);
         // Mandatory field
        $this->form_validation->set_rules('authority_name', 'Authority Name', 'required|trim',
            array('required' => 'The %s field is mandatory.')
        );

        // Non-mandatory field (no 'required' rule)
        $this->form_validation->set_rules('alias', 'Alias', 'trim');

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header');
            $this->load->view('authority/edit_authority', $data);
            $this->load->view('layout/footer');
        } else {
            $authority_name = trim($this->input->post('authority_name'));

            // ✅ Check for duplicate (excluding current record)
            $exists = $this->Authority_model->isAuthorityExists($authority_name, $id);

            if ($exists) {
                $data['error_message'] = 'Authority name already exists!';
                $this->load->view('templates/header');
                $this->load->view('authority/edit_authority', $data);
                $this->load->view('layout/footer');
                return;
            }
            
            // Check for duplicate alias name (excluding current record)
            $alias_name = trim($this->input->post('alias_name'));
            if (!empty($alias_name) && check_duplicate_name('authority', 'alias_name', $alias_name, $id, ['status' => '1'])) {
                $data['error_message'] = 'Alias name already exists!';
                $this->load->view('templates/header');
                $this->load->view('authority/edit_authority', $data);
                $this->load->view('layout/footer');
                return;
            }

            $this->Authority_model->update($id, [
                'authority_name' => $this->input->post('authority_name'),
                'alias_name' => $this->input->post('alias_name')
            ]);

            $this->session->set_flashdata('message_type', 'success');
            $this->session->set_flashdata('message_name', 'Authority updated successfully!');
            redirect('authority');
        }
    }

    public function delete($id) {
        // Permission check - manage authorities
        require_permission('authority.manage');
        require_delete_permission('authority');
        
        //Check is authoiry is mapped with any type and user
        if ($this->id_exists('sub_type', $id)) {
            $this->session->set_flashdata('message_type', 'error');
            $this->session->set_flashdata('message_name', 'Delete not allowed — Authority in use.');
            redirect('authority');
            return;
        }

        $this->Authority_model->delete($id);

        if ($this->db->affected_rows() > 0) {
            $this->session->set_flashdata('message_type', 'success');
            $this->session->set_flashdata('message_name', 'Authority deleted successfully!');
        }
        else {
        $this->session->set_flashdata('message_type', 'error');
        $this->session->set_flashdata('message_name', 'Authority not found or already deleted.');
        }

        redirect('authority');
    }

    public function toggle_status($id) {
        // Permission check - manage authorities
        require_permission('authority.manage');
        require_edit_permission('authority');

        //Check is authoiry is mapped with any type and user
        if ($this->id_exists('sub_type', $id)) {
            $this->session->set_flashdata('message_type', 'error');
            $this->session->set_flashdata('message_name', 'Deactivation not allowed — authority in use.');
            redirect('authority');
            return;
        }

        $authority = $this->Authority_model->get($id); 

        if ($authority) {
            $new_status = ($authority->status == '0') ? '1' : '0';
            $this->Authority_model->update_status($id, $new_status);

            if ($this->db->affected_rows() > 0) {
                $this->session->set_flashdata('message_type', 'success');
                $this->session->set_flashdata('message_name', 'Authority deleted successfully!');
            }
            else {
                $this->session->set_flashdata('message_type', 'error');
                $this->session->set_flashdata('message_name', 'Authority not found or already deleted.');
            }
        }

        redirect('authority');
    }

    public function alpha_num_space_apo($str)
    {
        if (preg_match("/^[a-zA-Z0-9' ]+$/", $str)) {
            return TRUE;
        } else {
            $this->form_validation->set_message('alpha_num_space_apo', 'The {field} field may only contain alphabets, numbers, spaces, and apostrophes.');
            return FALSE;
        }
    }

    // 🔹 Private helper function to check if a record exists
    private function id_exists($table, $id)
    {
        return $this->db->where('authority_id', $id)
                        ->where('status', '1')
                        ->limit(1)
                        ->count_all_results($table) > 0;
    }

    public function viewAuthority($id, $company_id = null)
    {
        // Check login - all logged-in users can view
        $login_id = $this->session->userdata('id');
        if (empty($login_id)) {
            redirect('login');
        }

        if ($company_id) {
            $this->session->set_userdata('company_id', $company_id);
        }

        $authority = $this->Authority_model->get($id);
        if (!$authority) {
            show_404();
        }

        $data['view_mode']      = 'authority';
        $data['authority']      = $authority;
        //$data['upload_count']   = $this->Authority_model->count_usage($id);

        $this->load->view('templates/header');
        $this->load->view('authority/view_authority', $data);
        $this->load->view('layout/footer');
    }

    public function valid_authority_name($str)
    {
        // Allow ONLY alphabets, numbers, space, -, /, '
        if (!preg_match("/^[a-zA-Z0-9\s\-\/']+$/", $str)) {
            $this->form_validation->set_message(
                'valid_authority_name',
                "Authority Name can contain only letters, numbers, space, -, / and '"
            );
            return false;
        }
        return true;
    }

    function normalize_authority_name($name)
    {
        return preg_replace("/[\s\-\/']+/", '', strtolower($name));
    }

}