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

class Upload extends CI_Controller {

	public function index($company_id = null)
    {
        // Get parameters from URL
        $authority_id = isset($_GET['authority_id']) ? $_GET['authority_id'] : null;
        $type_id = isset($_GET['type_id']) ? $_GET['type_id'] : null;
        $month = isset($_GET['month']) ? $_GET['month'] : null;
        $year = isset($_GET['year']) ? $_GET['year'] : null;
        $readonly = isset($_GET['readonly']) ? $_GET['readonly'] : null;
        $from = isset($_GET['from']) ? $_GET['from'] : null;
        // New return parameters for dashboard redirect
        $return_tab = isset($_GET['return_tab']) ? $_GET['return_tab'] : 'favourite';
        $return_year = isset($_GET['return_year']) ? $_GET['return_year'] : 'all';
        $return_companies = isset($_GET['return_companies']) ? $_GET['return_companies'] : '';
        
        if (!$company_id) {
            show_error("Company ID is required!", 400);
        }
		
		$login_id = $this->session->userdata('id');
		if($login_id=='') {
			redirect('login');
		}
		
		// Permission check - view upload page
		require_permission('upload.view');
		
		// Check company access
		require_company_access($company_id);

        // Fetch company details
        $company = $this->db->get_where('company', ['id' => $company_id])->row();

        if (!$company) {
            show_error("Company not found", 404);
        }
        
        $this->load->model('Upload_model');
        $this->load->model('Company_model');
		$role_id = $this->session->userdata('role_id');
		
		// Get authorities - filtered by company-enabled authorities
		// For User role (3), also filter by user's assigned authorities
		if ($role_id == '3') {
			$allowed_authorities = get_allowed_authorities();
			if (!empty($allowed_authorities)) {
				// Get company-enabled authorities that user also has access to
				$all_authorities = $this->Upload_model->getAuthorities($company_id);
				$data['authorities'] = array_filter($all_authorities, function($auth) use ($allowed_authorities) {
					return in_array($auth['authority_id'], $allowed_authorities);
				});
				$data['authorities'] = array_values($data['authorities']); // Re-index array
			} else {
				$data['authorities'] = [];
			}
		} else {
			$data['authorities'] = $this->Upload_model->getAuthorities($company_id);
		}
		
        $data['companies'] = $this->Company_model->getCompanies();
        $data['details'] = $company;

        $data['company'] = $company;
        
        // Pass URL parameters to view
        $data['preset_authority_id'] = $authority_id;
        $data['preset_type_id'] = $type_id;
        $data['preset_month'] = $month;
        $data['preset_year'] = $year;
        $data['preset_readonly'] = $readonly;
        $data['preset_from'] = $from;
        $data['return_tab'] = $return_tab;
        $data['return_year'] = $return_year;
        $data['return_companies'] = $return_companies;
        
        // Pass permission flags to view
        $data['can_edit'] = can_edit();
        $data['can_delete'] = can_delete();

        $this->load->view('templates/header',$data);
        $this->load->view('company/upload_view', $data);
    }
	
	public function getTypesByAuthority() {
		$authority_id = $this->input->post('authority_id');
		$company_id = $this->session->userdata('company_id');
		
		// Updated to use company_id directly in sub_type (no more company_document_heads bridge table)
		$sql = "SELECT st.* FROM sub_type st
			WHERE st.company_id = ? 
			AND st.authority_id = ? 
			AND st.status = '1'
			AND st.is_enabled = TRUE
			ORDER BY st.type_name ASC";
		$docs = $this->db->query($sql, array($company_id, $authority_id))->result_array();
		
		echo json_encode($docs);
	}
    public function getTypes()
    {
		error_reporting(1);
		ini_set('display_errors',1);
        $authority_id = $this->input->post('authority_id');
        $company_id = $this->input->post('company_id');
        $month = $this->input->post('month');
        $year = $this->input->post('year');

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

        $types = $this->Upload_model->getTypesByAuthority($authority_id,$company_id,$month, $year);
        echo json_encode($types);
    }

