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

class Upload extends CI_Controller {

    public function index()
    {
        $this->load->model('Upload_model');
        $this->load->model('Company_model');
        $data['authorities'] = $this->Upload_model->getAuthorities();
        $data['companies'] = $this->Company_model->getCompanies();
		$this->load->view('templates/header');
        $this->load->view('company/upload_view', $data);
    }

    public function getTypes()
    {
        $authority_id = $this->input->post('authority_id');
        $this->load->model('Upload_model');
        $types = $this->Upload_model->getTypesByAuthority($authority_id);
        echo json_encode($types);
    }

	public function getDocuments()
	{
		$type_id    = (int) $this->input->post('type_id');
		$company_id = (int) $this->input->post('company_id');

		$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.company_id = ?
			WHERE md.type_id = ?
		", [$company_id, $type_id])->result_array();

		echo json_encode($docs);
	}
    public function doUpload()
	{
		$config['upload_path'] = 'c:/xampp/htdocs/dms_new/uploads/documents/';
		//$config['upload_path'] = FCPATH . 'uploads/documents/';
		$config['allowed_types'] = 'pdf';
		$config['max_size']      = 2048;

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

		if (!$this->upload->do_upload('file')) {
			echo json_encode(['status' => false, 'error' => $this->upload->display_errors()]);
		} else {
			$uploadData = $this->upload->data();
			$file_name  = $uploadData['file_name'];
			$file_path  = 'uploads/documents/' . $file_name;  // ✅ save correct relative path

			$this->load->model('Upload_model');
			$this->Upload_model->saveUpload([
				'company_id'  => $company_id,
				'type_id'     => $type_id,
				'document_id' => $document_id,
				'file_name'   => $file_name,
				'file_path'   => $file_path,
				'document_month'   => date('m'),
				'document_year'   => date('Y')
			]);

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