<?php

namespace App\Controllers;

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

class Certificates extends BaseController {

	protected array $data;
	
	// Halaman Utama
	public function maintenanceIndex() {
		return view('certificate_maintenance_index');
	}
	public function trainingIndex() {
		return view('certificate_training_index');
	}
	public function calibrateIndex() {
		
		$certificates = [
			// [
			// 	'certid' => 'CERT001',
			// 	'certname' => 'TMS50i Calibration Certificate',
			// 	'productname' => 'tms50i',
			// 	'productnumber' => 'SN-2024-001',
			// 	'type' => 'calibration',
			// 	'issuedate' => '2024-01-15',
			// 	'expirydate' => '2025-01-15',
			// 	'vendor' => 'Summit Calibration Lab',
			// 	'description' => 'Annual calibration certificate for TMS50i equipment.'
			// ],
			// [
			// 	'certid' => 'CERT002',
			// 	'certname' => 'TMS24i Calibration Certificate',
			// 	'productname' => 'tms24i',
			// 	'productnumber' => 'SN-2024-002',
			// 	'type' => 'calibration',
			// 	'issuedate' => '2024-01-16',
			// 	'expirydate' => '2025-01-16',
			// 	'vendor' => 'Summit Calibration Lab',
			// 	'description' => 'Annual calibration certificate for tms24i equipment.'
			// ],
			// [
			// 	'certid' => 'CERT003',
			// 	'certname' => 'tms30i Calibration Certificate',
			// 	'productname' => 'tms30i',
			// 	'productnumber' => 'SN-2024-003',
			// 	'type' => 'calibration',
			// 	'issuedate' => '2024-01-17',
			// 	'expirydate' => '2025-01-17',
			// 	'vendor' => 'Summit Calibration Lab',
			// 	'description' => 'Annual calibration certificate for tms30i equipment.'
			// ],
			// [
			// 	'certid' => 'CERT004',
			// 	'certname' => 'BS430 Calibration Certificate',
			// 	'productname' => 'bs430',
			// 	'productnumber' => 'SN-2024-004',
			// 	'type' => 'calibration',
			// 	'issuedate' => '2024-01-18',
			// 	'expirydate' => '2025-01-18',
			// 	'vendor' => 'Summit Calibration Lab',
			// 	'description' => 'Annual calibration certificate for BS430 equipment.'
			// ],
			// [
			// 	'certid' => 'CERT005',
			// 	'certname' => 'CL900i Calibration Certificate',
			// 	'productname' => 'cl900i',
			// 	'productnumber' => 'SN-2024-005',
			// 	'type' => 'calibration',
			// 	'issuedate' => '2024-01-19',
			// 	'expirydate' => '2025-01-19',
			// 	'vendor' => 'Summit Calibration Lab',
			// 	'description' => 'Annual calibration certificate for CL900i equipment.'
			// ],
			// [
			// 	'certid' => 'CERT006',
			// 	'certname' => 'Jokoh Calibration Certificate',
			// 	'productname' => 'jokoh',
			// 	'productnumber' => 'SN-2024-006',
			// 	'type' => 'calibration',
			// 	'issuedate' => '2024-01-20',
			// 	'expirydate' => '2025-01-20',
			// 	'vendor' => 'Summit Calibration Lab',
			// 	'description' => 'Annual calibration certificate for Jokoh equipment.'
			// ],
			// [
			// 	'certid' => 'CERT007',
			// 	'certname' => 'BC760R Calibration Certificate',
			// 	'productname' => 'bc760r',
			// 	'productnumber' => 'SN-2024-007',
			// 	'type' => 'calibration',
			// 	'issuedate' => '2024-01-21',
			// 	'expirydate' => '2025-01-21',
			// 	'vendor' => 'Summit Calibration Lab',
			// 	'description' => 'Annual calibration certificate for BC760R equipment.'
			// ],
			// [
			// 	'certid' => 'CERT008',
			// 	'certname' => 'BC5140 Calibration Certificate',
			// 	'productname' => 'bc5140',
			// 	'productnumber' => 'SN-2024-008',
			// 	'type' => 'calibration',
			// 	'issuedate' => '2024-01-22',
			// 	'expirydate' => '2025-01-22',
			// 	'vendor' => 'Summit Calibration Lab',
			// 	'description' => 'Annual calibration certificate for BC5140 equipment.'
			// ],
		];

		$data = ['certificates' => $certificates];
		return view('certificate_calibration_index', $data);
	}
	

