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

class Report extends CI_Controller {

	public function index()
    {
        
    }

    public function reminder($company_id = null)
    {
        error_reporting(0);
        
        // Get logged-in user info from session
        $login_id = $this->session->userdata('id');
        if (empty($login_id)) {
            redirect('login');
        }
        
        // Get company_id from URL parameter, then session, then fallback
        if (empty($company_id)) {
            $company_id = $this->session->userdata('company_id');
        }
        if (empty($company_id)) {
            // Get first allowed company for user
            $allowed = get_allowed_companies();
            $company_id = !empty($allowed) ? $allowed[0] : null;
        }
        
        if (empty($company_id)) {
            $this->session->set_flashdata('message_type', 'error');
            $this->session->set_flashdata('message_name', 'No companies assigned to your account.');
            redirect('dashboard/dashboard');
        }
        
        // Check if user has access to this company
        require_company_access($company_id);
        
        // Store in session for subsequent requests
        $this->session->set_userdata('company_id', $company_id);

        // Year from querystring (normalize to int), default = current year
        $yearParam = $this->input->get('year');
        $currentYear = (int) date('Y');

        // if not provided or invalid, default to current year
        $year = is_numeric($yearParam) ? (int) $yearParam : $currentYear;

        // Get company start date + fiscal pattern
        $company = $this->db
            ->select('id, company_name, co_start_date, fiscal_year')
            ->from('company')
            ->where('id', $company_id)
            ->get()
            ->row_array();

        if (!empty($company['co_start_date'])) {
            $company_start_year = (int) date('Y', strtotime($company['co_start_date']));
        } else {
            // fallback if not set
            $company_start_year = 2020;
        }

        // Clamp the selected year to the allowed range: [company_start_year, currentYear]
        if ($year < $company_start_year) {
            $year = $company_start_year;
        }
        if ($year > $currentYear) {
            $year = $currentYear;
        }

        // Parse fiscal-year pattern to get month number (1-12)
        $fiscal_start_month = $this->getFiscalStartMonth($company['fiscal_year'] ?? 'Jan-Dec');

        $this->load->model('Upload_model');
        $this->load->model('Dashboard_model');
        
        // Get authority IDs for User role (role 3) for additional filtering
        $role_id = $this->session->userdata('role_id');
        $authorityIds = null;
        if ($role_id == '3') {
            $authorityIds = get_allowed_authorities();
        }

        // Get compliance matrix - filter by company_id and authorities for User role
        $matrix = $this->Upload_model->get_compliance_matrix($login_id, $year, $company_id, $authorityIds);
        
        // Get dashboard counts for comparison
        $companyIds = [$company_id];
        $counts = $this->Dashboard_model->getDashboardCounts($login_id, $companyIds, $authorityIds, $year);

        $data['year']                = (int)$year;
        $data['matrix']              = $matrix;
        $data['user_id']             = $login_id;
        $data['company_id']          = $company_id;
        $data['company_name']        = $company['company_name'] ?? '';
        $data['counts']              = $counts;
        $data['current_menu']        = 'report/reminder';
        $data['current_sub_menu']    = 'report/reminder';
        $data['company_start_year']  = $company_start_year;
        $data['fiscal_start_month']  = $fiscal_start_month;

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


        /**
     * 🔥 Universal Fiscal Year Parser
     * Supports: Jan-Dec, April-March, Nov-Oct, July-June, Oct-Sep, etc.
     * Returns numeric month (1-12)
     */
    private function getFiscalStartMonth($pattern)
    {
        if (empty($pattern)) {
            return 1; // default Jan
        }

        // Split on "-" or "–"
        $parts = preg_split('/[-–]/', $pattern);
        if (empty($parts)) {
            return 1;
        }

        // First part is fiscal start month
        $startPart = trim($parts[0]);
        if ($startPart === '') {
            return 1;
        }

        // Remove non-letters (e.g. "April (Q1)")
        $clean = preg_replace('/[^A-Za-z]/', '', $startPart);

        // First three letters → month abbreviation
        $abbr = strtoupper(substr($clean, 0, 3));

        // Map to month number
        $map = [
            'JAN' => 1, 'FEB' => 2, 'MAR' => 3,
            'APR' => 4, 'MAY' => 5, 'JUN' => 6,
            'JUL' => 7, 'AUG' => 8, 'SEP' => 9, 'SEPT' => 9,
            'OCT' => 10, 'NOV' => 11, 'DEC' => 12
        ];

        return $map[$abbr] ?? 1; // default Jan
    }

	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 getTypesByAuthority() {
		$authority_id = $this->input->post('authority_id');
		$docs = $this->db->query("SELECT * from sub_type where authority_id= '$authority_id'")->result_array();
		
	}
    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', $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
		$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
			$d['parent_uploaded'] = 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]);
				
				// Get mandatory status if parent is uploaded
				if ($d['parent_uploaded'] && 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
					];
				}
			}
		}

		echo json_encode($docs);
		} catch (Exception $e) {
			log_message('error', 'Error in getDocuments (report): ' . $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=='') {
			redirect('login');
		}
		
		// Check edit permission
		if (!can_edit()) {
			echo json_encode(['status' => false, 'error' => 'You do not have permission to upload documents.']);
			return;
		}
		
		//$config['upload_path']   = 'c:/xampp/htdocs/dms_type/uploads/documents/';
		//$config['upload_path']   = 'd:/wamp/www/dms_new/uploads/documents/';
		//$config['upload_path'] = FCPATH . '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);

		$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');

		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;  // relative path for frontend

		$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'  => $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);
		}

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

	
	public function removeFile()
	{
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		
		$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]);
	}
	
	

}
