<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use Dompdf\Dompdf;
use Dompdf\Options;

class Certificates extends BaseController {

	protected array $data;
	
	// Untuk Sertifikat Instalasi [1]
	public function installationIndex() { // Index
		return view('certificate_installation_index');
	}
	public function getDataIndexInstallation() { // Untuk API Get Data
		// $actid = $this->request->getVar('actid'); Siapa Tahu Buat 
	}
	public function createinstallationPreview($certid = null) { // Untuk Preview Sertifikat
		//Melakukan search data dari database
	}

	// Untuk Sertifikat Maintenance [2]
	public function maintenanceIndex() { // Index
		return view('certificate_maintenance_index');
	}
	public function getDataIndexMaintenance() { // Untuk API Get Data
		// $actid = $this->request->getVar('actid'); Siapa Tahu Buat 
		
		$certificates = [
			[
				'certid' => 'f353ca91-4fc5-49f2-9b9e-304f83d11914',
				'certname' => 'Jokoh Calibration Certificate',
				'productname' => 'Jokoh',
				'productnumber' => 'SN-2024-001',
				'issuedate' => '2024-01-15',
				'expirydate' => '2025-01-15',
				'vendor' => 'Summit Calibration Lab',
				'isval' => null
			],
			[
				'certid' => 'f353ca91-4fc5-49f2-9b9e-304f83d11915',
				'certname' => 'Electrical Safety Test',
				'productname' => 'GE Healthcare VIVID',
				'productnumber' => 'GE-VIV-Q992',
				'issuedate' => '2024-06-12',
				'expirydate' => '2026-10-01',
				'vendor' => 'Pramita Medika Service',
				'isval' => '2026-03-01'
			]
		];

		// If no actid, return all certificates
		if (empty($certificates)) {
			return $this->response->setJSON(null);
		}

		return $this->response->setJSON($certificates);
	}
	public function createMaintenancePreview($certid = null) { // Untuk Preview Sertifikat
		//Melakukan search data dari database
		
		if (!$certid) {
			return $this->response->setStatusCode(400)->setJSON(['error' => 'Certificate ID is required']);
		}

		// Get certificate data Berdasarkan certid
		$certificate = [
			'certid' => 'f353ca91-4fc5-49f2-9b9e-304f83d11914',
			'certname' => 'Jokoh Calibration Certificate',
			'productname' => 'Jokoh',
			'productnumber' => 'SN-2024-001',
			'issuedate' => '2024-01-15',
			'expirydate' => '2025-01-15',
			'vendor' => 'Summit Calibration Lab',
			'isval' => null
		];

		if (empty($certificate)) { // JIka Tidak Ada
			return $this->response->setStatusCode(404)->setJSON(['error' => 'Maintenance certificate not found']);
		}
		
		return $this->previewPdf($certificate, 'maintenance'); // Preview PDF
	}
	
	// Untuk Sertifikat Training [3]
	public function trainingIndex() {
		return view('certificate_training_index');
	}
	public function getDataIndexTraining() {
		// $actid = $this->request->getVar('actid');
		
		// Sample data - replace with actual database query
		$certificates = [
			[
				'certid' => 'CERT001',
				'certname' => 'Jokoh Calibration Certificate',
				'productname' => 'Jokoh',
				'productnumber' => 'SN-2024-001',
				'issuedate' => '2024-01-15',
				'expirydate' => '2025-01-15',
				'vendor' => 'Summit Calibration Lab',
				'type' => 'joko',
				'sitename' => 'Jakarta Office',
				'siteid' => 'SITE001'
			],
			[
				'certid' => 'CERT002',
				'certname' => 'TMS50i Calibration Certificate',
				'productname' => 'TMS50i',
				'productnumber' => 'SN-2024-002',
				'issuedate' => '2024-02-15',
				'expirydate' => '2025-02-15',
				'vendor' => 'Summit Calibration Lab',
				'type' => 'tms',
				'sitename' => 'Surabaya Office',
				'siteid' => 'SITE002'
			],
			[
				'certid' => 'CERT003',
				'certname' => 'Tokyo Boeki Calibration Certificate',
				'productname' => 'Tokyo Boeki',
				'productnumber' => 'SN-2024-003',
				'issuedate' => '2024-03-15',
				'expirydate' => '2025-03-15',
				'vendor' => 'Summit Calibration Lab',
				'type' => 'boeki',
				'sitename' => 'Bandung Office',
				'siteid' => 'SITE003'
			]
		];

		// If no actid, return all certificates
		if (empty($certificates)) {
			return $this->response->setJSON(null);
		}

		return $this->response->setJSON($certificates);
	}

	// Untuk Sertifikat Calibrate [4]
	public function calibrateIndex() {
		return view('certificate_calibration_index');
	}


