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

/**
 * Company Document Heads Controller
 * 
 * Manages company-specific document head configurations.
 * Admin workflow for activating/deactivating document heads.
 * 
 * @version 1.0
 * @date 2026-01-15
 */
class CompanyDocHeads extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->helper(['url', 'form']);
        $this->load->library('session');
        
        // Check login
        if (!$this->session->userdata('id')) {
            redirect('login');
        }
    }

    /**
     * List all document heads for a company
     */
    public function index($company_id = null)
    {
        $this->session->set_userdata('menu', 'company_doc_heads');
        
        // Check login - all logged-in users can view
        $login_id = $this->session->userdata('id');
        if (empty($login_id)) {
            redirect('login');
        }
        
        // Company ID is required (comes from modal selection)
        // If accessed directly without company_id, show a message
        if (!$company_id) {
            // Show company selection page or redirect
            $this->session->set_flashdata('message_type', 'warning');
            $this->session->set_flashdata('message_name', 'Please select Company Doc Heads from the Masters menu to choose a company.');
            redirect('company/companies');
            return;
        }
        
        // Check company access
        require_company_access($company_id);
        
        // Get company details
        $company = $this->db->get_where('company', ['id' => $company_id])->row();
        if (!$company) {
            $this->session->set_flashdata('message_type', 'error');
            $this->session->set_flashdata('message_name', 'Company not found.');
            redirect('company/companies');
            return;
        }
        
        $data['company'] = $company;
        $data['selected_company_id'] = $company_id;
        $data['company_name'] = $company->company_name;
        
        // Get document heads for this company with status
        $data['doc_heads'] = $this->_getCompanyDocumentHeads($company_id);
        
        // Set header variables
        $data['current_menu'] = 'company_doc_heads';
        $data['current_sub_menu'] = 'companydocheads/index';
        
        $this->load->view('templates/header', $data);
        $this->load->view('company_doc_heads/index', $data);
        $this->load->view('layout/footer');
    }

    /**
     * Get document heads for a company with their status
     */
    private function _getCompanyDocumentHeads($company_id)
    {
        $sql = "
            SELECT 
                st.id as type_id,
                st.type_name,
                st.alias_name,
                st.frequency,
                st.document_start_date as master_start_date,
                a.authority_name,
                a.id as authority_id,
                cdh.id as company_doc_head_id,
                cdh.is_enabled,
                cdh.is_reviewed,
                cdh.custom_start_date,
                cdh.enabled_at,
                CASE 
                    WHEN cdh.id IS NULL THEN 'not_assigned'
                    WHEN cdh.is_enabled = TRUE THEN 'active'
                    WHEN cdh.is_reviewed = true THEN 'reviewed'
                    ELSE 'pending'
                END as status
            FROM sub_type st
            LEFT JOIN authority a ON CAST(st.authority_id AS INTEGER) = a.id
            LEFT JOIN company_document_heads cdh ON st.id = cdh.type_id AND cdh.company_id = ?
            WHERE st.status = '1'
            ORDER BY a.authority_name, st.type_name
        ";
        
        return $this->db->query($sql, [$company_id])->result();
    }

    /**
     * View/Edit a specific document head for a company
     */
    public function edit($company_id, $type_id)
    {
        $this->session->set_userdata('menu', 'company_doc_heads');
        
        // Check login - all logged-in users can view
        $login_id = $this->session->userdata('id');
        if (empty($login_id)) {
            redirect('login');
        }
        
        // Check company access
        require_company_access($company_id);
        
        // Get company details
        $company = $this->db->get_where('company', ['id' => $company_id])->row();
        if (!$company) {
            $this->session->set_flashdata('error', 'Company not found.');
            redirect('dashboard');
            return;
        }
        
        // Get document head details
        $doc_head = $this->db->select('st.*, a.authority_name')
            ->from('sub_type st')
            ->join('authority a', 'CAST(st.authority_id AS INTEGER) = a.id', 'left')
            ->where('st.id', $type_id)
            ->get()
            ->row();
        
        if (!$doc_head) {
            $this->session->set_flashdata('error', 'Document head not found.');
            redirect('companydocheads/index/' . $company_id);
            return;
        }
        
        // Get company-specific settings
        $company_settings = $this->db->get_where('company_document_heads', [
            'company_id' => $company_id,
            'type_id' => $type_id
        ])->row();
        
        // Get mandatory documents for this type
        $mandatory_docs = $this->db->select('cmd.*, d.document_name')
            ->from('company_mandatory_documents cmd')
            ->join('documents d', 'd.id = cmd.document_id')
            ->where('cmd.company_id', $company_id)
            ->where('cmd.type_id', $type_id)
            ->order_by('cmd.sort_order', 'ASC')
            ->get()
            ->result();
        
        // If no company-specific docs, get from master
        if (empty($mandatory_docs)) {
            $mandatory_docs = $this->db->query("
                SELECT md.*, d.document_name,
                    CASE 
                        WHEN LOWER(md.mandatory) IN ('yes', '1', 'true', 't') THEN true
                        ELSE false
                    END as is_mandatory
                FROM mandatory_documents md
                JOIN documents d ON d.id = md.document_id
                WHERE md.type_id = ?
                ORDER BY md.id
            ", [$type_id])->result();
        }
        
        // Get reminders
        $reminders = $this->db->get_where('company_document_head_reminders', [
            'company_id' => $company_id,
            'type_id' => $type_id
        ])->result();
        
        // If no company-specific reminders, get from master
        if (empty($reminders)) {
            $reminders = $this->db->query("
                SELECT sr.*,
                    COALESCE(sr.reminder_to_user::boolean, false) as reminder_to_user,
                    COALESCE(sr.reminder_to_admin::boolean, false) as reminder_to_admin,
                    COALESCE(sr.reminder_to_super_admin::boolean, false) as reminder_to_super_admin
                FROM sub_type_reminders sr
                WHERE sr.sub_type_id = ?
                ORDER BY sr.reminder_no
            ", [$type_id])->result();
        }
        
        // Check if this document head has any uploaded documents for this company
        $has_uploads = $this->db->where('type_id', $type_id)
            ->where('company_id', $company_id)
            ->where('is_deleted', 0)
            ->count_all_results('uploaded_documents');
        
        // View-only if user doesn't have edit permission OR document head has uploads
        $is_view_only = !can_edit() || ($has_uploads > 0);
        
        $data = [
            'company' => $company,
            'doc_head' => $doc_head,
            'company_settings' => $company_settings,
            'mandatory_docs' => $mandatory_docs,
            'reminders' => $reminders,
            'has_uploads' => $has_uploads,
            'is_view_only' => $is_view_only,
            'company_name' => $company->company_name,
            'current_menu' => 'company_doc_heads',
            'current_sub_menu' => 'companydocheads/edit'
        ];
        
        $this->load->view('templates/header', $data);
        $this->load->view('company_doc_heads/edit', $data);
        $this->load->view('layout/footer');
    }

    /**
     * Save document head settings and mark as reviewed
     */
    public function save()
    {
        // Permission check - edit permission required
        if (!can_edit()) {
            $this->session->set_flashdata('error', 'You do not have permission to edit.');
            redirect('dashboard');
            return;
        }
        
        $company_id = $this->input->post('company_id');
        $type_id = $this->input->post('type_id');
        $custom_start_date = $this->input->post('custom_start_date');

        $due_day = $this->input->post('custom_frequency_start_date');
        $due_month = $this->input->post('custom_due_in_same_next_month');
        
        // Check company access
        require_company_access($company_id);

        // ------------------------------
        // Mandatory field validations
        // ------------------------------
        if (empty($custom_start_date)) {
            $this->session->set_flashdata('message_type', 'error');
            $this->session->set_flashdata('message_name', 'Document start date is required.');
            redirect('companydocheads/edit/' . $company_id . '/' . $type_id);
            return;
        }

        if ($due_day === null || $due_day === '') {
            $this->session->set_flashdata('message_type', 'error');
            $this->session->set_flashdata('message_name', 'Due day is required.');
            redirect('companydocheads/edit/' . $company_id . '/' . $type_id);
            return;
        }

        if (!is_numeric($due_day) || $due_day < 1 || $due_day > 31) {
            $this->session->set_flashdata('message_type', 'error');
            $this->session->set_flashdata('message_name', 'Due day must be between 1 and 31.');
            redirect('companydocheads/edit/' . $company_id . '/' . $type_id);
            return;
        }

        if (!in_array($due_month, ['0', '1'], true)) {
            $this->session->set_flashdata('message_type', 'error');
            $this->session->set_flashdata('message_name', 'Please select whether due is in same month or next month.');
            redirect('companydocheads/edit/' . $company_id . '/' . $type_id);
            return;
        }

        // Validate start date against company start date
        $company = $this->db->get_where('company', ['id' => $company_id])->row();
        if ($custom_start_date && strtotime($custom_start_date) < strtotime($company->co_start_date)) {
            $this->session->set_flashdata('message_type', 'error');
            $this->session->set_flashdata('message_name', 
                'Document start date cannot be earlier than company start date (' . 
                date('d-M-Y', strtotime($company->co_start_date)) . ')');
            redirect('companydocheads/edit/' . $company_id . '/' . $type_id);
            return;
        }
        
        $user_id = $this->session->userdata('id');
        
        // Check if record exists
        $existing = $this->db->get_where('company_document_heads', [
            'company_id' => $company_id,
            'type_id' => $type_id
        ])->row();
        
        $data = [
            'custom_start_date' => ($custom_start_date !== '' && $custom_start_date !== null) ? $custom_start_date : null,
            'custom_frequency_start_date' => ($due_day !== '' && $due_day !== null) ? (int) $due_day : null,
            'custom_due_in_same_next_month' => ($due_month !== '' && $due_month !== null) ? (int) $due_month : null,
            'is_reviewed' => true,
            'updated_at' => date('Y-m-d H:i:s')
        ];
        
        if ($existing) {
            $this->db->where('id', $existing->id)->update('company_document_heads', $data);
        } else {
            $data['company_id'] = $company_id;
            $data['type_id'] = $type_id;
            $data['is_enabled'] = false;
            $data['created_by'] = $user_id;
            $data['created_at'] = date('Y-m-d H:i:s');
            $this->db->insert('company_document_heads', $data);
        }
        
        /*$this->session->set_flashdata('message_type', 'success');
        $this->session->set_flashdata('message_name', 'Document head settings saved and marked as reviewed.');
        redirect('companydocheads/index/' . $company_id);*/

        // ------------------------------------
        // AUTO-ACTIVATE AFTER SAVE
        // ------------------------------------
        if (can('company_doc_heads.activate')) {

            $this->load->model('Permission_model');

            $activateResult = $this->Permission_model->activate_document_head(
                $company_id,
                $type_id,
                $custom_start_date,
                $user_id
            );

            if (!$activateResult['success']) {
                $this->session->set_flashdata('message_type', 'warning');
                $this->session->set_flashdata(
                    'message_name',
                    'Settings saved, but activation failed: ' . $activateResult['message']
                );
                redirect('companydocheads/edit/' . $company_id . '/' . $type_id);
                return;
            }
        }

        // Success
        $this->session->set_flashdata('message_type', 'success');
        $this->session->set_flashdata(
            'message_name',
            'Document head saved and activated successfully.'
        );
        //redirect('companydocheads/index/' . $company_id);
        redirect('type/allType/' . $company_id);
        
    }

    /**
     * Activate a document head (AJAX)
     */
    public function activate()
    {
        header('Content-Type: application/json');
        
        // Permission check
        if (!can('company_doc_heads.activate') || !can_edit()) {
            echo json_encode(['success' => false, 'message' => 'Permission denied.']);
            return;
        }
        
        $company_id = $this->input->post('company_id');
        $type_id = $this->input->post('type_id');
        $custom_start_date = $this->input->post('custom_start_date');
        
        // Check company access
        if (!has_company_access($company_id)) {
            echo json_encode(['success' => false, 'message' => 'Company access denied.']);
            return;
        }
        
        $user_id = $this->session->userdata('id');
        
        // Use Permission_model to activate
        $result = $this->Permission_model->activate_document_head($company_id, $type_id, $custom_start_date, $user_id);
        
        echo json_encode($result);
    }

    /**
     * Deactivate a document head (AJAX)
     */
    public function deactivate()
    {
        header('Content-Type: application/json');
        
        // Permission check
        if (!can('company_doc_heads.activate') || !can_edit()) {
            echo json_encode(['success' => false, 'message' => 'Permission denied.']);
            return;
        }
        
        $company_id = $this->input->post('company_id');
        $type_id = $this->input->post('type_id');
        
        // Check company access
        if (!has_company_access($company_id)) {
            echo json_encode(['success' => false, 'message' => 'Company access denied.']);
            return;
        }
        
        // Use Permission_model to deactivate
        $result = $this->Permission_model->deactivate_document_head($company_id, $type_id);
        
        echo json_encode($result);
    }

    /**
     * Add a document head to company from master list (AJAX)
     */
    public function add()
    {
        header('Content-Type: application/json');
        
        // Permission check
        if (!can('company_doc_heads.add') || !can_edit()) {
            echo json_encode(['success' => false, 'message' => 'Permission denied.']);
            return;
        }
        
        $company_id = $this->input->post('company_id');
        $type_id = $this->input->post('type_id');
        
        // Check company access
        if (!has_company_access($company_id)) {
            echo json_encode(['success' => false, 'message' => 'Company access denied.']);
            return;
        }
        
        $user_id = $this->session->userdata('id');
        
        // Check if already exists
        $existing = $this->db->get_where('company_document_heads', [
            'company_id' => $company_id,
            'type_id' => $type_id
        ])->row();
        
        if ($existing) {
            echo json_encode(['success' => false, 'message' => 'Document head already assigned to this company.']);
            return;
        }
        
        // Get document head info
        $doc_head = $this->db->get_where('sub_type', ['id' => $type_id])->row();
        if (!$doc_head) {
            echo json_encode(['success' => false, 'message' => 'Document head not found.']);
            return;
        }
        
        $this->db->trans_start();
        
        // Add document head (disabled)
        $this->db->insert('company_document_heads', [
            'company_id' => $company_id,
            'type_id' => $type_id,
            'is_enabled' => false,
            'is_reviewed' => false,
            'created_by' => $user_id,
            'created_at' => date('Y-m-d H:i:s')
        ]);
        
        // Add authority (disabled)
        $authority_id = $doc_head->authority_id;
        $this->db->query("
            INSERT INTO company_authorities (company_id, authority_id, is_enabled)
            VALUES (?, ?, FALSE)
            ON CONFLICT (company_id, authority_id) DO NOTHING
        ", [$company_id, $authority_id]);
        
        // Copy mandatory documents (disabled)
        $this->db->query("
            INSERT INTO company_mandatory_documents (company_id, type_id, document_id, is_mandatory, is_enabled, sort_order)
            SELECT ?, md.type_id, md.document_id, 
                CASE WHEN md.mandatory = '1' THEN TRUE ELSE FALSE END,
                FALSE,
                ROW_NUMBER() OVER (ORDER BY md.id)
            FROM mandatory_documents md
            WHERE md.type_id = ?
            ON CONFLICT (company_id, type_id, document_id) DO NOTHING
        ", [$company_id, $type_id]);
        
        // Copy reminders (disabled)
        $this->db->query("
            INSERT INTO company_document_head_reminders (company_id, type_id, reminder_no, days_before, 
                reminder_to_user, reminder_to_admin, reminder_to_super_admin, is_enabled)
            SELECT ?, sr.sub_type_id, sr.reminder_no, sr.days_before,
                CASE WHEN sr.reminder_to_user = 'true' THEN TRUE ELSE FALSE END,
                CASE WHEN sr.reminder_to_admin = 'true' THEN TRUE ELSE FALSE END,
                CASE WHEN sr.reminder_to_super_admin = 'true' THEN TRUE ELSE FALSE END,
                FALSE
            FROM sub_type_reminders sr
            WHERE sr.sub_type_id = ?
            ON CONFLICT (company_id, type_id, reminder_no) DO NOTHING
        ", [$company_id, $type_id]);
        
        $this->db->trans_complete();
        
        if ($this->db->trans_status() === FALSE) {
            echo json_encode(['success' => false, 'message' => 'Database error occurred.']);
            return;
        }
        
        //echo json_encode(['success' => true, 'message' => 'Document head added to company. Please review and activate.']);
        $editUrl = base_url("companydocheads/edit/{$company_id}/{$type_id}");

        echo json_encode([
            'success' => true,
            'redirect' => base_url('companydocheads/edit/' . $company_id . '/' . $type_id)
        ]);
    }

    /**
     * Get available document heads not yet assigned to company (AJAX)
     */
    public function getAvailable()
    {
        header('Content-Type: application/json');
        
        $company_id = $this->input->post('company_id');
        
        // Check company access
        if (!has_company_access($company_id)) {
            echo json_encode(['success' => false, 'message' => 'Company access denied.']);
            return;
        }
        
        // Get document heads not yet assigned to this company
        $sql = "
            SELECT st.id, st.type_name, st.alias_name, a.authority_name
            FROM sub_type st
            LEFT JOIN authority a ON CAST(st.authority_id AS INTEGER) = a.id
            WHERE st.status = '1'
              AND st.id NOT IN (
                  SELECT type_id FROM company_document_heads WHERE company_id = ?
              )
            ORDER BY a.authority_name, st.type_name
        ";
        
        $result = $this->db->query($sql, [$company_id])->result();
        
        echo json_encode(['success' => true, 'data' => $result]);
    }
}

