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

class Document 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('document/allDocuments');
	}
	
	public function allDocuments($company_id = null)
    {   
		$this->session->set_userdata('menu','document');
		$login_id = $this->session->userdata('id');
		if($login_id=='') {
			redirect('login');
		}
		
		$role_id = $this->session->userdata('role_id');
		
		// For User role, only show documents from their assigned document heads
		if ($role_id == '3') {
			$allowed_doc_heads = get_allowed_document_types();
			if (!empty($allowed_doc_heads)) {
				// Get document IDs from assigned document heads via mandatory_documents
				$placeholders = implode(',', array_fill(0, count($allowed_doc_heads), '?'));
				$sql = "SELECT DISTINCT d.* FROM documents d
						INNER JOIN mandatory_documents md ON md.document_id = d.id
						WHERE md.type_id IN ({$placeholders})
						ORDER BY d.id ASC";
				$query = $this->db->query($sql, $allowed_doc_heads);
				$business_data = $query->result_array();
			} else {
				$business_data = [];
			}
		} else {
			// Super Admin and Admin see all documents
			$sql="select * from documents order by id asc ";  
			$query = $this->db->query($sql);
			$business_data = $query->result_array();
		}
		
		// Get company_id from URL parameter first, then fall back to session
		if (!empty($company_id)) {
			// Check if user has access to this company
			require_company_access($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');
			// Validate session company_id if set
			if (!empty($company_id) && !has_company_access($company_id)) {
				$company_id = null;
				$this->session->unset_userdata('company_id');
			}
		}
		
		$company_document_status = [];
		$document_in_enabled_head = [];
		$document_has_uploads = [];
		$company_name = '';
		
		if (!empty($company_id)) {
			// Get all company_documents for selected company
			$cd_query = $this->db->query(
				"SELECT document_id, is_enabled FROM company_documents WHERE company_id = ?", 
				array($company_id)
			);
			foreach ($cd_query->result() as $row) {
				$company_document_status[$row->document_id] = $row->is_enabled;
			}
			
			// Check which documents are part of enabled document heads
			$enabled_docs_query = $this->db->query("
				SELECT DISTINCT md.document_id
				FROM mandatory_documents md
				INNER JOIN company_document_heads cdh ON cdh.type_id = md.type_id
				WHERE cdh.company_id = ? AND cdh.is_enabled = true
			", array($company_id));
			foreach ($enabled_docs_query->result() as $row) {
				$document_in_enabled_head[$row->document_id] = true;
			}
			
			// Check which documents have uploads for this company
			$uploads_query = $this->db->query("
				SELECT DISTINCT document_id, COUNT(*) as upload_count
				FROM uploaded_documents
				WHERE company_id = ? AND is_deleted = 0
				GROUP BY document_id
			", array($company_id));
			foreach ($uploads_query->result() as $row) {
				$document_has_uploads[$row->document_id] = $row->upload_count;
			}
			
			// Get company name for display
			$company = $this->db->get_where('company', ['id' => $company_id])->row();
			$company_name = $company ? $company->company_name : '';
		}
		
		$this->load->view('templates/header');
		$this->load->view('document/all_document', array(
			'authority_list' => $business_data,
			'company_id' => $company_id,
			'company_name' => $company_name,
			'company_document_status' => $company_document_status,
			'document_in_enabled_head' => $document_in_enabled_head,
			'document_has_uploads' => $document_has_uploads
		));
		//$this->load->view('templates/footer');

	}
	public function addDocument() {
		$this->session->set_userdata('menu','document');
		$login_id = $this->session->userdata('id');
		if($login_id=='') {
			redirect('login');
		}
		
		// Permission check - edit permission required for adding
		require_edit_permission('document/allDocuments');
		
		$this->load->view('templates/header');
		$this->load->view('document/add_document');
		//$this->load->view('templates/footer');
	}
	
	public function saveDocument() {
		
		$this->session->set_userdata('menu','document');
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		
		// Permission check - edit permission required for saving
		require_edit_permission('document/allDocuments');
		
		$document_name = trim($_POST['document_name']);
		
		// Check for duplicate document name (ignoring special characters)
		if (check_duplicate_name('documents', 'document_name', $document_name, null, ['status' => '1'])) {
			$this->session->set_flashdata('message_type', 'error');
			$this->session->set_flashdata('message_name', 'Document name already exists! (A similar name with different special characters may exist)');
			redirect('document/addDocument');
			return;
		}
		
		$query = "insert into documents(document_name,status) values('".$this->db->escape_str($document_name)."','1')";
		
		$insert_query = $this->db->query($query);
		
		// Get the inserted document ID
		$document_id = $this->db->insert_id();
		$current_company_id = $this->session->userdata('company_id');

		// Auto-copy to company_documents 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_documents', [
				'company_id' => $company->id,
				'document_id' => $document_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', 'New Document Created Successfully');
		
		redirect('document/allDocuments');	
	}
	public function deleteDocument($id)
	{
		$this->session->set_userdata('menu','document');
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		
		// Permission check - delete permission required
		require_delete_permission('document/allDocuments');

		if ($this->id_exists('uploaded_documents', $id)) {
            $this->session->set_flashdata('message_type', 'error');
            $this->session->set_flashdata('message_name', 'Delete is not allowed — Document in use.');
            redirect('document/allDocuments');
            return;
        }
		
		$query = $this->db->get_where('documents', ['id' => $id]);

		if ($query->num_rows() === 0) {
			redirect('document/allDocuments');
		} else {
			$delete_query  = "delete from documents where id= '$id'";
			$delete_data = $this->db->query($delete_query);
			
			$this->session->set_flashdata('message_name', 'Document Deleted Successfully');
			redirect('document/allDocuments');
		}
	}
	
	public function editDocument($id) {
		
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		
		// All logged-in users can view - edit actions are protected in the view
		$this->session->set_userdata('menu','document');

		// Check if document has uploads - if yes, show view-only mode
		$company_id = $this->session->userdata('company_id');
		$has_uploads = 0;
		if (!empty($company_id)) {
			$has_uploads = $this->db->where('document_id', $id)
				->where('company_id', $company_id)
				->where('is_deleted', 0)
				->count_all_results('uploaded_documents');
		}
		
		$sql = "select * from documents where id='$id'";

		$type_query = $this->db->query($sql);
		$type_data = $type_query->result_array();

		if(empty($type_data)) {
			redirect('document/allDocuments');
		}
		
		// View-only if user doesn't have edit permission OR document has uploads
		$is_view_only = !can_edit() || ($has_uploads > 0);
		
		$this->load->view('templates/header');
		$this->load->view('document/edit_document', array(
			'authority_data' => $type_data,
			'has_uploads' => $has_uploads,
			'is_view_only' => $is_view_only
		));		
		
	}
	public function updateDocument() {
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		
		// Permission check - edit permission required
		require_edit_permission('document/allDocuments');
		
		$this->session->set_userdata('menu','document');
		$id = $_POST['id'];
		
		$document_name = trim($_POST['document_name']);
		
		// Check for duplicate document name (excluding current ID)
		if (check_duplicate_name('documents', 'document_name', $document_name, $id, ['status' => '1'])) {
			$this->session->set_flashdata('message_type', 'error');
			$this->session->set_flashdata('message_name', 'Document name already exists! (A similar name with different special characters may exist)');
			redirect('document/editDocument/' . $id);
			return;
		}
		
		$sql = "update documents set document_name='".$this->db->escape_str($document_name)."' where id='$id'";
		$query1 = $this->db->query($sql);
		$this->session->set_flashdata('message_type', 'success');
		$this->session->set_flashdata('message_name', 'Document Successfully Updated');

		redirect('document/allDocuments');
		
	}
	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');

		// Convert 'Active' to 0 and anything else to 1
		$new_status = $status ;

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

		$sql = "UPDATE documents SET status='$new_status' WHERE id='$id'"; 
		$query = $this->db->query($sql);

		if ($query) {
			echo json_encode([
				'success'    => true,
				'message'    => 'Status updated successfully.',
				'new_status' => $new_status
			]);
		} else {
			echo json_encode([
				'success' => false,
				'message' => 'Failed to update status.'
			]);
		}
	}
	
	public function addDocumentGroup() {
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		
		// Permission check - edit permission required for adding groups
		require_edit_permission('document/groupList');
		
		$sql = "select * from documents";

		$document_query = $this->db->query($sql);
		$document_data = $document_query->result_array();

		if(empty($document_data)) {
			redirect('document/groupList');
		}
		
		// Get all existing document groups for circular reference prevention
		$all_groups_query = $this->db->query("SELECT id, document_id, grouped_doc_id FROM document_groups");
		$all_groups = $all_groups_query->result_array();
		
		$this->load->view('templates/header');
		$this->load->view('document/add_group', array(
			'document_data' => $document_data,
			'all_groups' => $all_groups
		));	
	}
	
	public function saveGroup() {
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		
		// Permission check - edit permission required
		require_edit_permission('document/groupList');
		
		$main_id = $_POST['main_document'];
		$child = implode(',',$_POST['child_document']);
		
		$query = "insert into document_groups(document_id, grouped_doc_id) values ('$main_id','$child')";
		$data = $this->db->query($query);
		
		redirect('document/groupList');
		
	}
	
	public function groupList() {
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		
		$role_id = $this->session->userdata('role_id');
		$company_id = $this->session->userdata('company_id');
		
		// For User role, only show document groups where main document is from their assigned document heads
		if ($role_id == '3') {
			$allowed_doc_heads = get_allowed_document_types();
			if (!empty($allowed_doc_heads)) {
				// Get document IDs from assigned document heads via mandatory_documents
				$placeholders = implode(',', array_fill(0, count($allowed_doc_heads), '?'));
				$sql = "SELECT 
							g.id,
							g.document_id,
							g.grouped_doc_id,
							d.document_name AS main_doc_name,
							string_agg(d2.document_name, ', ') AS grouped_doc_names
						FROM document_groups g
						LEFT JOIN documents d 
							ON d.id = g.document_id::int
						LEFT JOIN LATERAL (
							SELECT document_name
							FROM documents
							WHERE id IN (
								SELECT unnest(string_to_array(g.grouped_doc_id, ',')::int[])
							)
						) AS d2 ON TRUE
						WHERE g.document_id::int IN (
							SELECT DISTINCT md.document_id FROM mandatory_documents md 
							WHERE md.type_id IN ({$placeholders})
						)
						GROUP BY g.id, g.document_id, g.grouped_doc_id, d.document_name
						ORDER BY g.id ASC";
				$document_query = $this->db->query($sql, $allowed_doc_heads);
				$document_data = $document_query->result_array();
			} else {
				$document_data = [];
			}
		} else {
			$sql = "SELECT 
						g.id,
						g.document_id,
						g.grouped_doc_id,
						d.document_name AS main_doc_name,
						string_agg(d2.document_name, ', ') AS grouped_doc_names
					FROM document_groups g
					LEFT JOIN documents d 
						ON d.id = g.document_id::int                -- cast to int
					LEFT JOIN LATERAL (
						SELECT document_name
						FROM documents
						WHERE id IN (
							SELECT unnest(string_to_array(g.grouped_doc_id, ',')::int[])
						)
					) AS d2 ON TRUE
					GROUP BY g.id, g.document_id, g.grouped_doc_id, d.document_name
					ORDER BY g.id ASC;";
			$document_query = $this->db->query($sql);
			$document_data = $document_query->result_array();
		}
		
		// For each group, check status
		$group_status = [];
		
		if (!empty($company_id)) {
			// Get all documents that are in enabled document heads for this company
			$enabled_docs_query = $this->db->query("
				SELECT DISTINCT md.document_id
				FROM mandatory_documents md
				INNER JOIN company_document_heads cdh ON cdh.type_id = md.type_id
				WHERE cdh.company_id = ? AND cdh.is_enabled = true
			", array($company_id));
			
			$enabled_doc_ids = [];
			foreach ($enabled_docs_query->result() as $row) {
				$enabled_doc_ids[$row->document_id] = true;
			}
			
			// Get all uploaded documents for this company
			$uploaded_docs_query = $this->db->query("
				SELECT DISTINCT document_id
				FROM uploaded_documents
				WHERE company_id = ? AND is_deleted = 0
			", array($company_id));
			
			$uploaded_doc_ids = [];
			foreach ($uploaded_docs_query->result() as $row) {
				$uploaded_doc_ids[$row->document_id] = true;
			}
			
			// Check each group
			foreach ($document_data as $group) {
				$main_doc_id = $group['document_id'];
				$child_doc_ids = !empty($group['grouped_doc_id']) ? explode(',', $group['grouped_doc_id']) : [];
				$all_doc_ids = array_merge([$main_doc_id], $child_doc_ids);
				
				// Check if ALL documents are in enabled heads
				$all_in_enabled_heads = true;
				foreach ($all_doc_ids as $doc_id) {
					if (!isset($enabled_doc_ids[trim($doc_id)])) {
						$all_in_enabled_heads = false;
						break;
					}
				}
				
				// Check if ALL documents are uploaded
				$all_uploaded = true;
				foreach ($all_doc_ids as $doc_id) {
					if (!isset($uploaded_doc_ids[trim($doc_id)])) {
						$all_uploaded = false;
						break;
					}
				}
				
				$group_status[$group['id']] = [
					'in_enabled_heads' => $all_in_enabled_heads,
					'all_uploaded' => $all_uploaded
				];
			}
		}
		
		$this->load->view('templates/header');
		$this->load->view('document/group_list', array(
			'document_data' => $document_data,
			'group_status' => $group_status,
			'company_id' => $company_id
		));
	}
	
	public function groupEdit($id) {
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		
		// All logged-in users can view - edit actions are protected in the view
		$company_id = $this->session->userdata('company_id');
		
		$sql = "select * from documents";

		$document_query = $this->db->query($sql);
		$document_data = $document_query->result_array();

		$query = "select * from document_groups where id='$id'";
		$group_query = $this->db->query($query);
		$group_data = $group_query->result_array();
		
		if(empty($document_data)) {
			redirect('document/groupList');
		}
		
		// Get all existing document groups for circular reference prevention
		$all_groups_query = $this->db->query("SELECT id, document_id, grouped_doc_id FROM document_groups");
		$all_groups = $all_groups_query->result_array();
		
		// Check if all documents in group are uploaded (view-only mode)
		$is_view_only = false;
		if (!empty($company_id) && !empty($group_data)) {
			$main_doc_id = $group_data[0]['document_id'];
			$child_doc_ids = !empty($group_data[0]['grouped_doc_id']) ? explode(',', $group_data[0]['grouped_doc_id']) : [];
			$all_doc_ids = array_merge([$main_doc_id], $child_doc_ids);
			
			// Get all uploaded documents for this company
			$uploaded_docs_query = $this->db->query("
				SELECT DISTINCT document_id
				FROM uploaded_documents
				WHERE company_id = ? AND is_deleted = 0
			", array($company_id));
			
			$uploaded_doc_ids = [];
			foreach ($uploaded_docs_query->result() as $row) {
				$uploaded_doc_ids[$row->document_id] = true;
			}
			
			// Check if ALL documents are uploaded
			$all_uploaded = true;
			foreach ($all_doc_ids as $doc_id) {
				if (!isset($uploaded_doc_ids[trim($doc_id)])) {
					$all_uploaded = false;
					break;
				}
			}
			$is_view_only = $all_uploaded;
		}
		
		// Also view-only if user doesn't have edit permission
		if (!can_edit()) {
			$is_view_only = true;
		}
		
		$this->load->view('templates/header');
		$this->load->view('document/edit_group', array(
			'document_data' => $document_data,
			'group_data' => $group_data,
			'is_view_only' => $is_view_only,
			'all_groups' => $all_groups,
			'current_group_id' => $id
		));	
		
	}
	
	public function updateGroup() {
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		
		// Permission check - edit permission required
		require_edit_permission('document/groupList');
		
		$main_id = $_POST['main_document'];
		$id = $_POST['id'];
		$child = implode(',',$_POST['child_document']);
		
		$query = "update document_groups set document_id='$main_id',grouped_doc_id='$child' where id='$id'";
		$run_query = $this->db->query($query);
		redirect('document/groupList');
	}
	
	public function groupDelete($id) {
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		
		// Permission check - delete permission required
		require_delete_permission('document/groupList');
		
		$query = "delete from document_groups where id='$id'";
		$run_query = $this->db->query($query);
		redirect('document/groupList');
	}
	
	// 🔹 Private helper function to check if a record exists
    private function id_exists($table, $id)
    {
        return $this->db->where('document_id', $id)
                ->where('is_deleted', 0)
                ->limit(1)
                ->count_all_results($table) > 0;
    }
}