	// Helper Function Preview dan Validate
	private function previewPdf($certificate, $type, $productType=null) { // Untuk Show/Preview PDF
		// Generate PDF
		$options = new Options();
		$options->set('isRemoteEnabled', true);
		$options->set('isHtml5ParserEnabled', true);
		// $options->set('defaultFont', 'Playfair Display');

		$dompdf = new Dompdf($options);

		// Format dates
		$issuedate = date('F d, Y', strtotime($certificate['issuedate']));
		$expirydate = date('F d, Y', strtotime($certificate['expirydate']));

		// Get status
		$today = date('Y-m-d');
		$expiryCheck = date('Y-m-d', strtotime($certificate['expirydate']));
		$daysUntilExpiry = (strtotime($expiryCheck) - strtotime($today)) / (60 * 60 * 24);

		if ($daysUntilExpiry < 0) {
			$status = 'Expired';
			$statusColor = '#dc3545';
		} elseif ($daysUntilExpiry <= 30) {
			$status = 'Expiring Soon';
			$statusColor = '#ffc107';
		} else {
			$status = 'Active';
			$statusColor = '#28a745';
		}

		// Select template and orientation based on type
		$template = 'certificate_pdf';
		$orientation = 'portrait';

		switch($type) {
			case 'training':
				$template = 'certificates/certificate_training';
				$orientation = 'landscape';
				break;
			case 'calibration':
				if ($productType == 'tms50i') {
					$template = 'certificates/callibrations_template/certificate_tms50i_calibration';
				} else if ($productType == 'tms24i') {
					$template = 'certificates/callibrations_template/certificate_tms24i_calibration';
				} else if ($productType == 'tms30i') {
					$template = 'certificates/callibrations_template/certificate_tms30i_calibration';
				} else if ($productType == 'bs430') {
					$template = 'certificates/callibrations_template/certificate_bs430_calibration';
				} else if ($productType == 'cl900i') {
					$template = 'certificates/callibrations_template/certificate_cl900i_calibration';
				} else if ($productType == 'jokoh') {
					$template = 'certificates/callibrations_template/certificate_jokoh_calibration';
				} else if ($productType == 'bc760r') {
					$template = 'certificates/callibrations_template/certificate_bc760r_calibration';
				} else if ($productType == 'bc5140') {
					$template = 'certificates/callibrations_template/certificate_bc5140_calibration';
				} else {
					return $this->response->setStatusCode(404)->setJSON(['error' => 'Not Found']);
				}
				$orientation = 'portrait';
				break;
			case 'maintenance':
				$template = 'certificates/certificate_maintenance';
				$orientation = 'landscape';
				break;
		}

		$html = view($template, [
									'certificate' => $certificate,
									'issuedate' => $issuedate,
									'expirydate' => $expirydate,
									'status' => $status,
									'statusColor' => $statusColor
								]);

		$dompdf->loadHtml($html);
		// $dompdf->set_option('isRemoteEnabled', true);
		$dompdf->setPaper('A4', $orientation);
		$dompdf->render();

		// Output PDF
		$filename = 'Certificate_' . $certificate['certid'] . '.pdf';
		$dompdf->stream($filename, ['Attachment' => false]);
	}
	public function validateCertificate() { // Untuk Validasi Certificate
		$certid = $this->request->getPost('certid');
		$certificateType = $this->request->getPost('certificateType');

		if (!$certid) {
			return $this->response->setJSON([
				'success' => false,
				'message' => 'Certificate ID is required'
			]);
		}

		// Dummy data certificates
		$certificates = [
			'certid' => 'f353ca91-4fc5-49f2-9b9e-304f83d11914',
			'certname' => 'Jokoh Calibration Certificate',
			'productname' => 'Jokoh',
			'productnumber' => 'SN-2024-001',
			'issuedate' => '2024-01-15',
			'expirydate' => '2025-01-15',
			'vendor' => 'Summit Calibration Lab',
			'isval' => null
		];

		if ($certificates['certid'] === $certid) {
			return $this->response->setJSON([
				'success' => true,
				'message' => 'Certificate has already been validateda'
			]);
		} else {
			return $this->response->setJSON([
				'success' => false,
				'message' => 'Certificate not found'
			]);
		}

		// $validationDate = date('Y-m-d');

		// return $this->response->setJSON([
		// 	'success' => true,
		// 	'message' => 'Certificate validated ' . $certificateType,
		// 	'validationDate' => $validationDate
		// ]);
	}


