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

class Type extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/userguide3/general/urls.html
	 */
	public function index()
	{
		redirect('type/allType');
	}
	
	/*public function allType($url_company_id = null)
    {   
		$this->session->set_userdata('menu','type');
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		
		// Get company_id from URL parameter first, then fall back to session
		if (!empty($url_company_id)) {
			$company_id = $url_company_id;
			$this->session->set_userdata('company_id', $company_id);
		} else {
			$company_id = $this->session->userdata('company_id');
		}
		
		// Check if company is selected
		if(empty($company_id)) {
			$this->session->set_flashdata('message_type', 'info');
			$this->session->set_flashdata('message_name', 'Please select a company first.');
			redirect('company/companies');
			return;
		}
		
		// Get company's fiscal year
		$company = $this->db->select('fiscal_year')->where('id', $company_id)->get('company')->row();
		$fiscal_year = $company ? $company->fiscal_year : 'jan-dec';
		
		// Show ONLY ENABLED document heads for the company (INNER JOIN)
		$sql = "SELECT 
				s.*, 
				a.authority_name, 
				string_agg(d.document_name, ', ' ORDER BY array_position(string_to_array(s.document_name, ','), d.id::text)) AS document_names,
				u.first_name,
				u.last_name,
				u.email_id,
				cdh.is_enabled,
				cdh.custom_start_date,
				COALESCE(ud_count.upload_count, 0) as has_uploads
			FROM sub_type s
			INNER JOIN company_document_heads cdh 
				ON cdh.type_id = s.id 
				AND cdh.company_id = ?
				AND cdh.is_enabled = true
			LEFT JOIN authority a 
				ON a.id = CAST(NULLIF(s.authority_id, '') AS INTEGER)
			LEFT JOIN documents d 
				ON CAST(d.id AS TEXT) = ANY(string_to_array(s.document_name, ','))
			LEFT JOIN users u 
				ON CAST(u.id AS TEXT) = s.created_by
			LEFT JOIN (
				SELECT type_id, COUNT(*) as upload_count 
				FROM uploaded_documents 
				WHERE is_deleted = 0 
				GROUP BY type_id
			) ud_count ON ud_count.type_id = s.id
			WHERE s.status = '1'
			GROUP BY s.id, a.authority_name, u.first_name, u.last_name, u.email_id, cdh.is_enabled, cdh.custom_start_date, ud_count.upload_count
			ORDER BY s.type_name ASC";

		$query = $this->db->query($sql, array($company_id));
		$business_data = $query->result_array();
		$frequency = PAYMENT_OPTIONS;
		
		$this->load->view('templates/header');
		$this->load->view('type/all_type', array('authority_list' => $business_data, 'fiscal_year' => $fiscal_year));
		$this->load->view('templates/footer');

	}*/


	public function allType($company_id = null)
    {
        $this->session->set_userdata('menu', 'company_doc_heads');
        
        // Check login
        $login_id = $this->session->userdata('id');
        if (empty($login_id)) {
            redirect('login');
        }
        
        // All logged-in users can view document heads (edit/delete restricted in view based on permissions)
        
        // 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
     * For User role (3), only returns assigned document heads
     */
    private function _getCompanyDocumentHeads($company_id)
    {
        $role_id = $this->session->userdata('role_id');
        $user_id = $this->session->userdata('id');
        
        // Base query
        $sql = "SELECT 
				st.id AS type_id,
				st.type_name,
				st.alias_name,
				st.frequency,

				st.document_start_date AS master_start_date,
				st.frequency_start_date AS master_due_day,

				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.custom_frequency_start_date AS company_due_day,
				cdh.custom_due_in_same_next_month AS company_due_month,

				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,
				
				-- Count of uploaded documents for this type and company
				COALESCE(ud_count.upload_count, 0) AS has_uploads
			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 = ?
			LEFT JOIN (
				SELECT type_id, company_id, COUNT(*) AS upload_count
				FROM uploaded_documents
				WHERE is_deleted = 0 AND company_id = ?
				GROUP BY type_id, company_id
			) ud_count ON ud_count.type_id = st.id AND ud_count.company_id = ?
			WHERE st.status = '1'";
        
        $params = [$company_id, $company_id, $company_id];
        
        // For User role, filter by assigned document heads
        if ($role_id == '3') {
            $allowed_doc_heads = get_allowed_document_types();
            if (!empty($allowed_doc_heads)) {
                $placeholders = implode(',', array_fill(0, count($allowed_doc_heads), '?'));
                $sql .= " AND st.id IN ({$placeholders})";
                $params = array_merge($params, $allowed_doc_heads);
            } else {
                // No assigned doc heads - return empty
                return [];
            }
        }
        
        $sql .= " ORDER BY a.authority_name, st.type_name";
        
        return $this->db->query($sql, $params)->result();
    }

	public function addType() {
		$this->session->set_userdata('menu','type');
		$login_id = $this->session->userdata('id');
		$company_id = $this->session->userdata('company_id');

		if($login_id=='') {
			redirect('login');
		}
		
		// Permission check - edit permission required for adding
		require_edit_permission('type/allType/' . $company_id);
		
		// Filter authorities by company-enabled (if company selected) or show all for Super Admin
		if (!empty($company_id)) {
			$sql = "SELECT a.* FROM authority a
				INNER JOIN company_authorities ca ON ca.authority_id = a.id 
					AND ca.company_id = ? AND ca.is_enabled = true
				WHERE a.status='1' 
				ORDER BY a.authority_name ASC";
			$query = $this->db->query($sql, array($company_id));
		} else {
			$sql = "SELECT * FROM authority WHERE status='1' ORDER BY authority_name ASC";
			$query = $this->db->query($sql);
		}
		$business_data = $query->result_array();
		
		$document_sql = "select * from documents where status='1'";
		$document_query = $this->db->query($document_sql);
		$document_data = $document_query->result_array();

		$company_sql = "select * from company where status='1' and id=$company_id"; 
		$company_query = $this->db->query($company_sql);
		$company_data = $company_query->result_array();
		
		$frequency = PAYMENT_OPTIONS;
		$this->load->view('templates/header');
		$this->load->view('type/add_type',array('authority'=>$business_data,'frequency'=>$frequency,'document_data'=>$document_data, 'company_data'=>$company_data));
		//$this->load->view('templates/footer');
	}
	
	public function saveType() {
		
		$this->session->set_userdata('menu','type');
		$login_id = $this->session->userdata('id');
		$company_id = $this->session->userdata('company_id');
		
		if($login_id=='') {
			redirect('login');
		}
		
		// Permission check - edit permission required for saving
		require_edit_permission('type/allType/' . $company_id);

		//echo $this->session->userdata('full_name');

		//echo '<pre>'; print_r($_POST);exit;
		$post = $this->input->post();
		$sub_type = trim($post['sub_type']);
		$alias_name = $post['alias'];
		$authority_id = $post['authority_id'];
		$frequency = $post['frequency'];
		$doc_type = $post['doc_type'];
		$document_date = $post['document_date'] ?? null;
		$doc_start_date = $post['document_start_date'];
		$due_month = $post['due_month'];
		$next_due_date = $post['next_due_date'] ?? null;

		// Check for duplicate document head name (ignoring special characters)
		if (check_duplicate_name('sub_type', 'type_name', $sub_type, null, ['status' => '1'])) {
			$this->session->set_flashdata('message_type', 'error');
			$this->session->set_flashdata('message_name', 'Document Head name already exists! (A similar name with different special characters may exist)');
			redirect('type/addType');
			return;
		}
		
		// Check for duplicate alias name
		$alias_name_check = isset($post['alias']) ? trim($post['alias']) : '';
		if (!empty($alias_name_check) && check_duplicate_name('sub_type', 'alias_name', $alias_name_check, null, ['status' => '1'])) {
			$this->session->set_flashdata('message_type', 'error');
			$this->session->set_flashdata('message_name', 'Alias name already exists! (A similar alias with different special characters may exist)');
			redirect('type/addType');
			return;
		}

		if($due_month == 'same')
			$due_month = 0;
		else 
			$due_month = 1;
		//$frequency_start_date = $post['frequency_start_date'] ?? null;
		//$monthly_days = $post['monthly_days'] ?? null;
		if($frequency=='Monthly') {
            $frequency_start_date = $_POST['monthly_days'];
        }
        else {
			$frequency_start_date = $_POST['monthly_days'];
            //$frequency_start_date = $_POST['frequency_start_date'];
        }
		$created_by = $this->session->userdata('full_name') ?? null;

		$documents = $post['document'] ?? []; // selected documents
		$mandatory = $post['mandatory'] ?? []; // mandatory mapping

		// Insert into type table
		$typeData = [
			'type_name' => $sub_type,
			'alias_name' => $alias_name,
			'authority_id' => $authority_id,
			'frequency' => $frequency,
			'doc_type' => $doc_type,
			'frequency_start_date' => $frequency_start_date,
			'document_name'=>implode(',',$documents),
			'document_start_date' => $doc_start_date,
			'created_by'=> $login_id,
			'due_in_same_next_month' => $due_month,
			'status'                => 1
		];
		
		//echo $document_date;exit;
		/*if (!empty($document_date)) {
			$typeData['document_expiry_date'] = $document_date;
		}*/

		if (!empty($next_due_date)) {
			$typeData['document_expiry_date'] = $next_due_date;
		}

		$this->db->insert('sub_type', $typeData);
		$type_id = $this->db->insert_id();

		// Insert into type_documents table
		foreach ($documents as $docId) {
			$this->db->insert('mandatory_documents', [
				'type_id' => $type_id,
				'document_id' => $docId,
				'mandatory' => isset($mandatory[$docId]) ? $mandatory[$docId] : 0
			]);
		}

			// ================== INSERT INTO sub_type_reminders ==================
		// We read: no_of_reminders, reminder_days[], reminder_to[][]
		$no_of_reminders = (int) ($post['no_of_reminders'] ?? 0);
		$reminder_days   = $post['reminder_days'] ?? [];   // e.g. [1 => "30", 2 => "15", ...]
		$reminder_to     = $post['reminder_to']   ?? [];   // e.g. [1 => ['User','Admin'], 2 => ['User'], ...]

		if ($no_of_reminders > 0 && is_array($reminder_days)) {

			// respect DB constraint (1..5)
			$no_of_reminders = min($no_of_reminders, 5);

			for ($i = 1; $i <= $no_of_reminders; $i++) {

				if (!isset($reminder_days[$i])) {
					continue; // no row data
				}

				$days_before = (int) $reminder_days[$i];

				// who to remind?
				$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);

				$reminderRow = [
					'sub_type_id'             => $type_id,  // FK to sub_type(id)
					'reminder_no'             => $i,        // 1..5
					'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',
				];

				/*echo '<pre>';
				print_r($reminderRow);
				exit; */

				$this->db->insert('sub_type_reminders', $reminderRow);
			} 
		}

		// ================== AUTO-COPY TO COMPANY-SPECIFIC TABLES ==================
		// Copy to company_document_heads for ALL companies
		// Enabled only for the creating company, disabled for others
		$current_company_id = $company_id;
		$companies = $this->db->select('id')->where('status', '1')->get('company')->result();
		
		foreach ($companies as $comp) {
			$is_enabled = ($comp->id == $current_company_id) ? true : false;
			
			// 1. Insert into company_document_heads
			$this->db->insert('company_document_heads', [
				'company_id' => $comp->id,
				'type_id' => $type_id,
				'custom_start_date' => $doc_start_date,
				'is_enabled' => $is_enabled,
				'created_at' => date('Y-m-d H:i:s')
			]);
			
			// 2. Copy mandatory documents to company_mandatory_documents
			foreach ($documents as $docId) {
				$this->db->insert('company_mandatory_documents', [
					'company_id' => $comp->id,
					'type_id' => $type_id,
					'document_id' => $docId,
					'is_mandatory' => isset($mandatory[$docId]) ? ($mandatory[$docId] == 1 ? true : false) : false,
					'is_enabled' => $is_enabled,
					'sort_order' => 0
				]);
			}
			
			// 3. Copy reminders to company_document_head_reminders
			if ($no_of_reminders > 0) {
				for ($i = 1; $i <= $no_of_reminders; $i++) {
					if (!isset($reminder_days[$i])) continue;
					
					$toArray = isset($reminder_to[$i]) ? (array) $reminder_to[$i] : [];
					$this->db->insert('company_document_head_reminders', [
						'company_id' => $comp->id,
						'type_id' => $type_id,
						'reminder_no' => $i,
						'days_before' => (int) $reminder_days[$i],
						'reminder_to_user' => in_array('User', $toArray),
						'reminder_to_admin' => in_array('Admin', $toArray),
						'reminder_to_super_admin' => in_array('Super Admin', $toArray),
						'is_enabled' => $is_enabled
					]);
				}
			}
		}

		$this->session->set_flashdata('message_name', 'Sub Type Created Successfully');
		$this->session->set_flashdata('message_type', 'success');
		redirect('type/allType/' . $current_company_id);	
	}
	public function deleteType($id)
	{
		$this->session->set_userdata('menu','type');
		$login_id = $this->session->userdata('id');
		$company_id = $this->session->userdata('company_id');
		
		if($login_id=='') {
			redirect('login');
		}
		
		// Permission check - delete permission required
		require_delete_permission('type/allType/' . $company_id);

		//Check is authoiry is mapped with any type and user
        if ($this->id_exists('uploaded_documents', $id)) {
            $this->session->set_flashdata('message_type', 'error');
            $this->session->set_flashdata('message_name', 'Delete not allowed — Document head in use.');
            redirect('type/allType/' . $this->session->userdata('company_id'));
            return;
        }
		
		$query = $this->db->get_where('sub_type', ['id' => $id]);

		if ($query->num_rows() === 0) {
			redirect('type');
		} else {
			//echo "in else";exit;
			$this->db->where('id', $id)->update('sub_type', ['status' => 0]);
			$this->session->set_flashdata('message_name', 'Type Deleted Successfully');
			$this->session->set_flashdata('message_type', 'success'); // optional: success, error, info, warning
			redirect('type/allType/' . $this->session->userdata('company_id'));
		}
	}
	
	
	public function editType($id, $url_company_id = null) {
		
		$login_id = $this->session->userdata('id');
		
		// Get company_id from URL parameter first, then fall back to session
		if (!empty($url_company_id)) {
			$company_id = $url_company_id;
			$this->session->set_userdata('company_id', $company_id);
		} else {
			$company_id = $this->session->userdata('company_id');
		}
		
		if ($login_id == '') {
			redirect('login');
		}
		
		// Permission check - edit permission required
		require_edit_permission('type/allType/' . $company_id);
		
		// If no company selected, redirect to company list to select one
		if (empty($company_id)) {
			$this->session->set_flashdata('message_type', 'info');
			$this->session->set_flashdata('message_name', 'Please select a company first.');
			redirect('company/companies');
			return;
		}
		
		$this->session->set_userdata('menu', 'type');

        if ($this->id_exists('uploaded_documents', $id)) {
            $this->session->set_flashdata('message_type', 'error');
            $this->session->set_flashdata('message_name', 'Edit not allowed — Document head in use.');
            redirect('type/allType/' . $company_id);
            return;
        }

		// Get type data
		$sql = "SELECT * FROM sub_type WHERE id = ?";
		$type_query = $this->db->query($sql, array($id));
		$type_data = $type_query->row_array(); // single row is enough

		if (empty($type_data)) {
			redirect('type/allType/' . $company_id);
		}

		// Get current authority_id from type_data
		$current_authority_id = !empty($type_data['authority_id']) ? $type_data['authority_id'] : null;

		// Filter authorities by company-enabled (if company selected) or show all for Super Admin
		// Also include the currently assigned authority even if not enabled
		if (!empty($company_id)) {
			$sql1 = "SELECT a.* FROM authority a
				LEFT JOIN company_authorities ca ON ca.authority_id = a.id 
					AND ca.company_id = ?
				WHERE a.status='1' 
					AND (ca.is_enabled = true OR a.id = ?)
				ORDER BY a.authority_name ASC";
			$query1 = $this->db->query($sql1, array($company_id, $current_authority_id));
		} else {
			$sql1 = "SELECT * FROM authority WHERE status='1' ORDER BY authority_name ASC";
			$query1 = $this->db->query($sql1);
		}
		$authority_data = $query1->result_array();

		// Get all documents
		$document_sql = "SELECT * FROM documents WHERE status='1'";
		$document_query = $this->db->query($document_sql);
		$document_data = $document_query->result_array();

		// ✅ Get already assigned documents (with mandatory flag)
		$assigned_sql = "SELECT document_id, mandatory FROM mandatory_documents WHERE type_id = ?";
		$assigned_query = $this->db->query($assigned_sql, array($id));
		$assigned_documents = $assigned_query->result_array();
		
		// Convert assigned docs into [doc_id => mandatory]
		$selected_docs = [];
		foreach ($assigned_documents as $doc) {
			$selected_docs[$doc['document_id']] = $doc['mandatory'];
		}
		$frequency = PAYMENT_OPTIONS;

		$company_sql = "select * from company where status='1' and id=?"; 
		$company_query = $this->db->query($company_sql, array($company_id));
		$company_data = $company_query->result_array();

		// Get existing reminders for this type
		$reminder_sql = "SELECT * FROM sub_type_reminders WHERE sub_type_id = ? ORDER BY reminder_no";
		$reminder_query = $this->db->query($reminder_sql, array($id));
		$reminders = $reminder_query->result_array();

		$this->load->view('templates/header');
		$this->load->view(
			'type/edit_type',
			array(
				'authority_data'   => $authority_data,
				'type_data'        => $type_data,
				'frequency'        => $frequency,
				'document_data'    => $document_data,
				'selected_docs'    => $selected_docs,
				'company_data'     => $company_data,
				'reminders'        => $reminders
			)
		);
	}

	/**
	 * View document head (read-only) - for document heads that have uploads
	 */
	public function viewType($id, $url_company_id = null) {
		$login_id = $this->session->userdata('id');
		
		// Get company_id from URL parameter first, then fall back to session
		if (!empty($url_company_id)) {
			$company_id = $url_company_id;
			$this->session->set_userdata('company_id', $company_id);
		} else {
			$company_id = $this->session->userdata('company_id');
		}
		
		if ($login_id == '') {
			redirect('login');
		}
		
		// If no company selected, redirect to company list to select one
		if (empty($company_id)) {
			$this->session->set_flashdata('message_type', 'info');
			$this->session->set_flashdata('message_name', 'Please select a company first.');
			redirect('company/companies');
			return;
		}
		
		$this->session->set_userdata('menu', 'type');

		// Get type data
		$sql = "SELECT s.*, a.authority_name 
				FROM sub_type s
				LEFT JOIN authority a ON a.id = CAST(NULLIF(s.authority_id, '') AS INTEGER)
				WHERE s.id = ?";
		$type_query = $this->db->query($sql, array($id));
		$type_data = $type_query->row_array();

		if (empty($type_data)) {
			redirect('type/allType/' . $company_id);
		}

		// Get assigned documents
		$assigned_sql = "SELECT md.document_id, md.mandatory, d.document_name 
						 FROM mandatory_documents md
						 JOIN documents d ON d.id = md.document_id
						 WHERE md.type_id = ?";
		$assigned_query = $this->db->query($assigned_sql, array($id));
		$assigned_documents = $assigned_query->result_array();

		// Get reminders
		$reminder_sql = "SELECT * FROM sub_type_reminders WHERE sub_type_id = ? ORDER BY reminder_no";
		$reminder_query = $this->db->query($reminder_sql, array($id));
		$reminders = $reminder_query->result_array();

		// Get upload count
		$upload_count = $this->db->where('type_id', $id)->where('is_deleted', 0)->count_all_results('uploaded_documents');

		$this->load->view('templates/header');
		$this->load->view('type/view_type', array(
			'type_data' => $type_data,
			'assigned_documents' => $assigned_documents,
			'reminders' => $reminders,
			'upload_count' => $upload_count
		));
		$this->load->view('templates/footer');
	}
		
	public function updateType() {
		$login_id = $this->session->userdata('id');
		$company_id = $this->session->userdata('company_id');
		if($login_id=='') {
			redirect('login');
		}
		
		// Permission check - edit permission required
		require_edit_permission('type/allType/' . $company_id);
		
		$this->session->set_userdata('menu','type');
		$id = $_POST['type_id'];
		//echo '<pre>'; print_r($_POST);exit;
		$sub_type = trim($_POST['sub_type']);
		$alias_name = $_POST['alias'];
		$monthly_days = $_POST['monthly_days'];
		$authority_id = $_POST['authority_id'];
		$frequency = $_POST['frequency'];
		$doc_type = $_POST['doc_type'];
		$due_month = $_POST['due_month'];

		// Check for duplicate document head name (excluding current ID)
		if (check_duplicate_name('sub_type', 'type_name', $sub_type, $id, ['status' => '1'])) {
			$this->session->set_flashdata('message_type', 'error');
			$this->session->set_flashdata('message_name', 'Document Head name already exists! (A similar name with different special characters may exist)');
			redirect('type/editType/' . $id);
			return;
		}
		
		// Check for duplicate alias name (excluding current ID)
		$alias_name_check = isset($_POST['alias']) ? trim($_POST['alias']) : '';
		if (!empty($alias_name_check) && check_duplicate_name('sub_type', 'alias_name', $alias_name_check, $id, ['status' => '1'])) {
			$this->session->set_flashdata('message_type', 'error');
			$this->session->set_flashdata('message_name', 'Alias name already exists! (A similar alias with different special characters may exist)');
			redirect('type/editType/' . $id);
			return;
		}

		if($due_month == 'same'){
			$due_month = 0;
		} else {
			$due_month = 1;
		}	

		if($frequency=='Monthly') {
			$frequency_start_date = $_POST['monthly_days'];
		}
		else {
			$frequency_start_date = $_POST['frequency_start_date'];
		}
		$document_expiry_date = $_POST['document_expiry_date'];
		$document_date = $_POST['document_date'];
		$document =  implode(',',$_POST['document']);
		//$created_by = $this->session->userdata('full_name') ?? null;
		//$document =  implode(',', $_POST['document']);
		
		//$sql = "update sub_type set type_name='$sub_type',authority_id='$authority_id', frequency = '$frequency',doc_type='$doc_type',frequency_start_date='$frequency_start_date', document_expiry_date='$document_expiry_date',document_name='$document',alias_name='$alias_name'  where id='$id'";
		//$query1 = $this->db->query($sql);
		$this->db->where('id', $id);
		$this->db->update('sub_type', array_merge([
    'type_name'            => $sub_type,
    'authority_id'         => $authority_id,
    'frequency'            => $frequency,
    'status'               => 1,
    'doc_type'             => $doc_type,
    'frequency_start_date' => $frequency_start_date,
    'document_name'        => $document,
    'alias_name'           => $alias_name,
    'created_by'           => $login_id,
	'due_in_same_next_month' => $due_month
], !empty($document_date) ? ['document_expiry_date' => $document_date] : []));

		$delete_query  = "delete from mandatory_documents where type_id = '$id'";
		$delete_data = $this->db->query($delete_query);
		
		$documents = $_POST['document'] ?? []; // selected documents
		$mandatory = $_POST['mandatory'] ?? []; // mandatory mapping

		// Insert into type_documents table
		foreach ($documents as $docId) {
			$this->db->insert('mandatory_documents', [
				'type_id' => $id,
				'document_id' => $docId,
				'mandatory' => isset($mandatory[$docId]) ? $mandatory[$docId] : 0
			]);
		}

		// ================== UPDATE sub_type_reminders ==================
		// First delete existing reminders
		$this->db->delete('sub_type_reminders', ['sub_type_id' => $id]);

		// Then insert new reminders
		$no_of_reminders = (int) ($_POST['no_of_reminders'] ?? 0);
		$reminder_days   = $_POST['reminder_days'] ?? [];
		$reminder_to     = $_POST['reminder_to'] ?? [];

		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'             => $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_name', 'Type Details Successfully Updated');

		// Preserve company_id on redirect
		$company_id = $_POST['company_id'] ?? $this->session->userdata('company_id');
		if (!empty($company_id)) {
			$this->session->set_userdata('company_id', $company_id);
			redirect('type/allType/' . $company_id);
		} else {
			redirect('type/allType');
		}
	}
	
	public function viewProject($id) {
		$login_id = $this->session->userdata('id');
		if($login_id=='') {
			redirect('login');
		}
		
		$sql="select * from projects where id= '$id'";   
		$project_query = $this->db->query($sql);
		$project_data = $project_query->result_array();
		$this->load->view('templates/layout');
		$this->load->view('project/view_project',array('project_data'=>$project_data));
	}
	
	public function changeStatus()
	{
		// Permission check - edit permission required for status change
		if (!can_edit()) {
			echo json_encode([
				'success' => false,
				'message' => 'You do not have permission to change status.'
			]);
			return;
		}
		
		$id     = $this->input->post('id');
		$status = $this->input->post('status');

		if ($this->id_exists('uploaded_documents', $id)) {
            echo json_encode([
				'success' => false,
				'message' => 'Deactivation not allowed — Document head in use.'
			]);
			return;
        }

		// Convert 'Active' to 0 and anything else to 1
		if($status=='1') {
			$new_status ='0';
		} else {
			$new_status = '1';	
		}
		$sql = "UPDATE sub_type SET status='$new_status' WHERE id='$id'";
		$query = $this->db->query($sql);

		if ($query) {
			echo json_encode([
				'success'    => true,
				'message'    => 'Status updated successfully.'
			]);
		} else {
			echo json_encode([
				'success' => false,
				'message' => 'Failed to update status.'
			]);
		}
	}
	 // 🔹 Private helper function to check if a record exists
    private function id_exists($table, $id)
    {
        return $this->db->where('type_id', $id)
                ->where('is_deleted', 0)
                ->limit(1)
                ->count_all_results($table) > 0;
    }

	public function reorder_all($company_id = null)
	{
		// Check login
		$login_id = $this->session->userdata('id');
		if (empty($login_id)) {
			redirect('login');
		}
		
		$role_id = $this->session->userdata('role_id');
		
		if (!empty($company_id)) {
			$this->session->set_userdata('company_id', (int)$company_id);
		}

		$company_id = (int) $this->session->userdata('company_id');
		if (empty($company_id)) {
			show_error('Company not selected', 400);
		}

		$this->db->select('st.*')
				 ->from('sub_type st')
				 ->join(
					'company_document_heads cst',
					'cst.type_id = st.id AND cst.company_id = ' . (int)$company_id,
					'inner'
				 )
				 ->where('st.status', '1')
				 ->where('cst.is_enabled', true);
		
		// For User role, only show assigned document heads
		if ($role_id == '3') {
			$allowed_doc_heads = get_allowed_document_types();
			if (!empty($allowed_doc_heads)) {
				$this->db->where_in('st.id', $allowed_doc_heads);
			} else {
				// No assigned doc heads - return empty
				$sub_types = [];
			}
		}
		
		if (!isset($sub_types)) {
			$sub_types = $this->db->get()->result_array();
		}
			
		foreach ($sub_types as &$row) {

			// Convert CSV IDs -> array
			$doc_ids = array_filter(array_map('trim', explode(',', $row['document_name'])));

			$documents = [];
			if (!empty($doc_ids)) {

				// Fetch documents IN THE SAME ORDER as stored sequence
				$doc_list = $this->db
					->where_in('id', $doc_ids)
					->where('status', '1')
					->get('documents')
					->result_array();

				// Index by ID for quick lookup
				$docIndexed = [];
				foreach ($doc_list as $d) {
					$docIndexed[$d['id']] = $d['document_name'];
				}

				// Keep ordering same as sub_type.document_name
				foreach ($doc_ids as $doc_id) {
					if (isset($docIndexed[$doc_id])) {
						$documents[] = [
							'id' => $doc_id,
							'name' => $docIndexed[$doc_id]
						];
					}
				}
			}

			
			// Attach final structured list
			$row['documents'] = $documents;
		}

		$data['sub_types'] = $sub_types;
		$data['is_view_only'] = !can_edit();

		$this->load->view('templates/header');
		$this->load->view('type/reorder_all_view', $data);
		//$this->load->view('templates/footer');
	}

	public function save_order()
	{
		// Permission check - edit permission required for reordering
		if (!can_edit()) {
			echo json_encode(['status' => 'error', 'message' => 'You do not have permission to reorder.']);
			return;
		}
		
		$type_id = $this->input->post('type_id');
		$sequence = $this->input->post('sequence');

		$docs = implode(',', $sequence);

		$this->db->where('id', $type_id)
				->update('sub_type', ['document_name' => $docs]);

		echo json_encode(['status' => 'success']);
	}

	public function getFiscalYear()
	{
		$this->db->select('fiscal_year');
		$this->db->from('company');
		$this->db->where('id',2);
		$this->db->limit(1);
		$query = $this->db->get();

		$result = $query->row();

		echo json_encode([
			'fiscal_year' => $result ? $result->fiscal_year : ''
		]);
	}

	/**
	 * Get child documents for a parent document from document_groups
	 * Used for auto-selecting children when creating/editing Document Head
	 */
	public function getChildDocuments()
	{
		$document_id = $this->input->post('document_id');
		
		if (empty($document_id)) {
			echo json_encode(['children' => []]);
			return;
		}
		
		// Get the group where this document is the parent
		$group = $this->db->where('document_id', $document_id)
						  ->get('document_groups')
						  ->row_array();
		
		if (empty($group) || empty($group['grouped_doc_id'])) {
			echo json_encode(['children' => [], 'is_parent' => false]);
			return;
		}
		
		// Parse child document IDs
		$child_ids = array_map('trim', explode(',', $group['grouped_doc_id']));
		$child_ids = array_filter($child_ids);
		
		if (empty($child_ids)) {
			echo json_encode(['children' => [], 'is_parent' => false]);
			return;
		}
		
		// Get child document details
		$children = $this->db->where_in('id', $child_ids)
							 ->where('status', '1')
							 ->get('documents')
							 ->result_array();
		
		echo json_encode([
			'is_parent' => true,
			'children' => $children
		]);
	}

	/**
	 * Get all document groups for reference
	 * Returns a map of parent_id => [child_ids]
	 */
	public function getAllDocumentGroups()
	{
		$groups = $this->db->get('document_groups')->result_array();
		
		$groupMap = [];
		foreach ($groups as $g) {
			$parent_id = $g['document_id'];
			$child_ids = array_map('trim', explode(',', $g['grouped_doc_id']));
			$child_ids = array_filter($child_ids);
			$groupMap[$parent_id] = $child_ids;
		}
		
		echo json_encode(['groups' => $groupMap]);
	}

	/**
	 * Check if a document is a child in any group
	 * Returns the parent document if it is a child
	 */
	public function checkDocumentParent()
	{
		$document_id = $this->input->post('document_id');
		
		if (empty($document_id)) {
			echo json_encode(['is_child' => false]);
			return;
		}
		
		// Check all groups to see if this document is a child
		$groups = $this->db->get('document_groups')->result_array();
		
		foreach ($groups as $g) {
			$child_ids = array_map('trim', explode(',', $g['grouped_doc_id']));
			if (in_array($document_id, $child_ids)) {
				// This document is a child - get parent details
				$parent = $this->db->where('id', $g['document_id'])
								   ->get('documents')
								   ->row_array();
				
				echo json_encode([
					'is_child' => true,
					'parent_id' => $g['document_id'],
					'parent_name' => $parent ? $parent['document_name'] : ''
				]);
				return;
			}
		}
		
		echo json_encode(['is_child' => false]);
	}
}
