<?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
     * Updated: Now uses company_id directly in sub_type (no more company_document_heads bridge table)
     */
    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,
                st.document_start_date as custom_start_date,
                st.frequency_start_date as company_due_day,
                st.document_expiry_date as master_due_day,
                st.due_in_same_next_month,
                a.authority_name,
                a.id as authority_id,
                st.id as company_doc_head_id,
                st.is_enabled,
                TRUE as is_reviewed,
                st.created_at as enabled_at,
                CASE 
                    WHEN st.is_enabled = TRUE THEN 'active'
                    ELSE 'disabled'
                END as status
            FROM sub_type st
            LEFT JOIN authority a ON CAST(st.authority_id AS INTEGER) = a.id AND a.company_id = st.company_id
            WHERE st.status = '1'
            AND st.company_id = ?
            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;
        }
        
        // Updated: Get settings directly from sub_type (no more company_document_heads bridge table)
        $company_settings = $this->db->select('id, is_enabled, document_start_date as custom_start_date')
            ->where('id', $type_id)
            ->where('company_id', $company_id)
            ->get('sub_type')
            ->row();
        
        // Get all available documents for this company (for adding new ones)
        $all_documents = $this->db->query("
            SELECT id, document_name 
            FROM documents 
            WHERE company_id = ? AND status = '1' 
            ORDER BY document_name
        ", [$company_id])->result();
        
        // Get currently assigned documents with mandatory flag
        $mandatory_docs = $this->db->query("
            SELECT md.*, d.document_name, md.document_id,
                CASE 
                    WHEN LOWER(CAST(md.mandatory AS TEXT)) 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();
        
        // Build array of selected document IDs with mandatory flag
        $selected_docs = [];
        foreach ($mandatory_docs as $doc) {
            $selected_docs[$doc->document_id] = $doc->is_mandatory ? '1' : '0';
        }
        
        // Get reminders from sub_type_reminders
        $reminders = $this->db->query("
            SELECT sr.*,
                COALESCE(sr.reminder_to_user::text, 'false') as reminder_to_user,
                COALESCE(sr.reminder_to_admin::text, 'false') as reminder_to_admin,
                COALESCE(sr.reminder_to_super_admin::text, '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,
            'all_documents' => $all_documents,
            'selected_docs' => $selected_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);
        
        // Get document head to check frequency
        $doc_head = $this->db->get_where('sub_type', ['id' => $type_id])->row();
        $frequency = strtolower($doc_head->frequency ?? '');
        $is_one_time = ($frequency === 'one time' || $frequency === 'one-time' || $frequency === 'onetime');

        // ------------------------------
        // Mandatory field validations (skip for One Time frequency)
        // ------------------------------
        if (!$is_one_time) {
            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 (if provided)
        $company = $this->db->get_where('company', ['id' => $company_id])->row();
        if (!empty($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');
        
        // Get documents and reminders from POST
        $documents = $this->input->post('document') ?: [];
        $mandatory = $this->input->post('mandatory') ?: [];
        $no_of_reminders = (int) ($this->input->post('no_of_reminders') ?: 0);
        $reminder_days = $this->input->post('reminder_days') ?: [];
        $reminder_to = $this->input->post('reminder_to') ?: [];
        
        // Updated: Update sub_type directly (no more company_document_heads bridge table)
        $data = [
            'document_start_date' => ($custom_start_date !== '' && $custom_start_date !== null) ? $custom_start_date : null,
            'frequency_start_date' => ($due_day !== '' && $due_day !== null) ? (int) $due_day : null,
            'due_in_same_next_month' => ($due_month !== '' && $due_month !== null) ? (int) $due_month : null,
            'document_name' => !empty($documents) ? implode(',', $documents) : null
        ];
        
        $this->db->where('id', $type_id)
            ->where('company_id', $company_id)
            ->update('sub_type', $data);
        
        // ================== UPDATE mandatory_documents ==================
        // Delete existing mandatory documents for this type
        $this->db->delete('mandatory_documents', ['type_id' => $type_id]);
        
        // Insert new mandatory documents
        if (!empty($documents) && is_array($documents)) {
            foreach ($documents as $docId) {
                $this->db->insert('mandatory_documents', [
                    'type_id' => $type_id,
                    'document_id' => $docId,
                    'mandatory' => isset($mandatory[$docId]) ? $mandatory[$docId] : 0,
                    'company_id' => $company_id
                ]);
            }
        }
        
        // ================== UPDATE sub_type_reminders ==================
        // Delete existing reminders
        $this->db->delete('sub_type_reminders', ['sub_type_id' => $type_id]);
        
        // Insert new reminders
        if ($no_of_reminders > 0 && is_array($reminder_days)) {
            $no_of_reminders = min($no_of_reminders, 5);
            
            for ($i = 1; $i <= $no_of_reminders; $i++) {
                if (!isset($reminder_days[$i])) {
                    continue;
                }
                
                $days_before = (int) $reminder_days[$i];
                $toArray = isset($reminder_to[$i]) ? (array) $reminder_to[$i] : [];
                
                $to_user = in_array('User', $toArray);
                $to_admin = in_array('Admin', $toArray);
                $to_super_admin = in_array('Super Admin', $toArray);
                
                $this->db->insert('sub_type_reminders', [
                    'sub_type_id' => $type_id,
                    'reminder_no' => $i,
                    'days_before' => $days_before,
                    'reminder_to_user' => $to_user ? 'true' : 'false',
                    'reminder_to_admin' => $to_admin ? 'true' : 'false',
                    'reminder_to_super_admin' => $to_super_admin ? 'true' : 'false'
                ]);
            }
        }
        
        /*$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');
        $deactivation_date = $this->input->post('deactivation_date');
        $deactivation_remarks = $this->input->post('deactivation_remarks');
        
        // 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, $deactivation_date, $deactivation_remarks);
        
        echo json_encode($result);
    }

    /**
     * DEPRECATED: With company-wise masters, document heads are created directly for a company
     * This method was used to copy document heads from a master list to a company
     */
    public function add()
    {
        header('Content-Type: application/json');
        
        // This method is deprecated in the new company-wise masters model
        // Document heads should be created directly for a company via the type.php controller
        echo json_encode([
            'success' => false, 
            'message' => 'This function is deprecated. Please create document heads directly from the Document Head master page.'
        ]);
    }

    /**
     * DEPRECATED: With company-wise masters, each company creates its own document heads
     * This method was used to find master document heads not yet assigned to a company
     */
    public function getAvailable()
    {
        header('Content-Type: application/json');
        
        // This method is deprecated in the new company-wise masters model
        // Each company creates its own document heads
        echo json_encode(['success' => true, 'data' => []]);
    }
}