	public function getDocuments()
	{
		try {
			$type_id    = (int) $this->input->post('type_id');
			$company_id = (int) $this->input->post('company_id');
			$month      = $this->input->post('months');
			$year       = $this->input->post('years');

			// Load DocumentGroup model
			$this->load->model('DocumentGroup_model');

		// 0️⃣ Get document sequence from sub_type.document_name
		$sub_type = $this->db->select('document_name')
							 ->where('id', $type_id)
							 ->get('sub_type')
							 ->row();
		$doc_sequence = [];
		if ($sub_type && !empty($sub_type->document_name)) {
			$doc_sequence = array_map('intval', array_filter(explode(',', $sub_type->document_name)));
		}

		// 1️⃣ Fetch all mandatory documents (current type)
		$docs = $this->db->query("
			SELECT d.id, d.document_name, md.mandatory,
				   ud.file_name, ud.file_path
			FROM mandatory_documents md
			JOIN documents d ON d.id = md.document_id
			LEFT JOIN uploaded_documents ud 
				ON ud.document_id = md.document_id
			   AND ud.type_id = md.type_id
			   AND ud.is_deleted = 0
			   AND ud.company_id = ?
			   AND ud.document_month = ?
			   AND ud.document_year = ? 
			WHERE md.type_id = ?
		", [$company_id, $month, $year, $type_id])->result_array();

		// 1.1️⃣ Sort documents according to sub_type.document_name sequence
		if (!empty($doc_sequence)) {
			usort($docs, function($a, $b) use ($doc_sequence) {
				$posA = array_search((int)$a['id'], $doc_sequence);
				$posB = array_search((int)$b['id'], $doc_sequence);
				// If not found in sequence, put at the end
				if ($posA === false) $posA = PHP_INT_MAX;
				if ($posB === false) $posB = PHP_INT_MAX;
				return $posA - $posB;
			});
		}

		// 2️⃣ Fetch all uploaded documents for the company & month/year
		$all_uploaded = $this->db->select('document_id, file_name, file_path')
								 ->where('company_id', $company_id)
								 ->where('document_month', $month)
								 ->where('document_year', (string)$year)
								 ->where('is_deleted', 0)
								 ->get('uploaded_documents')
								 ->result_array();
		$uploaded_map = [];
		foreach($all_uploaded as $u) { $uploaded_map[$u['document_id']] = $u; }

		// 3️⃣ Get all document IDs in the current mandatory documents set
		$current_doc_ids = array_column($docs, 'id');
		$current_doc_ids = array_map('intval', $current_doc_ids);
		
		// 4️⃣ Get all document groups
		$groups = $this->db->select('document_id, grouped_doc_id')->get('document_groups')->result_array();

		// 5️⃣ Build parent-child relationships ONLY for documents in current set
		// A document is only considered a parent/child if BOTH parent AND child are in the current mandatory documents
		$parent_to_children = []; // parent_doc_id => [child_ids that are in current set]
		$child_to_parent = [];    // child_doc_id => parent_doc_id (only if both are in current set)
		
		foreach($groups as $g){
			$parent_id = (int)$g['document_id'];
			
			// Only process if parent is in current document set
			if (!in_array($parent_id, $current_doc_ids)) {
				continue; 
			}
			
			$all_child_ids = array_map('trim', explode(',', $g['grouped_doc_id']));
			$all_child_ids = array_filter($all_child_ids);
			$all_child_ids = array_map('intval', $all_child_ids);
			
			// Filter to only include children that are also in current document set
			$valid_child_ids = array_filter($all_child_ids, function($cid) use ($current_doc_ids) {
				return in_array($cid, $current_doc_ids);
			});
			
			if (!empty($valid_child_ids)) {
				$parent_to_children[$parent_id] = array_values($valid_child_ids);
				
				foreach($valid_child_ids as $cid){
					$child_to_parent[$cid] = $parent_id;
				}
			}
		}

		// 6️⃣ Fetch all supportive document names at once
		$all_child_ids = array_keys($child_to_parent);
		$supportive_docs_names = [];
		if(!empty($all_child_ids)){
			$query = $this->db->where_in('id', $all_child_ids)->get('documents')->result_array();
			foreach($query as $q){
				$supportive_docs_names[$q['id']] = $q['document_name'];
			}
		}

		// 7️⃣ Get child mandatory status for all parents in this set
		$child_mandatory_status = [];
		foreach($docs as $d) {
			if (isset($parent_to_children[$d['id']])) {
				$status = $this->DocumentGroup_model->getChildMandatoryStatus($d['id'], $company_id, $type_id, $month, $year);
				$child_mandatory_status[$d['id']] = $status;
			}
		}

		// 8️⃣ Attach parent-child info to each document
		foreach($docs as &$d){
			$doc_id = (int)$d['id'];
			
			// Check if this is a parent document (has children in current set)
			$d['is_parent'] = isset($parent_to_children[$doc_id]) ? 1 : 0;
			$d['has_supportive_docs'] = $d['is_parent'];
			
			// Check if this is a child document (has parent in current set)
			$d['is_child'] = isset($child_to_parent[$doc_id]) ? 1 : 0;
			$d['parent_document_id'] = $d['is_child'] ? $child_to_parent[$doc_id] : null;
			
			// Default values - document is enabled by default
			$d['parent_uploaded'] = false;
			$d['is_disabled'] = false;
			$d['is_mandatory_child'] = null;
			
			// Only apply parent-child logic if this is actually a child in current context
			if ($d['is_child']) {
				$parent_id = $child_to_parent[$doc_id];
				$d['parent_uploaded'] = isset($uploaded_map[$parent_id]);
				
				// Check if mandatory status has been set for this parent
				$hasStatus = false;
				if ($d['parent_uploaded']) {
					$hasStatus = $this->DocumentGroup_model->hasMandatoryStatusSet($parent_id, $company_id, $type_id, $month, $year);
				}
				$d['mandatory_status_set'] = $hasStatus;
				
				// Child is disabled if parent is NOT uploaded OR mandatory status is NOT set
				$d['is_disabled'] = !$d['parent_uploaded'] || !$hasStatus;
				
				// Get mandatory status if parent is uploaded and status is set
				if ($d['parent_uploaded'] && $hasStatus && isset($child_mandatory_status[$parent_id][$doc_id])) {
					$d['is_mandatory_child'] = $child_mandatory_status[$parent_id][$doc_id];
				}
			}

			// Attach supportive/child documents for parent docs
			$d['supportive_docs'] = [];
			if ($d['is_parent'] && isset($parent_to_children[$doc_id])) {
				$mandatory_status = $child_mandatory_status[$doc_id] ?? [];
				
				foreach($parent_to_children[$doc_id] as $sid){
					$d['supportive_docs'][] = [
						'id' => $sid,
						'document_name' => $supportive_docs_names[$sid] ?? '',
						'file_name' => $uploaded_map[$sid]['file_name'] ?? null,
						'file_path' => $uploaded_map[$sid]['file_path'] ?? null,
						'is_mandatory' => $mandatory_status[$sid] ?? null // null = not set
					];
				}
			}
			
			// Check if mandatory status needs to be set (parent uploaded but no status set)
			$d['needs_mandatory_setup'] = false;
			if ($d['is_parent'] && isset($uploaded_map[$doc_id]) && !empty($parent_to_children[$doc_id])) {
				$hasStatus = $this->DocumentGroup_model->hasMandatoryStatusSet($doc_id, $company_id, $type_id, $month, $year);
				$d['needs_mandatory_setup'] = !$hasStatus;
			}
		}

		echo json_encode($docs);
		} catch (Exception $e) {
			log_message('error', 'Error in getDocuments: ' . $e->getMessage());
			echo json_encode(['error' => 'An error occurred while loading documents. Please try again.']);
		}
	}



    public function doUpload()
	{
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			echo json_encode(['status' => false, 'error' => 'Session expired. Please login again.']);
			return;
		}
		
		// Check edit permission
		if (!can_edit()) {
			echo json_encode(['status' => false, 'error' => 'You do not have permission to upload documents.']);
			return;
		}

		$company_id  = $this->input->post('company_id');
		$type_id     = $this->input->post('type_id');
		$document_id = $this->input->post('document_id');
		$document_month = $this->input->post('month');
		$document_year  = $this->input->post('year');

		// Validate required parameters
		if (empty($company_id) || empty($type_id) || empty($document_id) || empty($document_month) || empty($document_year)) {
			echo json_encode(['status' => false, 'error' => 'Missing required parameters.']);
			return;
		}

		// Check frequency-based upload permission
		$this->load->model('Upload_model');
		$frequencyCheck = $this->Upload_model->checkFrequencyDue($type_id, $company_id, $document_month, $document_year);
		
		if (!$frequencyCheck['allowed']) {
			$errorMsg = $frequencyCheck['message'];
			if (isset($frequencyCheck['next_due'])) {
				$errorMsg .= ' Next due: ' . $frequencyCheck['next_due'];
			}
			echo json_encode(['status' => false, 'error' => $errorMsg, 'frequency_error' => true]);
			return;
		}

		//$config['upload_path']   = 'c:/xampp/htdocs/dms/uploads/documents/';
		$config['upload_path'] = $this->config->item('documents_upload_path');
		$config['allowed_types'] = 'pdf';
		$config['max_size']      = 10240;

		// Make sure the directory exists
		if (!is_dir($config['upload_path'])) {
			mkdir($config['upload_path'], 0777, true);
		}

		$this->load->library('upload');
		$this->upload->initialize($config);

		if (!$this->upload->do_upload('file')) {
			echo json_encode(['status' => false, 'error' => $this->upload->display_errors()]);
			return;
		}

		$uploadData = $this->upload->data();
		$file_name  = $uploadData['file_name'];
		$file_path  = 'uploads/documents/' . $file_name;

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

		// ✅ Check if record exists
		$exists = $this->db->get_where('uploaded_documents', [
			'company_id'     => $company_id,
			'type_id'        => $type_id,
			'document_id'    => $document_id,
			'document_month' => $document_month,
			'document_year'  => (string)$document_year,
			'is_deleted' => 0
		])->row_array();

		$data = [
			'company_id'     => $company_id,
			'type_id'        => $type_id,
			'document_id'    => $document_id,
			'file_name'      => $file_name,
			'file_path'      => $file_path,
			'document_month' => $document_month,
			'document_year'  => $document_year,
			'user_id'        => $login_id
		];

		if ($exists) {
			$this->db->where('id', $exists['id'])->update('uploaded_documents', $data);
		} else {
			$this->db->insert('uploaded_documents', $data);
		}

		// Check if this is a parent document that needs mandatory setup
		$this->load->model('DocumentGroup_model');
		$is_parent = $this->DocumentGroup_model->isParentDocument($document_id);
		$child_docs = [];
		$needs_mandatory_setup = false;
		
		if ($is_parent) {
			// Get child documents and filter to only those in current document head
			$all_children = $this->DocumentGroup_model->getChildDocuments($document_id);
			
			// Get mandatory document IDs for this type
			$mandatory_docs = $this->db->select('document_id')
									   ->where('type_id', $type_id)
									   ->get('mandatory_documents')
									   ->result_array();
			$mandatory_doc_ids = array_column($mandatory_docs, 'document_id');
			
			// Filter children to only those in current document head
			$filtered_children = array_filter($all_children, function($child) use ($mandatory_doc_ids) {
				return in_array($child['id'], $mandatory_doc_ids);
			});
			$child_docs = array_values($filtered_children);
			
			// Only show modal if there are children in current document head
			if (!empty($child_docs)) {
				// Check if mandatory status is already set
				$hasStatus = $this->DocumentGroup_model->hasMandatoryStatusSet($document_id, $company_id, $type_id, $document_month, $document_year);
				
				if (!$hasStatus) {
					$needs_mandatory_setup = true;
				}
			}
		}

		echo json_encode([
			'status'      => true,
			'file'        => $file_name,
			'file_path'   => $file_path,
			'document_id' => $document_id,
			'is_parent'   => $is_parent,
			'needs_mandatory_setup' => $needs_mandatory_setup,
			'child_docs'  => $child_docs
		]);
	}

