<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH.'third_party/FPDF/fpdf.php';
require_once APPPATH . 'third_party/FPDI/src/autoload.php';
use setasign\Fpdi\Fpdi;

class Company 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 __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->helper(['url', 'form', 'download','date']);
        $this->load->library(['session', 'upload','zip']);
        $this->load->model('Company_model');
		
        // Ensure Composer autoload is loaded
        require_once APPPATH.'third_party/FPDI/src/Fpdi.php'; // FPDI
    } 
	public function index()
	{
		redirect('company/companies');
	}
	
	public function companies()
    {   
		$this->session->set_userdata('menu','company');
		$login_id = $this->session->userdata('id');
		$role_id = $this->session->userdata('role_id');
		if($login_id=='') {
			redirect('login');
		}
		
		if ($role_id == '3') {
			$user = $this->db->select('user_company')
				->from('users')
				->where('id', $login_id)
				->get()
				->row_array();

			$company_array = explode(',', $user['user_company']);

			$this->db->select('*')
				->from('company')
				->where_in('id', $company_array)
				->order_by('id', 'ASC');
		} else {
			$this->db->select('*')
				->from('company')
				->order_by('id', 'ASC');
		}

		$query = $this->db->get();
		$business_data = $query->result_array();
		
		$sql1="select * from authority where status='1' order by id asc ";  
		
		$authority_query = $this->db->query($sql1);
		$authority_data = $authority_query->result_array();
		
		$this->load->view('templates/header');
		$this->load->view('company/all_company',array('company_list'=>$business_data,'authority_data'=>$authority_data));
		//$this->load->view('templates/footer');

	}
	public function addCompany() {
		$this->session->set_userdata('menu','company');
		$login_id = $this->session->userdata('id');
		if($login_id=='') {
			redirect('login');
		}
		$sql="select * from authority where status='1' order by id asc ";  
		
		$query = $this->db->query($sql);
		$business_data = $query->result_array();
		
		$frequency = PAYMENT_OPTIONS;
		$this->load->view('templates/header');
		$this->load->view('company/add_company',array('authority'=>$business_data,'frequency'=>$frequency));
		//$this->load->view('templates/footer');
	}
	public function getTypeByAuthority() {
		$this->session->set_userdata('menu','company');
		$login_id = $this->session->userdata('id');
		if($login_id=='') {
			redirect('login');
		}
		$authority_id = $this->input->post('authority_id');

		$this->db->where('authority_id', $authority_id);
		$query = $this->db->get('sub_type');
		$result = $query->result_array();

		if ($result) {
			echo json_encode([
				'success' => true,
				'types' => $result // each row should have `id`, `type`
			]);
		} else {
			echo json_encode([
				'success' => false,
				'message' => 'No types found for this authority.'
			]);
		}
	}
	public function getFrequencyByType() {
		$this->session->set_userdata('menu','company');
		$login_id = $this->session->userdata('id');
		if($login_id=='') {
			redirect('login');
		}
		 $type_id = $this->input->post('type_id');

		$this->db->where('id', $type_id);
		$query = $this->db->get('sub_type');
		$row = $query->row_array();

		if ($row) {
			echo json_encode([
				'success' => true,
				'frequency' => $row['frequency']
			]);
		} else {
			echo json_encode([
				'success' => false,
				'message' => 'Frequency not found.'
			]);
		}
	}
	/*public function getDocumentsByType() {
		$this->load->model('Company_model');
		$type_id = $this->input->post('type_id');
		$documents = $this->Company_model->getDocumentsForType($type_id); // handle CSV IDs
		if(!empty($documents)){
			echo json_encode(['success'=>true, 'documents'=>$documents]);
		} else {
			echo json_encode(['success'=>false]);
		}
	}*/
	public function getDocumentsByType() {
		error_reporting(E_ALL);
		ini_set('display_errors', 1);
		$this->load->model('Company_model');
		$type_id = $this->input->post('type_id');
		$documents = $this->Company_model->getDocumentsForType($type_id);
		if (!empty($documents)) {
			echo json_encode(['success' => true, 'documents' => $documents]);
		} else {
			echo json_encode(['success' => false]);
		}
	}

	public function submit() {
		$company_id   = $this->input->post('company_id');
		$type_ids     = $this->input->post('type_id');
		$document_ids = $this->input->post('document_id');

		$upload_path = FCPATH . 'uploads/documents/';
		if (!is_dir($upload_path)) mkdir($upload_path, 0777, true);

		foreach ($type_ids as $rowIndex => $type_id) {
			if (empty($_FILES['document_file']['name'][$rowIndex])) continue;

			foreach ($_FILES['document_file']['name'][$rowIndex] as $docIndex => $name) {
				if ($name == '') continue;

				$_FILES['file']['name']     = $_FILES['document_file']['name'][$rowIndex][$docIndex];
				$_FILES['file']['type']     = $_FILES['document_file']['type'][$rowIndex][$docIndex];
				$_FILES['file']['tmp_name'] = $_FILES['document_file']['tmp_name'][$rowIndex][$docIndex];
				$_FILES['file']['error']    = $_FILES['document_file']['error'][$rowIndex][$docIndex];
				$_FILES['file']['size']     = $_FILES['document_file']['size'][$rowIndex][$docIndex];

				$config['upload_path']   = $upload_path;
				$config['allowed_types'] = 'pdf'; // ✅ only pdf
				$config['max_size']      = 2048;  // 2MB
				$config['file_name']     = time() . '_' . $_FILES['file']['name'];

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

				if ($this->upload->do_upload('file')) {
					$uploadData = $this->upload->data();
					$filePath = 'uploads/documents/' . $uploadData['file_name'];

					$this->db->insert('uploaded_documents', [
						'company_id'    => $company_id,
						'type_id'       => $type_id,
						'document_id'   => $document_ids[$rowIndex][$docIndex],
						'document_name' => $_FILES['file']['name'],
						'file_path'     => $filePath
					]);
				} else {
					$error = $this->upload->display_errors();
					$this->session->set_flashdata('error', $error);
					redirect('company');
				}
			}
		}

		$this->session->set_flashdata('success', 'Documents uploaded successfully!');
		redirect('company');
	}

	public function saveCompany() {
		
		$this->session->set_userdata('menu','type');
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		
		$company_name = $_POST['company_name'];
		$company_person = $_POST['company_person'];
		$company_email = $_POST['company_email'];
		$short_name = $_POST['short_name'];
		$country_code = $_POST['country_code'];
		$phone_number = $_POST['phone_number'];
		$financial_year = $_POST['financial_year'];
		$created_at = date('d-m-y');
		$query = "insert into company(company_name,contact_person,contact_email,status,created_at,fiscal_year,short_name, country_code, phone) values('".$company_name."','".$company_person."','".$company_email."','1','".$created_at."','".$financial_year."','".$short_name."','".$country_code."','".$phone_number."')";
		
		$insert_query = $this->db->query($query);	
		
		$this->session->set_flashdata('message_name', 'Company Created Successfully');
		
		redirect('company/companies');	
	}
	public function checkCompanyName()
	{
		/*$company_name = trim($this->input->post('company_name'));
		$id = $this->input->post('id'); // in case of edit mode

		$this->db->where('company_name', $company_name);

		if (!empty($id)) {
			// Exclude current record if editing
			$this->db->where('id !=', $id);
		}

		$exists = $this->db->get('company')->num_rows() > 0;

		echo $exists ? "false" : "true"; */
		$company_name = $this->input->post('company_name');
		$id           = $this->input->post('id'); // for edit mode

		// Normalize: remove spaces + lowercase
		$normalized = strtolower(str_replace(' ', '', $company_name));

		$this->db->select('id, company_name');
		$this->db->from('company');
		$query = $this->db->get();

		$exists = false;
		foreach ($query->result() as $row) {
			$db_normalized = strtolower(str_replace(' ', '', $row->company_name));
			if ($db_normalized === $normalized) {
				if (!empty($id) && $row->id == $id) {
					continue; // ignore self in edit mode
				}
				$exists = true;
				break;
			}
		}

		echo $exists ? "false" : "true"; 
		// "true" means available, "false" means duplicate
	}
	public function deleteCompany($id)
	{
		$this->session->set_userdata('menu','company');
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		
		$query = $this->db->get_where('company', ['id' => $id]);

		if ($query->num_rows() === 0) {
			redirect('company/companies');
		} else {
			$this->db->where('id', $id)->delete('company');
			$this->session->set_flashdata('message_name', 'Company Deleted Successfully');
			$this->session->set_flashdata('message_type', 'success'); // optional: success, error, info, warning
			redirect('company/companies');
		}
	}
	
	public function editCompany($id) {
		
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		$this->session->set_userdata('menu','company');
		
		$sql = "select * from company where id='$id'";

		$type_query = $this->db->query($sql);
		$type_data = $type_query->result_array();
		
		if(empty($type_data)) {
			redirect('company/companies');
		}
		
		$this->load->view('templates/header');
		$this->load->view('company/edit_company',array('company_data'=>$type_data));		
		
	}
	public function updateCompany() {
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		$this->session->set_userdata('menu','type');
		$id = $_POST['id'];
		$company_name = $_POST['company_name'];
		$company_person = $_POST['company_person'];
		$company_email = $_POST['company_email'];
		$short_name = $_POST['short_name'];
		$financial_year = $_POST['financial_year'];
		$country_code = $_POST['country_code'];
		$phone_number = $_POST['phone_number'];
		$created_at = date('d-m-y');

		$query = "update company set company_name='$company_name', contact_person='$company_person', contact_email='$company_email', short_name='$short_name', country_code='$country_code', phone='$phone_number',fiscal_year='$financial_year' where id='$id'";
		$insert_query = $this->db->query($query);	
		
		$this->session->set_flashdata('message_name', 'Company updated Successfully');
		
		redirect('company/companies');	
		
	}
	
	/*public function uploadDocuments($id) {
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		$this->session->set_userdata('menu','company');
		$sql="select * from company where status='1' order by id asc ";  
		
		$query = $this->db->query($sql);
		$business_data = $query->result_array();
		
		$sql1="select * from authority where status='1' order by id asc ";  
		
		$authority_query = $this->db->query($sql1);
		$authority_data = $authority_query->result_array();
		
		$this->load->view('templates/layout');
		$this->load->view('company/upload_documents',array('company_list'=>$business_data,'authority_data'=>$authority_data));
	}*/
	
	public function allDocument($company_id, $type_id)
	{
		// Include FPDF & FPDI (only if not already included elsewhere)
		if (!class_exists('FPDF')) {
			require_once APPPATH . 'third_party/FPDF/fpdf.php';
		}
		if (!class_exists('\setasign\Fpdi\Fpdi')) {
			require_once APPPATH . 'third_party/FPDI/src/autoload.php';
		}
		
		$c_id = $this->db
			->select('company_id')
			->from('uploaded_documents')
			->where('id', $company_id)
			->where('is_deleted', 0)
			->get()
			->result_array();
		
		$c__id = $c_id[0]['company_id'];

		// Fetch uploaded rows for the company and type (only rows with a file_name)
		$rows = $this->db
			->select('file_path, file_name')
			->from('uploaded_documents')
			->where('company_id', (int)$c__id)
			->where('type_id', (int)$type_id)
			->where('file_name IS NOT NULL', null, false)
			->where('is_deleted', 0)
			->get()
			->result_array();
		if (empty($rows)) {
			show_error("No uploaded documents found for this company and type.");
			return;
		}

		// Build absolute paths, keep only existing files, remove duplicates
		$paths = [];
		foreach ($rows as $r) {
			// normalize and protect against leading slashes
			$relative = ltrim($r['file_path'], '/\\');
			$full = FCPATH . $relative;

			if (file_exists($full) && is_readable($full)) {
				$paths[] = $full;
			} else {
				log_message('error', "allDocument: file missing or unreadable: {$full}");
			}
		}

		$paths = array_values(array_unique($paths));

		if (empty($paths)) {
			show_error("No physical files found on server for the selected documents.");
			return;
		}

		// Instantiate FPDI
		$pdf = new \setasign\Fpdi\Fpdi();

		// Merge files (skip encrypted/invalid ones)
		foreach ($paths as $file) {
			try {
				$pageCount = $pdf->setSourceFile($file);
			} catch (\setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException $e) {
				// encrypted or malformed PDF — skip it
				log_message('error', "allDocument: encrypted/invalid PDF skipped: {$file} — " . $e->getMessage());
				continue;
			} catch (\Exception $e) {
				log_message('error', "allDocument: could not read PDF {$file} — " . $e->getMessage());
				continue;
			}

			for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
				$templateId = $pdf->importPage($pageNo);
				$size = $pdf->getTemplateSize($templateId);
				$pdf->AddPage($size['orientation'], [$size['width'], $size['height']]);
				$pdf->useTemplate($templateId);
			}
		}

		// Final filename
		$outName = "Company_{$company_id}_Type_{$type_id}.pdf";

		// Clear any output buffering that might corrupt PDF
		if (ob_get_length()) {
			@ob_end_clean();
		}

		// Force download
		$pdf->Output($outName, 'D');
	}

	public function uploadDocuments() {
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		$this->session->set_userdata('menu','company');
		$sql="select * from company where status='1' order by id asc ";  
		
		$query = $this->db->query($sql);
		$business_data = $query->result_array();
		
		$sql1="select * from authority where status='1' order by id asc ";  
		
		$authority_query = $this->db->query($sql1);
		$authority_data = $authority_query->result_array();
		
		$this->load->view('templates/layout');
		$this->load->view('company/upload_documents',array('company_list'=>$business_data,'authority_data'=>$authority_data));
	}
	public function viewDocuments($id) {
		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		$this->load->model('Company_model');
		$this->session->set_userdata('menu','company');
		$sql="select * from company where status='1' and id='$id' order by id asc ";  
		$company_query = $this->db->query($sql);
		$business_data = $company_query->result_array();
		$data['type_list'] = $this->Company_model->get_all_types();
		
		$sql="select * from authority where status='1' order by id asc ";  
		$query = $this->db->query($sql);
		$authority_data = $query->result_array();
		
		$type_sql="select * from sub_type where status='1' order by type_name asc ";  
		$type_query = $this->db->query($type_sql);
		$type_data1 = $type_query->result_array();
		//$data['company_files'] = $this->Company_model->get_all_files();
		
		$authority = $this->input->post('authority');
		$month = $this->input->post('monthly');
		$year = $this->input->post('year');
		if($year=='') {
			$year = date('Y');
		}
		// Fetch filtered data from DB
		$data['type_data'] = $this->Company_model->getFilteredDocuments($id, $authority, $month, $year);
		$this->load->view('templates/header');
		$this->load->view('company/view_documents',array('company_list'=>$business_data,'data'=>$data,'type_data1'=>$type_data1,'authority_data'=>$authority_data,'type_data'=>$data['type_data']));
	}
	public function filter()
	{
		error_reporting(1);
		$this->load->model('Company_model');
		$authority = $this->input->post('authority');
		$month = $this->input->post('monthly');
		$year = $this->input->post('year');
		$company_id = $this->input->post('company_id');
		
		//log_message('Error', 'Executed Auth: ' . $authority);

		// Fetch filtered data from DB
		$data['type_data'] = $this->Company_model->getFilteredDocuments($company_id, $authority, $month, $year);
			// Load only partial view
		if (empty($data['type_data'])) {
			echo "<p class='text-center text-warning'>No record found</p>";
		} else {
			$this->load->view('company/_documents_table', $data);
		}
	}
	public function addDocument() {
		$doc_id = $this->input->post('doc_id');

		// Windows safe path
		$upload_path = FCPATH . 'uploads' . DIRECTORY_SEPARATOR . 'documents' . DIRECTORY_SEPARATOR;

		// Ensure folder exists
		if (!is_dir($upload_path)) {
			mkdir($upload_path, 0777, true);
		}

		//$config['upload_path']   = $upload_path;
		$config['upload_path'] = 'C:/xampp/htdocs/dms/uploads/documents/';
		$config['allowed_types'] = 'pdf';
		$config['max_size']      = 3048;
		$config['overwrite']     = TRUE;
		
		//$this->load->library('upload', $config);
		$this->load->library('upload');
		$this->upload->initialize($config);

		if ($this->upload->do_upload('file')) {
			$uploadData = $this->upload->data();

			$data = [
				'document_name' => $uploadData['file_name'],
				'file_path' => $uploadData['file_name'],
				'uploaded_at'   => date('Y-m-d H:i:s')
			];

			$this->db->where('id', $doc_id);
			$this->db->update('uploaded_documents', $data);
			
			echo json_encode([
				"status" => "success",
				"message" => "File uploaded successfully!"
			]);
		} else {
			echo json_encode([
				"status" => "error",
				"message" => strip_tags($this->upload->display_errors())
			]);
		}
	}
	public function getDocument(){
		$doc_id = $this->input->post('doc_id', true);

		//$doc = $this->db->get_where('uploaded_documents', ['id' => $doc_id])->row_array();
		$this->db->select('ud.*, st.id as docu_id , st.document_name');
		$this->db->from('uploaded_documents ud');
		$this->db->join('documents st', 'ud.document_id = st.id', 'left');
		$this->db->where('ud.id', $doc_id);
		$this->db->where('ud.is_deleted', 0);
		$doc = $this->db->get()->row_array();
		//log_message('Error', 'SQL Query of getDocument: ' . print_r($doc));
		if($doc){
			echo json_encode([
				'status' => 'success',
				'data' => $doc
			]);
		} else {
			echo json_encode([
				'status' => 'error',
				'message' => 'Document not found.'
			]);
		}
	}
	public function updateDocument() {
		$doc_id = $this->input->post('doc_id', true); // this should be uploaded_documents.id
		$document_name = $this->input->post('document_name', true);

		$data = ['document_name' => $document_name];

		// Handle file upload if new file provided
		if(!empty($_FILES['file']['name'])){
			$config['upload_path']   = FCPATH . 'uploads/documents/';
			$config['allowed_types'] = 'pdf';
			$config['max_size']      = 3048;
			$config['overwrite']     = TRUE;

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

			if($this->upload->do_upload('file')){
				$uploadData = $this->upload->data();
				$data['file_name']   = $uploadData['file_name'];
				$data['file_path']   = 'uploads/documents/' . $uploadData['file_name'];
				$data['uploaded_at'] = date('Y-m-d H:i:s');
				//$data['document_month'] = date('m');
				//$data['document_year']  = date('Y');
			} else {
				echo json_encode([
					'status'=>'error',
					'message'=>strip_tags($this->upload->display_errors())
				]);
				return;
			}
		}

		// Update row
		$this->db->where('id', $doc_id);
		$this->db->update('uploaded_documents', $data);
		

		// Fetch updated row
		$doc = $this->db->get_where('uploaded_documents', ['id'=>$doc_id])->row_array();

		if ($doc) {
			echo json_encode([
				'status'=>'success',
				'message'=>'Document updated successfully!',
				'data'=>$doc
			]);
		} else {
			echo json_encode([
				'status'=>'error',
				'message'=>'Document not found',
				'data'=>null
			]);
		}
	}
	
	public function downloadDocument($doc_id){
		//$doc = $this->db->get_where('uploaded_documents', ['id' => $doc_id])->row_array();
		
		log_message('error', 'Doc ID: ' . $doc_id);
		
		if ($doc_id) {
			$filePath = FCPATH . 'uploads/documents/' . $doc_id;

			if (file_exists($filePath)) {
				$fileData = file_get_contents($filePath);
				$response = [
					'file_name' => $doc_id,
					'file_data' => base64_encode($fileData)
				];
				echo json_encode($response);
			} else {
				echo json_encode(['error' => 'File not found']);
			}
		} else {
			echo json_encode(['error' => 'Invalid document']);
		}

	}
	
	public function fullDownload($company_id=2, $type_id=15)
	{
		// 🔹 Fetch uploaded documents from DB
		$files = $this->db->select('file_path')
			->from('uploaded_documents')
			->where('company_id', $company_id)
			->where('type_id', $type_id)
			->where('file_name IS NOT NULL', null, false) // only uploaded files
			->where('is_deleted', 0)
			->get()
			->result_array();
		
		if (empty($files)) {
			show_error("No documents found for this company and type.");
			return;
		}

		// Initialize FPDI
		$pdf = new Fpdi();

		foreach ($files as $row) {
			if($row['file_path'] !='') {
			echo $file = FCPATH . $row['file_path']; // assumes file_path is relative
			if (file_exists($file)) {
				$pageCount = $pdf->setSourceFile($file);

				// Import all pages of the file
				for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
					$templateId = $pdf->importPage($pageNo);
					$size = $pdf->getTemplateSize($templateId);

					$pdf->AddPage($size['orientation'], [$size['width'], $size['height']]);
					$pdf->useTemplate($templateId);
				}
			}
			}
		}

		// Force download merged file
		$pdf->Output("Company_{$company_id}_Type_{$type_id}.pdf", 'D');
	}
	/*public function submit()
	{
		echo '<pre>'; print_R($_POST);echo '</pre>';
		$company_id    = $this->input->post('company_id');
		$type_ids      = $this->input->post('type_id');
		$document_ids  = $this->input->post('document_id');
		$mandatory     = $this->input->post('mandatory'); // from mandatory_documents table
		 if (empty($type_ids) || count($type_ids) == 0) {
			$this->session->set_flashdata('error', 'Please select at least one type.');
			redirect('type');
			return;
		}
		$upload_path = FCPATH . 'uploads/documents/';
		
		if (!is_dir($upload_path)) {
			mkdir($upload_path, 0777, true);
		}

		foreach ($type_ids as $rowIndex => $type_id) {
			$docGroupIndex = $rowIndex + 1;
				if (!isset($document_ids[$docGroupIndex])) {
					continue;
				}
			foreach ($document_ids[$docGroupIndex] as $docIndex => $document_id) {
				
				$uploaded = false;
				$filePath = null;
				$originalFileName = null;

				// check if file uploaded
				if (isset($_FILES['document_file']['name'][$docGroupIndex][$docIndex]) &&
					$_FILES['document_file']['name'][$docGroupIndex][$docIndex] != '') {

					// Prepare file data
					$_FILES['file']['name']     = $_FILES['document_file']['name'][$docGroupIndex][$docIndex];
					$_FILES['file']['type']     = $_FILES['document_file']['type'][$docGroupIndex][$docIndex];
					$_FILES['file']['tmp_name'] = $_FILES['document_file']['tmp_name'][$docGroupIndex][$docIndex];
					$_FILES['file']['error']    = $_FILES['document_file']['error'][$docGroupIndex][$docIndex];
					$_FILES['file']['size']     = $_FILES['document_file']['size'][$docGroupIndex][$docIndex];

					// Upload config
					$config['upload_path']   = $upload_path;
					$config['allowed_types'] = 'pdf';
					$config['max_size']      = 2048; // 2MB
					$config['file_name']     = time() . '_' . preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $_FILES['file']['name']);

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

					if ($this->upload->do_upload('file')) {
						$uploadData       = $this->upload->data();
						$fileName         = $uploadData['file_name'];
						$filePath         = 'uploads/documents/' . $fileName;
						$originalFileName = $fileName;
						$uploaded         = true;
					} else {
						$error = $this->upload->display_errors();
						log_message('error', 'File upload error: ' . $error);
					}
				}

				// ✅ Always insert a row — uploaded or not
				$data = [
					'company_id'     => $company_id,
					'type_id'        => $type_id,
					'document_id'    => $document_id,
					'document_name'  => $originalFileName,
					'file_path'      => $filePath,
					'document_month' => date('m'),
					'document_year'  => date('Y'),
					'uploaded_at'=>date('Y-m-d h:i:s')
				];
				$this->db->insert('uploaded_documents', $data);
			}
			
		}

		redirect('company/uploadDocuments');
	}*/
		
	
	public function changeProjectStatus($id) {
		$login_id = $this->session->userdata('id');
		if($login_id=='') {
			redirect('login');
		}
		$this->session->set_userdata('user_menu','Master');
		$sql="select * from projects where id='$id'";    
		$query = $this->db->query($sql);
		$business_data = $query->result_array();
		$business_data  = $business_data[0];
		
		if($business_data['status']=='1') {
			$sql="update projects set status='0' where id='$id'"; 
		} else {
			$sql="update projects set status='1' where id='$id'"; 
		}
		$query = $this->db->query($sql);
		$date = date('Y-m-d h:i:s');
		$login_id = $this->session->userdata('id');
		$sql1="insert into log_table (description,action, created_time, user_id) values('Project Status Changed','Status Changed','".$date."','".$login_id."')";
		$query1 = $this->db->query($sql1);
		$this->session->set_flashdata('message_name', 'Project Status Successfully Updated');

		redirect('project/myProjects');
	}
	
	public function sendDocumentEmail(){
		$doc_id = $this->input->post('doc_id', true);
		$recipient = $this->input->post('recipient_email', true);

		$doc = $this->db->get_where('uploaded_documents', ['id'=>$doc_id])->row_array();
		if(empty($doc['file_path'])){
			echo json_encode(['status'=>'error','message'=>'Document not found']);
			return;
		}

		$file_path = FCPATH . 'uploads/documents/' . $doc['file_path'];
		if(!file_exists($file_path)){
			echo json_encode(['status'=>'error','message'=>'File not found on server']);
			return;
		}

		$this->load->library('email');

		$this->email->from('rajeshjoshi@eighttechprojects.com','Rajesh Joshi');
		$this->email->to($recipient);
		$this->email->subject('Document: ' . $doc['document_name']);
		$this->email->message('Please find the attached document.');

		$this->email->attach($file_path);

		if($this->email->send()){
			echo json_encode(['status'=>'success','message'=>'Email sent successfully!']);
		} else {
			echo json_encode(['status'=>'error','message'=>'Failed to send email.']);
		}
	}
	
	public function changeStatus()
	{
		$id     = $this->input->post('id');
		$status = $this->input->post('status');

		// Convert 'Active' to 0 and anything else to 1
		$new_status = ($status == '0') ? '0' : '1';

		$sql = "UPDATE company 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 deleteDocument(){
		$doc_id = $this->input->post('doc_id', true);
		
		// Get file path if you want to remove the file from uploads
		$doc = $this->db->get_where('uploaded_documents', ['id' => $doc_id])->row_array();
		if(!$doc){
			echo json_encode(['status'=>'error','message'=>'Document not found']);
			return;
		}

		// Delete file from server
		/*if(!empty($doc['file_name'])){
			$file_path = FCPATH . 'uploads/documents/' . $doc['file_name'];
			if(file_exists($file_path)){
				unlink($file_path);
			}
		}
		$data['file_name'] = '';
		$data['file_path'] = '';
		$data['document_month'] = '';
		$data['document_year'] = '';*/
		$data['is_deleted'] = 1;
		$data['deleted_at'] = date('Y-m-d H:i:s');
		// Delete DB recor
		$this->db->where('id', $doc_id);
		$this->db->update('uploaded_documents', $data);
		$doc = $this->db->get_where('uploaded_documents', ['id'=>$doc_id])->row_array();
		
		echo json_encode(['status'=>'success','message'=>'Document deleted successfully!']);
	}
	
	public function newDocuments($id) {
		$microtime = microtime(true); // Current time in seconds with microseconds
		$datetime = date('Y-m-d H:i:s') . sprintf('.%03d', ($microtime - floor($microtime)) * 1000);
		log_message('debug', 'Entered New Document Method for Company ID ' .$datetime);

		$login_id = $this->session->userdata('id');
		
		if($login_id=='') {
			redirect('login');
		}
		$this->load->model('Company_model');
		$this->session->set_userdata('menu','company');
		$sql="select * from company where status='1' and id='$id' order by id asc ";  
		$company_query = $this->db->query($sql);
		$business_data = $company_query->result_array();
		$data['type_list'] = $this->Company_model->get_all_types();
		
		// Wrap in an associative array to pass to view
		$companies_data = [
			'company_list' => $business_data
		];

		$sql="select * from authority where status='1' order by id asc ";  
		$query = $this->db->query($sql);
		$authority_data = $query->result_array();
		
		//$type_sql="select * from sub_type where status='1' order by type_name asc ";  
		
		$type_sql="SELECT DISTINCT ud.type_id, st.type_name,st.alias_name
					FROM public.uploaded_documents AS ud
					JOIN public.sub_type AS st ON ud.type_id = st.id
					WHERE ud.is_deleted = '0' AND st.status='1' AND ud.company_id= $id
					ORDER BY st.type_name";

		$type_query = $this->db->query($type_sql);
		$type_data1 = $type_query->result_array();
		//$data['company_files'] = $this->Company_model->get_all_files();
		
		$authority = $this->input->post('authority');
		$month = $this->input->post('monthly');
		$year = $this->input->post('year');
		if($year=='') {
			$year = date('Y');
		}
		// Fetch filtered data from DB
		$data['type_data'] = $this->Company_model->getFilteredDocuments($id, $authority, $month, $year);
		$this->load->view('templates/header',$companies_data);
		$this->load->view('company/new_documents',array('company_list'=>$business_data,'data'=>$data,'type_data1'=>$type_data1,'authority_data'=>$authority_data,'type_data'=>$data['type_data']));
		$microtime = microtime(true); // Current time in seconds with microseconds
		$datetimeExit = date('Y-m-d H:i:s') . sprintf('.%03d', ($microtime - floor($microtime)) * 1000);
		log_message('debug', 'Exited New Document Method for Company ID ' . $datetimeExit);
	}
	
	public function getDocumentsByAuthority() {
        /*$authority_ids = $this->input->post('authority_ids');
        $documents = $this->Company_model->getDocuments($authority_ids);
		header('Content-Type: application/json');
        echo json_encode($documents);*/
		$authority_ids = $this->input->post('authority_ids');
		$company_id = $this->input->post('company_id'); // added in case you need it

		log_message('debug', 'Authority IDs: ' . print_r($authority_ids, TRUE));
		log_message('debug', 'Company IDs: ' . $company_id);

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

		//$authority_ids = array();
		//log_message('error', 'Reassign Authority IDs: ' . print_r($authority_ids, TRUE));
		// If no authorities selected → load all docs
		if (empty($authority_ids)) {
			$documents = $this->Company_model->getAllDocuments($company_id);
		} else {
			$documents = $this->Company_model->getDocuments($authority_ids, $company_id);
		}

	    //log_message('error', 'Documents from getDocumentsByAuthority Method: ' . print_r($documents, TRUE));
		header('Content-Type: application/json');
		echo json_encode($documents);
    }
	
	public function reminderSent(){
		//exit('in ReminderSent function');
	}

	public function send_due_reminders()
    {
		//$this->load->model('Company_model');
        //$this->Company_model->send_reminders();
		$this->load->model('Company_Model');
			$reminder_data = $this->Company_model->getReminders();

			foreach ($reminder_data as $row) {
				//echo $row['document_name'];
				//echo "</br>";
				switch ($row['reminder_type']) {
					case 'today':
						//echo 'today'.$row['document_name'];
						$pending_docs = $this->Company_model->getUnuploadedDocuments($row['document_name']);
						// Send "Due Today" email
						break;
					case '1_day':
						//echo 'one day'.$row['document_name'];
						$pending_docs = $this->Company_model->getUnuploadedDocuments($row['document_name']);
						// Send "Due Tomorrow" email
						break;
					case '5_days':
						//echo 'five days'.$row['document_name'];
						$pending_docs = $this->Company_model->getUnuploadedDocuments($row['document_name']);
						// Send "Due in 5 Days" email
						break;
					case '10_days':
						//echo 'Ten days'.$row['document_name'];
						$pending_docs= $this->Company_model->getUnuploadedDocuments($row['document_name']);
						// Send "Due in 10 Days" email
						break;
				}
				/*echo '<pre>';
				print_r($row['reminder_type']);
				echo '<pre>';
				print_r($pending_docs);*/

				if (!empty($row['reminder_type']) && $row['reminder_type'] == '10_days'){
					echo 'Mail sent for 10 days';
				}
				if (!empty($row['reminder_type']) && $row['reminder_type'] == '5_days'){
					echo 'Mail sent for 5 days';
				}
				if (!empty($row['reminder_type']) && $row['reminder_type'] == '1_day'){
					echo 'Mail sent for 1 days';
				}
				if (!empty($row['reminder_type']) && $row['reminder_type'] == 'today'){
					echo 'Mail sent for todays';
				}
			}
			

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

			echo '<pre>';
			print_r($pending_docs_five_days);

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

			exit;
        $this->load->model('Company_model');
        $this->Company_model->send_reminders();
		echo "Reminder email(s) sent.";
    }

    /**
     * Download all documents under a given Authority (Type)
     * Example: /DocumentTree/download_all/3
     */
    public function download_all($type_id,$company_id) {
        //echo $type_id.'   '.$company_id;exit;
		//echo '<pre>'; print_R($_REQUEST);exit;
        $docs = $this->Company_model->getDocumentsZip($type_id,$company_id);
        $this->_create_zip($docs, "Authority_{$type_id}",'type');
    }

    /**
     * Download all documents under a specific Year for an Authority
     * Example: /DocumentTree/download_year/3/2025
     */
    public function download_year($type_id, $company_id, $year) {
        $docs = $this->Company_model->getDocumentsZip($type_id, $company_id, $year);
        $this->_create_zip($docs, "Authority_{$type_id}_{$year}",'year');
    }

    /**
     * Download all documents under a specific Month of a given Year and Authority
     * Example: /DocumentTree/download_month/3/2025/January
     */
    public function download_month($type_id, $company_id, $year, $month) {
        /*echo 'in month'; */
        $monthNumber = get_month_number($month);
        /*echo $monthNumber;  // Outputs: 03
		exit;*/
        $docs = $this->Company_model->getDocumentsZip($type_id, $company_id, $year, $monthNumber);
		log_message('debug', "October PDF: ". print_r($docs, true));
        $this->_create_zip($docs, "Authority_{$type_id}_{$year}_{$month}",'month');
    }

	private function _create_zip($docs, $zipName = 'Documents', $level = 'type')
	{
		$this->load->library('zip');
		$this->zip->clear_data();

		$baseDir = FCPATH . 'temp_zip/';
		$outputDir = FCPATH . 'output/';

		// 🔹 Clean old temp folder if exists
		if (is_dir($baseDir)) {
			$this->delete_directory($baseDir);
		}
		mkdir($baseDir, 0777, true);
		if (!is_dir($outputDir)) mkdir($outputDir, 0777, true);

		// 🔹 Group documents by authority → year → month
		
		$grouped = [];
		foreach ($docs as $item) {
			//$grouped[$item->authority][$item->year][$item->month][] = $item->file_name;
			//$grouped[$item->authority][$item->year][$item->month][] = $item->doc_name;
			$grouped[$item->authority][$item->year][$item->month][] = [
				'file_name' => $item->file_name,
				'doc_name'  => $item->doc_name
			];
		}

		// 🔹 Loop through authorities
		foreach ($grouped as $authority => $years) {

			// Determine ZIP structure based on level
			if ($level == 'type') {
				$zipFolderPath = "$baseDir$authority/";
				$zipFileName = "{$authority}.zip";
			}

			foreach ($years as $year => $months) {

				// For year-level, ZIP per year
				if ($level == 'year') {
					$zipFolderPath = "$baseDir{$authority}_{$year}/";
					$zipFileName = "{$authority}_{$year}.zip";
				}

				foreach ($months as $month => $docsList) {

					if ($level == 'type') {
						$monthDir = "$zipFolderPath$year/$month/";
					} elseif ($level == 'year') {
						$monthDir = "$zipFolderPath$month/";
					} else {
						$monthDir = "$baseDir$authority/$year/$month/";
					}

					if (!is_dir($monthDir)) {
						mkdir($monthDir, 0777, true);
					}

					// 🔹 Build descriptive merged filename based on document names
					//$fileBaseNames = [];
					$pdfFiles = [];
					foreach ($docsList as $doc) {
						
						//$name = pathinfo($f, PATHINFO_FILENAME);
						//$name = preg_replace('/[^A-Za-z0-9]+/', '_', strtolower($doc['doc_name']));
						//$name = preg_replace('/[^A-Za-z0-9]+/', '_', strtolower($authority));
						//$fileBaseNames[] = $name;

						$filePath = FCPATH . 'uploads/documents/' . $doc['file_name'];
						if (file_exists($filePath)) {
							$pdfFiles[] = $filePath;  // ✅ store full path, not just filename
						} else {
							log_message('error', "Missing PDF: {$filePath}");
						}
					}

					$name = preg_replace('/[^A-Za-z0-9]+/', '_', strtolower($authority));
					$mergedName = "{$name}_{$year}_{$month}.pdf";
                	$mergedPdfPath = $monthDir . $mergedName;

					// Join them into one filename (trim if too long)
					/*$mergedName = implode('_', $fileBaseNames);
					if (strlen($mergedName) > 150) { // prevent extremely long names
						$mergedName = substr($mergedName, 0, 150);
					}

					// 🔹 Append year and month
					$mergedName .= "_{$year}_{$month}.pdf";
					$mergedPdfPath = $monthDir . $mergedName;*/

					 // Merge actual files
					if (!empty($pdfFiles)) {
						$this->merge_pdfs($pdfFiles, $mergedPdfPath);
					} else {
						log_message('error', "No valid PDFs to merge for {$authority} - {$year} - {$month}");
						continue;
					}

					// 🔹 If this is month-level → directly download the merged file
					if ($level == 'month') {
						header('Content-Type: application/pdf');
						header('Content-Disposition: attachment; filename="' . basename($mergedPdfPath) . '"');
						readfile($mergedPdfPath);
						exit; // stop further execution
					}
				}

				// For year-level, zip each year separately
				if ($level == 'year') {
					$this->zip->clear_data();
					$this->zip->read_dir($zipFolderPath, FALSE);
					$zipFilePath = $outputDir . $zipFileName;
					$this->zip->archive($zipFilePath);
					$this->zip->download($zipFileName);
				}
			}

			// For type-level, zip after all years processed
			if ($level == 'type') {
				$this->zip->clear_data();
				$this->zip->read_dir($zipFolderPath, FALSE);
				$zipFilePath = $outputDir . $zipFileName;
				$this->zip->archive($zipFilePath);
				$this->zip->download($zipFileName);
			}
		}
	}

    /**
     * Internal function to build the ZIP and trigger download
     */
    private function _create_zip1($docs, $zipName = 'Documents') {
        //$this->zip->clear_data();
		$this->load->library('zip');
    	$this->zip->clear_data();	
        
		$baseDir = FCPATH . 'temp_zip/';
		if (is_dir($baseDir)) {
			$this->delete_directory($baseDir); // custom function defined below
		}
		mkdir($baseDir, 0777, true);

        /*$baseDir = FCPATH . 'temp_zip/'; 
        if (!is_dir($baseDir)) mkdir($baseDir, 0777, true);*/

        // Group files by authority -> year -> month
        $grouped = [];
        foreach ($docs as $item) {
            $grouped[$item->authority][$item->year][$item->month][] = $item->file_name;
        }
		echo '<pre>';print_r($grouped);	
        // Process each group

		foreach ($grouped as $authority => $years) {
            foreach ($years as $year => $months) {
                foreach ($months as $month => $files) {
                    $monthDir = $baseDir . "$authority/$year/$month/";
                    if (!is_dir($monthDir)) mkdir($monthDir, 0777, true);

                    // Merge all files for this month into a single PDF
                    $mergedPdfPath = $monthDir . "Merged_${year}_${month}.pdf";
                    $this->merge_pdfs($files, $mergedPdfPath);
                }
				
				// Zip only this authority + year folder
				$zipFolderPath = $baseDir . "$authority/$year/";
				$zipFileName = "{$authority}_{$year}.zip";
				$zipFilePath = FCPATH . "output/$zipFileName";
				 
				$this->zip->clear_data(); // clear before new zip
				$this->zip->read_dir($zipFolderPath, FALSE);
				$this->zip->archive($zipFilePath);
				$this->zip->download($zipFileName);
            }
        }
		exit;
		/*
		foreach ($grouped as $authority => $years) {
            foreach ($years as $year => $months) {
                foreach ($months as $month => $files) {
                    $monthDir = $baseDir . "$authority/$year/$month/";
                    if (!is_dir($monthDir)) mkdir($monthDir, 0777, true);

                    // Merge all files for this month into a single PDF
                    $mergedPdfPath = $monthDir . "Merged_${year}_${month}.pdf";
                    $this->merge_pdfs($files, $mergedPdfPath);
                }
				// Zip only this authority + year folder
				$zipFolderPath = $baseDir . "$authority/$year/";
				$zipFileName = "{$authority}_{$year}.zip";
				$zipFilePath = FCPATH . "output/$zipFileName";

				//$this->zip->clear_data(); // clear before new zip
				$this->zip->read_dir($zipFolderPath, FALSE);
				$this->zip->archive($zipFilePath);
				$this->zip->download($zipFileName);
            }
        }*/

        // Create ZIP
        /*$zipFile = FCPATH . "output/${authority}_${year}.zip";
        $this->load->library('zip');
        $this->zip->read_dir($baseDir, FALSE);
        $this->zip->archive($zipFile);
        $this->zip->download("${authority}_${year}.zip");*/
    }

	private function merge_pdfs($files, $outputPath)
	{
		$pdf = new Fpdi();

		foreach ($files as $filePath) {
			if (!file_exists($filePath)) continue;

			try {
				$pageCount = $pdf->setSourceFile($filePath);
				for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
					$tplIdx = $pdf->importPage($pageNo);
					$size = $pdf->getTemplateSize($tplIdx);
					$pdf->AddPage($size['orientation'], [$size['width'], $size['height']]);
					$pdf->useTemplate($tplIdx);
				}
			} catch (Exception $e) {
				log_message('error', "PDF merge failed for {$filePath}: " . $e->getMessage());
			}
		}

		$pdf->Output($outputPath, 'F');
	}


    /*private function merge_pdfs($files, $outputPath)
    {
        $pdf = new Fpdi();
        
        foreach ($files as $file) {
           // echo '<pre>';echo $file;
            $filePath = FCPATH . 'uploads/documents/' . $file; // adjust your file path
            if (!file_exists($filePath)) continue;

            try {
            $pageCount = $pdf->setSourceFile($filePath);
            for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
                $tplIdx = $pdf->importPage($pageNo);
                $size = $pdf->getTemplateSize($tplIdx);
                $pdf->AddPage($size['orientation'], [$size['width'], $size['height']]);
                $pdf->useTemplate($tplIdx);
            }
        } catch (Exception $e) {
            log_message('error', "PDF merge failed for {$file}: " . $e->getMessage());
        }
    }

    $pdf->Output($outputPath, 'F');
    }*/

	/**
	 * Helper function to recursively delete old temp folder
	 */
	private function delete_directory($dir)
	{
		if (!file_exists($dir)) return true;
		if (!is_dir($dir)) return unlink($dir);
		foreach (scandir($dir) as $item) {
			if ($item == '.' || $item == '..') continue;
			$this->delete_directory($dir . DIRECTORY_SEPARATOR . $item);
		}
		return rmdir($dir);
	}

	/**
     * Download all documents under a specific Month of a given Year and Authority
     * Example: /DocumentTree/view_documents/3/2025/January
     */
    public function view_documents($type_id, $company_id, $year, $month) {
        $monthNumber = get_month_number($month);
        
        $docs = $this->Company_model->getDocumentsZip($type_id, $company_id, $year, $monthNumber);
		log_message('debug', "October PDF: ". print_r($docs, true));
        
		if (empty($docs)) {
        show_error("No documents found for {$month} {$year}.", 404);
        return;
		}

		$pdfFiles = [];
		foreach ($docs as $doc) {
			
			//$name = pathinfo($f, PATHINFO_FILENAME);
			//$name = preg_replace('/[^A-Za-z0-9]+/', '_', strtolower($doc['doc_name']));
			//$name = preg_replace('/[^A-Za-z0-9]+/', '_', strtolower($authority));
			//$fileBaseNames[] = $name;

			$filePath = FCPATH . 'uploads/documents/' . $doc->file_name;
			if (file_exists($filePath)) {
				$pdfFiles[] = $filePath;  // ✅ store full path, not just filename
				$type_name = $doc->authority;
			} else {
				log_message('error', "Missing PDF: {$filePath}");
			}
		}

		// Ensure temp directory exists
		$outputDir = FCPATH . 'uploads/temp/';
		if (!is_dir($outputDir)) {
			mkdir($outputDir, 0755, true);
		}
		// Define merged PDF path
		$outputPath = $outputDir . "{$type_name}_{$year}_{$monthNumber}.pdf";

		// Merge the files using your existing helper
		$this->merge_pdfs($pdfFiles, $outputPath);

		// Return the public URL to AJAX
		$fileUrl = base_url("uploads/temp/" . basename($outputPath));
		redirect($fileUrl);
    }
}