	// Helper Generate dan Save PDF
	public function generatePdf() {
		$certid = $this->request->getPost('certid');
		$certificateType = $this->request->getPost('certificateType');

		if (!$certid) {
			return $this->response->setJSON([
				'success' => false,
				'message' => 'Certificate ID is required'
			]);
		}

		// Dummy data certificates
		$certificate = [
			'certid' => 'f353ca91-4fc5-49f2-9b9e-304f83d11914',
			'certname' => 'Jokoh Calibration Certificate',
			'productname' => 'Jokoh',
			'productnumber' => 'SN-2024-001',
			'issuedate' => '2024-01-15',
			'expirydate' => '2025-01-15',
			'vendor' => 'Summit Calibration Lab',
			'isval' => null
		];

		if (empty($certificate)) {
			return $this->response->setJSON([
				'success' => false,
				'message' => 'Certificate not found'
			]);
		}

		try {
			$filePath = $this->savePdf($certificate, $certificateType, null);

			if (!$filePath) {
				return $this->response->setJSON([
					'success' => false,
					'message' => 'Failed to generate PDF'
				]);
			}

			$relativePath = str_replace(FCPATH, '', $filePath);

			return $this->response->setJSON([
				'success' => true,
				'message' => 'PDF generated and saved successfully',
				'filePath' => $relativePath
			]);

		} catch (\Exception $e) {
			return $this->response->setJSON([
				'success' => false,
				'message' => 'Failed to generate PDF: ' . $e->getMessage()
			]);
		}
	}
	private function savePdf($certificate, $type, $productType=null) {
		// Generate PDF
		$options = new Options();
		$options->set('isRemoteEnabled', true);
		$options->set('isHtml5ParserEnabled', true);

		$dompdf = new Dompdf($options);

		// Format dates
		$issuedate = date('F d, Y', strtotime($certificate['issuedate']));
		$expirydate = date('F d, Y', strtotime($certificate['expirydate']));

		// Get status
		$today = date('Y-m-d');
		$expiryCheck = date('Y-m-d', strtotime($certificate['expirydate']));
		$daysUntilExpiry = (strtotime($expiryCheck) - strtotime($today)) / (60 * 60 * 24);

		if ($daysUntilExpiry < 0) {
			$status = 'Expired';
			$statusColor = '#dc3545';
		} elseif ($daysUntilExpiry <= 30) {
			$status = 'Expiring Soon';
			$statusColor = '#ffc107';
		} else {
			$status = 'Active';
			$statusColor = '#28a745';
		}

		// Select template and orientation based on type
		$template = 'certificate_pdf';
		$orientation = 'portrait';

		switch($type) {
			case 'training':
				$template = 'certificates/certificate_training';
				$orientation = 'landscape';
				break;
			case 'calibration':
				if ($productType == 'tms50i') {
					$template = 'certificates/callibrations_template/certificate_tms50i_calibration';
				} else if ($productType == 'tms24i') {
					$template = 'certificates/callibrations_template/certificate_tms24i_calibration';
				} else if ($productType == 'tms30i') {
					$template = 'certificates/callibrations_template/certificate_tms30i_calibration';
				} else if ($productType == 'bs430') {
					$template = 'certificates/callibrations_template/certificate_bs430_calibration';
				} else if ($productType == 'cl900i') {
					$template = 'certificates/callibrations_template/certificate_cl900i_calibration';
				} else if ($productType == 'jokoh') {
					$template = 'certificates/callibrations_template/certificate_jokoh_calibration';
				} else if ($productType == 'bc760r') {
					$template = 'certificates/callibrations_template/certificate_bc760r_calibration';
				} else if ($productType == 'bc5140') {
					$template = 'certificates/callibrations_template/certificate_bc5140_calibration';
				} else {
					return $this->response->setStatusCode(404)->setJSON(['error' => 'Not Found']);
				}
				$orientation = 'portrait';
				break;
			case 'maintenance':
				$template = 'certificates/certificate_maintenance';
				$orientation = 'landscape';
				break;
		}

		$html = view($template, [
									'certificate' => $certificate,
									'issuedate' => $issuedate,
									'expirydate' => $expirydate,
									'status' => $status,
									'statusColor' => $statusColor
								]);

		$dompdf->loadHtml($html);
		$dompdf->setPaper('A4', $orientation);
		$dompdf->render();

		// Generate filename with timestamp
		$timestamp = date('YmdHis');
		$filename = 'Certificate_' . $certificate['certid'] . '_' . $timestamp . '.pdf';

		// Ensure upload directory exists
		$uploadDir = FCPATH . 'upload' . DIRECTORY_SEPARATOR . 'documents';
		if (!is_dir($uploadDir)) {
			mkdir($uploadDir, 0755, true);
		}

		// Save PDF to file
		$filePath = $uploadDir . DIRECTORY_SEPARATOR . $filename;
		file_put_contents($filePath, $dompdf->output());

		// Return file path
		return $filePath;
	}

}