	/**
	 * Save child document mandatory status
	 * Called after parent document is uploaded
	 */
	public function saveChildMandatoryStatus()
	{
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			echo json_encode(['status' => false, 'error' => 'Session expired']);
			return;
		}

		$parent_document_id = $this->input->post('parent_document_id');
		$company_id = $this->input->post('company_id');
		$type_id = $this->input->post('type_id');
		$month = $this->input->post('month');
		$year = $this->input->post('year');
		$child_mandatory = $this->input->post('child_mandatory'); // Array: [child_id => is_mandatory]

		// Debug logging
		log_message('debug', "saveChildMandatoryStatus - parent_id: $parent_document_id, company: $company_id, type: $type_id, month: $month, year: $year");
		log_message('debug', "child_mandatory raw: " . print_r($child_mandatory, true));

		if (empty($parent_document_id) || empty($company_id) || empty($type_id) || empty($month) || empty($year)) {
			log_message('error', "saveChildMandatoryStatus - Missing parameters: parent=$parent_document_id, company=$company_id, type=$type_id, month=$month, year=$year");
			echo json_encode(['status' => false, 'error' => 'Missing required parameters']);
			return;
		}

		$this->load->model('DocumentGroup_model');
		
		// Ensure child_mandatory is an array
		if (!is_array($child_mandatory)) {
			$child_mandatory = [];
		}

