<?= $this->extend('layouts/main.php') ?>

<?= $this->section('content') ?>

<div class="page-wrapper">
	<div class="container-fluid">
		<div class="row page-titles">
			<div class="col-md-5 align-self-center">
				<h4 class="text-themecolor">Certificates Maintenance Management</h4>
			</div>
			<div class="col-md-7 align-self-center text-end">
				<button type="button" class="btn btn-info text-white btn-sm" data-bs-toggle="modal" data-bs-target="#createModal">
					<i class="fas fa-plus-circle"></i> Create
				</button>
			</div>
		</div>

		<div class="row">
			<div class="col-12">
				<div class="card">
					<div class="card-body">
						<div class="row mb-3">
							<div class="col-12 mb-3">
								<div class="input-group input-group-sm">
									<span class="input-group-text"><i class="fas fa-search"></i></span>
									<input type="text" id="searchInput" class="form-control" placeholder="Search certificates by name, product, type, vendor, or dates...">
								</div>
							</div>
							<div class="col-md-4 mb-2">
								<select id="statusFilter" class="form-select form-select-sm">
									<option value="">All Status</option>
									<option value="active">Active</option>
									<option value="expired">Expired</option>
									<option value="expiring">Expiring Soon</option>
								</select>
							</div>
							<div class="col-md-4 mb-2">
								<select id="typeFilter" class="form-select form-select-sm">
									<option value="">All Types</option>
									<option value="calibration">Calibration</option>
									<option value="training">Training</option>
									<option value="maintenance">Maintenance</option>
								</select>
							</div>
							<div class="col-md-4 mb-2">
								<button onclick="resetFilters()" class="btn btn-secondary btn-sm w-100">
									<i class="fas fa-redo"></i> Reset Filters
								</button>
							</div>
						</div>

						<div class="table-responsive">
							<table id="certificatesTable" class="table table-striped table-hover border">
								<thead class="table-primary">
									<tr>
										<th class="text-center" style="width: 5%;">No</th>
										<th style="width: 15%;">Certificate Name</th>
										<th style="width: 15%;">Product/Equipment</th>
										<th style="width: 12%;">Type</th>
										<th style="width: 12%;">Issue Date</th>
										<th style="width: 12%;">Expiry Date</th>
										<th style="width: 10%;">Status</th>
										<th style="width: 10%;">Vendor</th>
										<th class="text-center" style="width: 9%;">Action</th>
									</tr>
								</thead>
								<tbody>
									<?php 
									if(isset($certificates) && !empty($certificates)) {
										$no = 1;
										foreach($certificates as $cert) {
											$certid = $cert['certid'] ?? '';
											$certname = $cert['certname'] ?? '-';
											$productname = $cert['productname'] ?? '-';
											$productnumber = $cert['productnumber'] ?? '';
											$type = $cert['type'] ?? '-';
											$issuedate = $cert['issuedate'] ?? '';
											$expirydate = $cert['expirydate'] ?? '';
											$vendor = $cert['vendor'] ?? '-';
											
											// Format dates
											if($issuedate && $issuedate != '0000-00-00') {
												$issuedate = date('M d, Y', strtotime($issuedate));
											} else {
												$issuedate = '-';
											}
											
											if($expirydate && $expirydate != '0000-00-00') {
												$expirydate = date('M d, Y', strtotime($expirydate));
												// Check expiry status
												$today = date('Y-m-d');
												$expiryCheck = date('Y-m-d', strtotime($cert['expirydate']));
												$daysUntilExpiry = (strtotime($expiryCheck) - strtotime($today)) / (60 * 60 * 24);
												
												if($daysUntilExpiry < 0) {
													$statusBadge = '<span class="badge bg-danger">Expired</span>';
													$statusClass = 'expired';
												} elseif($daysUntilExpiry <= 30) {
													$statusBadge = '<span class="badge bg-warning text-dark">Expiring Soon</span>';
													$statusClass = 'expiring';
												} else {
													$statusBadge = '<span class="badge bg-success">Active</span>';
													$statusClass = 'active';
												}
											} else {
												$expirydate = '-';
												$statusBadge = '<span class="badge bg-secondary">N/A</span>';
												$statusClass = '';
											}
											
											// Type badge
											$typeBadge = '';
											switch(strtolower($type)) {
												case 'calibration':
													$typeBadge = '<span class="badge bg-info">Calibration</span>';
													break;
												case 'training':
													$typeBadge = '<span class="badge bg-primary">Training</span>';
													break;
												case 'maintenance':
													$typeBadge = '<span class="badge bg-warning text-dark">Maintenance</span>';
													break;
												default:
													$typeBadge = '<span class="badge bg-secondary">' . htmlspecialchars($type) . '</span>';
											}
									?>
									<tr>
										<td class="text-center"><?= $no++; ?></td>
										<td>
											<strong><?= htmlspecialchars($certname) ?></strong>
											<br>
											<small class="text-muted">ID: <?= $certid ?></small>
										</td>
										<td>
											<?= htmlspecialchars($productname) ?>
											<?php if($productnumber): ?>
												<br><small class="text-muted">SN: <?= htmlspecialchars($productnumber) ?></small>
											<?php endif; ?>
										</td>
										<td><?= $typeBadge ?></td>
										<td><?= $issuedate ?></td>
										<td><?= $expirydate ?></td>
										<td><?= $statusBadge ?></td>
										<td><?= htmlspecialchars($vendor) ?></td>
										<td class="text-center">
											<div class="btn-group btn-group-sm">
												<button type="button" class="btn btn-success btn-view" data-certid="<?= $certid ?>" data-certtype="<?= $type ?>" title="View PDF">
													<i class="fas fa-file-pdf"></i>
												</button>
												<button type="button" class="btn btn-warning btn-edit" data-certid="<?= $certid ?>" title="Edit">
													<i class="fas fa-edit"></i>
												</button>
												<button type="button" class="btn btn-danger btn-delete" data-certid="<?= $certid ?>" data-certname="<?= htmlspecialchars($certname) ?>" title="Delete">
													<i class="fas fa-trash"></i>
												</button>
											</div>
										</td>
									</tr>
									<?php 
										}
									} else {
									?>
									<tr>
										<td colspan="9" class="text-center py-5">
											<i class="fas fa-certificate fa-3x text-muted mb-3"></i>
											<p class="text-muted">No certificates found</p>
											<button type="button" class="btn btn-info text-white btn-sm" data-bs-toggle="modal" data-bs-target="#createModal">
												<i class="fas fa-plus-circle"></i> Add First Certificate
											</button>
										</td>
									</tr>
									<?php } ?>
								</tbody>
							</table>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>

