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

class Upload extends CI_Controller {

	public function index($company_id = null)
    {
        if (!$company_id) {
            show_error("Company ID is required!", 400);
        }

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

        if (!$company) {
            show_error("Company not found", 404);
        }
		$login_id = $this->session->userdata('id');
		if($login_id=='') {
			redirect('login');
		}
        $this->load->model('Upload_model');
        $this->load->model('Company_model');
		$role_id = $this->session->userdata('role_id');
		if($role_id=='3') {
        $data['authorities'] = $this->Upload_model->getAuthorities();
		}
		if($role_id=='2') {
        $data['authorities'] = $this->Upload_model->getAuthorities();
		}
		if($role_id=='1') {
        $data['authorities'] = $this->Upload_model->getAuthorities();
		}
        $data['companies'] = $this->Company_model->getCompanies();
        $data['details'] = $company;

        $data['company'] = $company;

        $this->load->view('templates/header',$data);
        $this->load->view('company/upload_view', $data);
    }
	
    /*public function index()
    {
		$login_id = $this->session->userdata('id');
		if($login_id=='') {
			redirect('login');
		}
        $this->load->model('Upload_model');
        $this->load->model('Company_model');
		$role_id = $this->session->userdata('role_id');
		if($role_id=='3') {
        $data['authorities'] = $this->Upload_model->getUserAuthorities();
		}
		if($role_id=='2') {
        $data['authorities'] = $this->Upload_model->getAuthorities();
		}
		if($role_id=='1') {
        $data['authorities'] = $this->Upload_model->getAuthorities();
		}
        $data['companies'] = $this->Company_model->getCompanies();
		$this->load->view('templates/layout');
        $this->load->view('company/upload_view', $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()
	{
		$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');

		// 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();

		// 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 groups
		$groups = $this->db->select('document_id, grouped_doc_id')->get('document_groups')->result_array();

		// 4️⃣ Split comma-separated grouped_doc_id into individual IDs
		$supportive_ids = [];
		foreach($groups as $g){
			$ids = array_map('trim', explode(',', $g['grouped_doc_id']));
			foreach($ids as $id){
				if(!empty($id)) $supportive_ids[(int)$id] = true;
			}
		}

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

		// 6️⃣ Attach supportive documents to main docs
		foreach($docs as &$d){
			$sids = [];
			foreach($groups as $g){
				if($g['document_id'] == $d['id']){
					$ids = array_map('trim', explode(',', $g['grouped_doc_id']));
					foreach($ids as $id){
						if(!empty($id)) $sids[] = (int)$id;
					}
				}
			}

			$d['has_supportive_docs'] = count($sids) > 0 ? 1 : 0;
			$d['supportive_docs'] = [];

			foreach($sids 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
				];
			}
		}

		echo json_encode($docs);
	}



    public function doUpload()
	{
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		$config['upload_path']   = 'c:/xampp/htdocs/dms/uploads/documents/';
		//$config['upload_path']   = 'd:/wamp/www/dms_new/uploads/documents/';
		//$config['upload_path'] = FCPATH . 'uploads/documents/';
		$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]);
	}
	
	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']
			];
		}
		//echo '<pre>'; print_r($companyData);exit;	
		$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);   // stored as varchar
		$this->db->where('document_month', (string)$month); // "01".."12"
		$this->db->where('is_deleted', 0);

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

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

}