	// Untuk API Get Data
	public function getDataIndexMaintenance() {
		// $actid = $this->request->getVar('actid');
		
		$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',
				'isval' => null
			],
			[
				'certid' => 'CERT002',
				'certname' => 'Installation Certificate - Sysmex XN',
				'productname' => 'Sysmex',
				'productnumber' => 'XN-1000-5521',
				'issuedate' => '2024-02-10',
				'expirydate' => '2026-02-10',
				'vendor' => 'Global Medika Indonesia',
				'isval' => '2026-03-01'
			],
			[
				'certid' => 'CERT003',
				'certname' => 'Maintenance Certificate Q3',
				'productname' => 'Mindray BC-5380',
				'productnumber' => 'MR-5380-BC88',
				'issuedate' => '2024-03-05',
				'expirydate' => '2024-09-05',
				'vendor' => 'Citra Sehat Teknik',
				'isval' => '2026-03-01'
			],
			[
				'certid' => 'CERT004',
				'certname' => 'User Training - Hematology Analyzer',
				'productname' => 'Beckman Coulter',
				'productnumber' => 'BC-DXH-900',
				'issuedate' => '2024-05-20',
				'expirydate' => '2027-05-20',
				'vendor' => 'Bio-Rad Laboratories',
				'isval' => '2026-03-01'
			],
			[
				'certid' => 'CERT005',
				'certname' => 'Electrical Safety Test',
				'productname' => 'GE Healthcare VIVID',
				'productnumber' => 'GE-VIV-Q992',
				'issuedate' => '2024-06-12',
				'expirydate' => '2026-03-01',
				'vendor' => 'Pramita Medika Service',
				'isval' => '2026-03-01'
			],
			[
				'certid' => 'CERT005',
				'certname' => 'Electrical Safety Test',
				'productname' => 'GE Healthcare VIVID',
				'productnumber' => 'GE-VIV-Q992',
				'issuedate' => '2024-06-12',
				'expirydate' => '2026-03-01',
				'vendor' => 'Pramita Medika Service',
				'isval' => null
			]
		];

		// If actid is provided, return specific certificate
		// if ($actid) {
		// 	$result = null;
		// 	foreach ($certificates as $cert) {
		// 		if ($cert['certid'] === $actid) {
		// 			$result = $cert;
		// 			break;
		// 		}
		// 	}
		// 	return $this->response->setJSON($result);
		// }

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

		return $this->response->setJSON($certificates);
	}
	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 actid is provided, return specific certificate
		// if ($actid) {
		// 	$result = null;
		// 	foreach ($certificates as $cert) {
		// 		if ($cert['certid'] === $actid) {
		// 			$result = $cert;
		// 			break;
		// 		}
		// 	}
		// 	return $this->response->setJSON($result);
		// }

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

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


	public function validateCertificate() {
		$certid = $this->request->getPost('certid');

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

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

		// try {
		// 	$db = \Config\Database::connect();
		// 	$builder = $db->table('certificates');

		// 	$certificate = $builder->where('certid', $certid)->get()->getRowArray();

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

		// 	if ($certificate['isval'] !== null) {
		// 		return $this->response->setJSON([
		// 			'success' => false,
		// 			'message' => 'Certificate has already been validated'
		// 		]);
		// 	}

		// 	$validationDate = date('Y-m-d');
		// 	$builder->where('certid', $certid)->update(['isval' => $validationDate]);

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

		// } catch (\Exception $e) {
		// 	log_message('error', 'Certificate validation error: ' . $e->getMessage());
		// 	return $this->response->setJSON([
		// 		'success' => false,
		// 		'message' => 'An error occurred during validation'
		// 	]);
		// }
	}

	


	

	
	


	public function createTraining($certid = null) {
		if (!$certid) {
			return $this->response->setStatusCode(400)->setJSON(['error' => 'Certificate ID is required']);
		}

		// Get certificate data
		$certificates = [
			[
				'certid' => 'CERT001',
				'certname' => 'Jokoh Training Certificate',
				'productname' => 'Jokoh',
				'productnumber' => 'SN-2024-001',
				'issuedate' => '2024-01-15',
				'expirydate' => '2025-01-15',
				'vendor' => 'Summit Calibration Lab'
			]
		];

		$certificate = null;
		foreach ($certificates as $cert) {
			if ($cert['certid'] === $certid) {
				$certificate = $cert;
				break;
			}
		}

		if (!$certificate) {
			return $this->response->setStatusCode(404)->setJSON(['error' => 'Training certificate not found']);
		}

		// Generate PDF
		return $this->generatePDF($certificate, 'training');
	}
	public function createCalibrate($certid = null, $productname = null) {
		if (!$certid) {
			return $this->response->setStatusCode(400)->setJSON(['error' => 'Certificate ID is required']);
		}

		// Get certificate data
		$certificates = [
			[
				'certid' => 'CERT001',
				'certname' => 'TMS50i Calibration Certificate',
				'productname' => 'tms50i',
				'productnumber' => 'SN-2024-001',
				'type' => 'calibration',
				'issuedate' => '2024-01-15',
				'expirydate' => '2025-01-15',
				'vendor' => 'Summit Calibration Lab',
				'description' => 'Annual calibration certificate for TMS50i equipment.'
			],
			[
				'certid' => 'CERT002',
				'certname' => 'tms24i Calibration Certificate',
				'productname' => 'tms24i',
				'productnumber' => 'SN-2024-002',
				'type' => 'calibration',
				'issuedate' => '2024-01-16',
				'expirydate' => '2025-01-16',
				'vendor' => 'Summit Calibration Lab',
				'description' => 'Annual calibration certificate for tms24i equipment.'
			],
			[
				'certid' => 'CERT003',
				'certname' => 'tms30i Calibration Certificate',
				'productname' => 'tms30i',
				'productnumber' => 'SN-2024-003',
				'type' => 'calibration',
				'issuedate' => '2024-01-17',
				'expirydate' => '2025-01-17',
				'vendor' => 'Summit Calibration Lab',
				'description' => 'Annual calibration certificate for tms30i equipment.'
			],
			[
				'certid' => 'CERT004',
				'certname' => 'BS430 Calibration Certificate',
				'productname' => 'bs430',
				'productnumber' => 'SN-2024-004',
				'type' => 'calibration',
				'issuedate' => '2024-01-18',
				'expirydate' => '2025-01-18',
				'vendor' => 'Summit Calibration Lab',
				'description' => 'Annual calibration certificate for BS430 equipment.'
			],
			[
				'certid' => 'CERT005',
				'certname' => 'CL900i Calibration Certificate',
				'productname' => 'cl900i',
				'productnumber' => 'SN-2024-005',
				'type' => 'calibration',
				'issuedate' => '2024-01-19',
				'expirydate' => '2025-01-19',
				'vendor' => 'Summit Calibration Lab',
				'description' => 'Annual calibration certificate for CL900i equipment.'
			],
			[
				'certid' => 'CERT006',
				'certname' => 'Jokoh Calibration Certificate',
				'productname' => 'jokoh',
				'productnumber' => 'SN-2024-006',
				'type' => 'calibration',
				'issuedate' => '2024-01-20',
				'expirydate' => '2025-01-20',
				'vendor' => 'Summit Calibration Lab',
				'description' => 'Annual calibration certificate for Jokoh equipment.'
			],
			[
				'certid' => 'CERT007',
				'certname' => 'BC760R Calibration Certificate',
				'productname' => 'bc760r',
				'productnumber' => 'SN-2024-007',
				'type' => 'calibration',
				'issuedate' => '2024-01-21',
				'expirydate' => '2025-01-21',
				'vendor' => 'Summit Calibration Lab',
				'description' => 'Annual calibration certificate for BC760R equipment.'
			],
			[
				'certid' => 'CERT008',
				'certname' => 'BC5140 Calibration Certificate',
				'productname' => 'bc5140',
				'productnumber' => 'SN-2024-008',
				'type' => 'calibration',
				'issuedate' => '2024-01-22',
				'expirydate' => '2025-01-22',
				'vendor' => 'Summit Calibration Lab',
				'description' => 'Annual calibration certificate for BC5140 equipment.'
			],
		];

		$certificate = null;
		foreach ($certificates as $cert) {
			if ($cert['certid'] === $certid) {
				$certificate = $cert;
				break;
			}
		}

		if (!$certificate) {
			return $this->response->setStatusCode(404)->setJSON(['error' => 'Calibration certificate not found']);
		}

		// Generate PDF
		return $this->generatePDF($certificate, 'calibration', $productname);
	}
 	public function createMaintenance($certid = null) {
		if (!$certid) {
			return $this->response->setStatusCode(400)->setJSON(['error' => 'Certificate ID is required']);
		}

		// Get certificate data
		$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'
			]
		];

		$certificate = null;
		foreach ($certificates as $cert) {
			if ($cert['certid'] === $certid) {
				$certificate = $cert;
				break;
			}
		}

		if (!$certificate) {
			return $this->response->setStatusCode(404)->setJSON(['error' => 'Maintenance certificate not found']);
		}

		// dd($certificate);

		// Generate PDF
		return $this->generatePDF($certificate, 'maintenance');
	}

	// Digunakan Untuk Generate PDF Show
	private function generatePDF($certificate, $type, $productType=null) {
		// 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]);
	}
}