<!-- Create Modal -->
<div class="modal fade" id="createModal" tabindex="-1" aria-labelledby="createModalLabel" aria-hidden="true">
	<div class="modal-dialog modal-lg modal-dialog-centered">
		<div class="modal-content">
			<div class="modal-header bg-info text-white">
				<h5 class="modal-title" id="createModalLabel">
					<i class="fas fa-plus-circle"></i> Create New Certificate
				</h5>
				<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
			<form id="createForm" action="<?= base_url('certificates/create') ?>" method="post">
				<div class="modal-body">
					<div class="row">
						<div class="col-md-6 mb-3">
							<label for="certname" class="form-label">Certificate Name <span class="text-danger">*</span></label>
							<input type="text" class="form-control" id="certname" name="certname" required>
						</div>
						<div class="col-md-6 mb-3">
							<label for="type" class="form-label">Type <span class="text-danger">*</span></label>
							<select class="form-select" id="type" name="type" required>
								<option value="">Select Type</option>
								<option value="calibration">Calibration</option>
								<option value="training">Training</option>
								<option value="maintenance">Maintenance</option>
							</select>
						</div>
					</div>
					<div class="row">
						<div class="col-md-6 mb-3">
							<label for="productid" class="form-label">Product/Equipment</label>
							<select class="form-select select2" id="productid" name="productid">
								<option value="">Select Product</option>
								<?php if(isset($products)): ?>
									<?php foreach($products as $product): ?>
										<option value="<?= $product['productid'] ?>">
											<?= htmlspecialchars($product['productname']) ?>
											<?php if($product['productnumber']): ?>
												(SN: <?= htmlspecialchars($product['productnumber']) ?>)
											<?php endif; ?>
										</option>
									<?php endforeach; ?>
								<?php endif; ?>
							</select>
						</div>
						<div class="col-md-6 mb-3">
							<label for="vendor" class="form-label">Vendor/Provider</label>
							<input type="text" class="form-control" id="vendor" name="vendor">
						</div>
					</div>
					<div class="row">
						<div class="col-md-6 mb-3">
							<label for="issuedate" class="form-label">Issue Date</label>
							<input type="date" class="form-control" id="issuedate" name="issuedate">
						</div>
						<div class="col-md-6 mb-3">
							<label for="expirydate" class="form-label">Expiry Date</label>
							<input type="date" class="form-control" id="expirydate" name="expirydate">
						</div>
					</div>
					<div class="mb-3">
						<label for="description" class="form-label">Description</label>
						<textarea class="form-control" id="description" name="description" rows="3"></textarea>
					</div>
					<div class="mb-3">
						<label for="attachment" class="form-label">Attachment</label>
						<input type="file" class="form-control" id="attachment" name="attachment" accept=".pdf,.jpg,.jpeg,.png">
						<small class="text-muted">Allowed: PDF, JPG, PNG (Max 5MB)</small>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
						<i class="fas fa-times"></i> Cancel
					</button>
					<button type="submit" class="btn btn-info text-white">
						<i class="fas fa-save"></i> Save
					</button>
				</div>
			</form>
		</div>
	</div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
	<div class="modal-dialog modal-lg modal-dialog-centered">
		<div class="modal-content">
			<div class="modal-header bg-warning text-dark">
				<h5 class="modal-title" id="editModalLabel">
					<i class="fas fa-edit"></i> Edit Certificate
				</h5>
				<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
			<form id="editForm" action="<?= base_url('certificates/update') ?>" method="post">
				<input type="hidden" id="edit_certid" name="certid">
				<div class="modal-body">
					<div class="row">
						<div class="col-md-6 mb-3">
							<label for="edit_certname" class="form-label">Certificate Name <span class="text-danger">*</span></label>
							<input type="text" class="form-control" id="edit_certname" name="certname" required>
						</div>
						<div class="col-md-6 mb-3">
							<label for="edit_type" class="form-label">Type <span class="text-danger">*</span></label>
							<select class="form-select" id="edit_type" name="type" required>
								<option value="">Select Type</option>
								<option value="calibration">Calibration</option>
								<option value="training">Training</option>
								<option value="maintenance">Maintenance</option>
							</select>
						</div>
					</div>
					<div class="row">
						<div class="col-md-6 mb-3">
							<label for="edit_productid" class="form-label">Product/Equipment</label>
							<select class="form-select select2" id="edit_productid" name="productid">
								<option value="">Select Product</option>
								<?php if(isset($products)): ?>
									<?php foreach($products as $product): ?>
										<option value="<?= $product['productid'] ?>">
											<?= htmlspecialchars($product['productname']) ?>
											<?php if($product['productnumber']): ?>
												(SN: <?= htmlspecialchars($product['productnumber']) ?>)
											<?php endif; ?>
										</option>
									<?php endforeach; ?>
								<?php endif; ?>
							</select>
						</div>
						<div class="col-md-6 mb-3">
							<label for="edit_vendor" class="form-label">Vendor/Provider</label>
							<input type="text" class="form-control" id="edit_vendor" name="vendor">
						</div>
					</div>
					<div class="row">
						<div class="col-md-6 mb-3">
							<label for="edit_issuedate" class="form-label">Issue Date</label>
							<input type="date" class="form-control" id="edit_issuedate" name="issuedate">
						</div>
						<div class="col-md-6 mb-3">
							<label for="edit_expirydate" class="form-label">Expiry Date</label>
							<input type="date" class="form-control" id="edit_expirydate" name="expirydate">
						</div>
					</div>
					<div class="mb-3">
						<label for="edit_description" class="form-label">Description</label>
						<textarea class="form-control" id="edit_description" name="description" rows="3"></textarea>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
						<i class="fas fa-times"></i> Cancel
					</button>
					<button type="submit" class="btn btn-warning text-dark">
						<i class="fas fa-save"></i> Update
					</button>
				</div>
			</form>
		</div>
	</div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
	<div class="modal-dialog modal-dialog-centered">
		<div class="modal-content">
			<div class="modal-header bg-danger text-white">
				<h5 class="modal-title" id="deleteModalLabel">
					<i class="fas fa-exclamation-triangle"></i> Confirm Delete
				</h5>
				<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
			<div class="modal-body">
				<p>Are you sure you want to delete this certificate?</p>
				<div class="alert alert-warning">
					<strong>Certificate:</strong> <span id="deleteCertName"></span>
				</div>
				<p class="text-muted small">This action cannot be undone.</p>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
					<i class="fas fa-times"></i> Cancel
				</button>
				<form id="deleteForm" action="<?= base_url('certificates/delete') ?>" method="post">
					<input type="hidden" id="delete_certid" name="certid">
					<button type="submit" class="btn btn-danger text-white">
						<i class="fas fa-trash"></i> Delete
					</button>
				</form>
			</div>
		</div>
	</div>