		$result = $this->DocumentGroup_model->saveChildMandatoryStatus(
			$parent_document_id,
			$child_mandatory,
			$company_id,
			$type_id,
			$month,
			$year
		);

		if ($result) {
			echo json_encode(['status' => true, 'message' => 'Child mandatory status saved successfully']);
		} else {
			echo json_encode(['status' => false, 'error' => 'Failed to save child mandatory status']);
		}
	}

	/**
	 * Check if a document can be uploaded (parent-child validation)
	 */
	public function checkParentChildStatus()
	{
		$document_id = $this->input->post('document_id');
		$company_id = $this->input->post('company_id');
		$type_id = $this->input->post('type_id');
		$month = $this->input->post('month');
		$year = $this->input->post('year');

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

		// Check if this is a child document
		$parentInfo = $this->DocumentGroup_model->isChildDocument($document_id);

		if ($parentInfo) {
			// This is a child document - check if parent is uploaded
			$parentUploaded = $this->DocumentGroup_model->isParentUploaded(
				$parentInfo['parent_id'],
				$company_id,
				$type_id,
				$month,
				$year
			);

			echo json_encode([
				'is_child' => true,
				'parent_id' => $parentInfo['parent_id'],
				'parent_name' => $parentInfo['parent_name'],
				'parent_uploaded' => $parentUploaded,
				'can_upload' => $parentUploaded,
				'message' => $parentUploaded ? 'OK' : "Please upload parent document '{$parentInfo['parent_name']}' first"
			]);
		} else {
			// Not a child document - can upload
			echo json_encode([
				'is_child' => false,
				'can_upload' => true,
				'message' => 'OK'
			]);
		}
	}

	/**
	 * Get child documents for a parent (for mandatory modal)
	 */
	public function getChildDocumentsForParent()
	{
		$parent_document_id = $this->input->post('parent_document_id');
		$company_id = $this->input->post('company_id');
		$type_id = $this->input->post('type_id');
		$month = $this->input->post('month');
		$year = $this->input->post('year');

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

		$children = $this->DocumentGroup_model->getChildDocumentsWithStatus(
			$parent_document_id,
			$company_id,
			$type_id,
			$month,
			$year
		);

		echo json_encode([
			'status' => true,
			'children' => $children
		]);
	}

	public function removeFile()
	{
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			echo json_encode(['status' => false, 'error' => 'Session expired. Please login again.']);
			return;
		}
		
		// Check delete permission
		if (!can_delete()) {
			echo json_encode(['status' => false, 'error' => 'You do not have permission to delete documents.']);
			return;
		}
		
		$company_id  = $this->input->post('company_id');
		$type_id     = $this->input->post('type_id');
		$document_id = $this->input->post('document_id');

		// 🔍 First check if record exists
		$query = $this->db->get_where('uploaded_documents', [
			'company_id'  => $company_id,
			'type_id'     => $type_id,
			'document_id' => $document_id,
			'user_id'=>$login_id,
			'is_deleted'=>0
		]);

		if ($query->num_rows() === 0) {
			echo json_encode(['status' => false, 'error' => 'Record not found']);
			return;
		}

		$file = $query->row_array();

		// ✅ Delete physical file
		$file_path = FCPATH . $file['file_path'];
		if (is_file($file_path)) {
			unlink($file_path);
		}

		// ✅ Delete DB entry
		$this->db->where([
			'company_id'  => $company_id,
			'type_id'     => $type_id,
			'document_id' => $document_id,
			'user_id'=>$login_id
			
		])->delete('uploaded_documents');

		echo json_encode(['status' => true]);
	}
	
	public function reminder($user_id) {
		error_reporting(1);
		$month = date('m');
		$year = date('Y');
		$this->load->model('Upload_model');
		$results = $this->Upload_model->get_missing_documents_by_company($user_id, $month, $year);

		$companyData = [];
		foreach ($results as $row) {
			$companyData[$row['company_name']][] = [
				'type_name' => $row['type_name'],
				'missing_documents' => $row['missing_documents']
			];
		}
		$data['companyData'] = $companyData;
		$this->load->view('templates/header');
		$this->load->view('company/missing_docs', $data);
		
	}
	public function filter_missing_docs()
	{
		$month = $this->input->post('month');
		$year = $this->input->post('year');
		$user_id = $this->input->post('user_id');

		$this->load->model('Upload_model');
		$results = $this->Upload_model->get_missing_documents_by_company($user_id, $month, $year);

		$companyData = [];
		foreach ($results as $row) {
			$companyData[$row['company_name']][] = [
				'type_name' => $row['type_name'],
				'missing_documents' => $row['missing_documents']
			];
		}

		$data['companyData'] = $companyData;

		// Return partial HTML only (no header/footer)
		$this->load->view('company/missing_docs_table', $data);
	}

	public function checkAlreadyUploaded()
	{
		$company_id = $this->input->post('company_id');
		$type_id    = $this->input->post('type_id');
		$year       = $this->input->post('year');
		$month      = $this->input->post('month');

		if (empty($company_id) || empty($type_id) || empty($year) || empty($month)) {
			echo json_encode(['exists' => false]);
			return;
		}

		$this->db->from('uploaded_documents');
		$this->db->where('company_id', $company_id);
		$this->db->where('type_id', $type_id);
		$this->db->where('document_year', (string)$year);
		$this->db->where('document_month', (string)$month);
		$this->db->where('is_deleted', 0);

		$exists = $this->db->count_all_results() > 0;

		echo json_encode(['exists' => $exists]);
	}

	/**
	 * Check if upload is allowed based on frequency
	 * Called via AJAX before allowing upload
	 */
	public function checkUploadAllowed()
	{
		try {
			$login_id = $this->session->userdata('id');
			if ($login_id == '') {
				echo json_encode(['allowed' => false, 'message' => 'Session expired. Please login again.']);
				return;
			}

			$company_id = $this->input->post('company_id');
			$type_id    = $this->input->post('type_id');
			$year       = $this->input->post('year');
			$month      = $this->input->post('month');

			if (empty($company_id) || empty($type_id) || empty($year) || empty($month)) {
				echo json_encode(['allowed' => false, 'message' => 'Missing required parameters.']);
				return;
			}

			$this->load->model('Upload_model');
			$result = $this->Upload_model->checkFrequencyDue($type_id, $company_id, $month, $year);

			echo json_encode($result);
		} catch (Exception $e) {
			echo json_encode(['allowed' => false, 'message' => 'Error: ' . $e->getMessage(), 'error' => true]);
		}
	}

}