</div>

<?= $this->endSection() ?>

<?= $this->section('script') ?>
<script>
$(function () {
	// Store DataTable instance
	var table = null;

	// Initialize DataTable
	table = $('#certificatesTable').DataTable({
		"order": [[0, "asc"]],
		"pageLength": 25,
		"lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
		"language": {
			"emptyTable": "No certificates available",
			"info": "Showing _START_ to _END_ of _TOTAL_ certificates",
			"infoEmpty": "No certificates found",
			"infoFiltered": "(filtered from _MAX_ total certificates)"
		},
		"dom": '<"row"<"col-md-6"l>>rtip',
		"columnDefs": [
			{ "orderable": false, "targets": [8] }, // Disable sorting on Action column
			{ "searchable": true, "targets": [0, 1, 2, 3, 4, 5, 6, 7] } // Enable search on all columns except Action
		]
	});

	// Hide default DataTables search
	$('#certificatesTable_filter').hide();

	// Initialize Select2
	$('.select2').select2({
		theme: 'bootstrap-5',
		width: '100%',
		dropdownParent: $('.modal')
	});

	// Custom search functionality
	$('#searchInput').on('keyup', function() {
		var searchValue = $(this).val().toLowerCase();
		table.search(searchValue).draw();
	});

	// Status filter using DataTables column filter
	$('#statusFilter').on('change', function() {
		var status = $(this).val();
		
		// Filter by status column (index 6)
		if(status === '') {
			table.column(6).search('').draw();
		} else {
			// Search for the badge text in status column
			var statusText = '';
			switch(status) {
				case 'active':
					statusText = 'Active';
					break;
				case 'expired':
					statusText = 'Expired';
					break;
				case 'expiring':
					statusText = 'Expiring Soon';
					break;
			}
			table.column(6).search(statusText).draw();
		}
	});

	// Type filter using DataTables column filter
	$('#typeFilter').on('change', function() {
		var type = $(this).val();
		
		// Filter by type column (index 3)
		if(type === '') {
			table.column(3).search('').draw();
		} else {
			// Capitalize first letter for search
			var typeText = type.charAt(0).toUpperCase() + type.slice(1);
			table.column(3).search(typeText).draw();
		}
	});

	// Reset filters
	window.resetFilters = function() {
		$('#searchInput').val('');
		$('#statusFilter').val('');
		$('#typeFilter').val('');
		
		// Reset DataTables search and filters
		table.search('').columns().search('').draw();
		
		// Re-apply default ordering
		table.order([5, 'asc']).draw();
	};

	// View button click - Open PDF in new tab based on certificate type
	$(document).on('click', '.btn-view', function() {
		var certid = $(this).data('certid');
		var certType = $(this).data('certtype');

		var url = '';
		switch(certType) {
			case 'training':
				url = '<?= base_url('certificates/training') ?>/' + certid;
				break;
			case 'calibration':
				url = '<?= base_url('certificates/calibrate') ?>/' + certid;
				break;
			case 'maintenance':
				url = '<?= base_url('certificates/maintenance') ?>/' + certid;
				break;
			default:
				url = '<?= base_url('certificates/view') ?>/' + certid;
		}

		window.open(url, '_blank');
	});

	// Edit button click
	$(document).on('click', '.btn-edit', function() {
		var certid = $(this).data('certid');
		$('#edit_certid').val(certid);
		$('#editModal').modal('show');
		
		// Load certificate data via AJAX
		$.get('<?= base_url('certificates/get') ?>/' + certid, function(data) {
			$('#edit_certname').val(data.certname);
			$('#edit_type').val(data.type);
			$('#edit_productid').val(data.productid).trigger('change');
			$('#edit_vendor').val(data.vendor);
			$('#edit_issuedate').val(data.issuedate);
			$('#edit_expirydate').val(data.expirydate);
			$('#edit_description').val(data.description);
		}).fail(function() {
			$('#editModal').modal('hide');
			alert('Failed to load certificate data.');
		});
	});

	// Delete button click
	$(document).on('click', '.btn-delete', function() {
		var certid = $(this).data('certid');
		var certname = $(this).data('certname');
		$('#delete_certid').val(certid);
		$('#deleteCertName').text(certname);
		$('#deleteModal').modal('show');
	});

	// Form validation
	$('#createForm, #editForm').on('submit', function(e) {
		var form = this;
		if(form.checkValidity()) {
			// Form is valid, submit
			return true;
		}
		e.preventDefault();
		e.stopPropagation();
		form.classList.add('was-validated');
	});

	// Date picker enhancement
	$('input[type="date"]').on('focus', function() {
		this.showPicker();
	});

	// Re-attach event handlers after DataTables pagination/draw
	table.on('draw.dt', function() {
		// Event handlers are already attached using $(document).on(), so no need to re-attach
	});
});
</script>
<?= $this->endSection() ?>
