<?php
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
	session_start();
}

// Enable error reporting for development
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors on page
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');

require_once('../includes/admin-security.php');
include_once('includes/config.php');

// Access Check
if (!has_permission('manage_products')) {
	echo "<script>alert('Access Denied. Redirecting to Dashboard...'); window.location.href='dashboard.php';</script>";
	exit();
}

// Handle product deletion
if (isset($_GET['del'])) {
	if (!has_permission('manage_products')) {
		$_SESSION['error'] = "You do not have permission to delete products.";
		header('location: manage-products.php');
		exit();
	}
	$productId = intval($_GET['id']);

	// Delete product images directory from disk
	$dirPath = "productimages/" . $productId;
	if (is_dir($dirPath)) {
		$files = glob($dirPath . '/*');
		foreach ($files as $file) {
			if (is_file($file)) {
				unlink($file);
			}
		}
		rmdir($dirPath);
	}

	mysqli_query($con, "DELETE FROM products WHERE id = $productId");
	$_SESSION['delmsg'] = "Product deleted successfully!";
	header('location: manage-products.php');
	exit();
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="utf-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
	<title>Manage Products - Professional Admin</title>
	<link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" />
	<link href="css/styles.css?v=4.0" rel="stylesheet" />
	<link href="css/admin-professional.css?v=4.0" rel="stylesheet" />
	<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"
		crossorigin="anonymous"></script>
</head>

<body class="sb-nav-fixed">
	<?php include_once('includes/header.php'); ?>

	<div id="layoutSidenav">
		<?php include_once('includes/sidebar.php'); ?>

		<div id="layoutSidenav_content">
			<main>
				<div class="container-fluid px-4">
					<!-- Page Header -->
					<div class="page-header mt-4">
						<div>
							<h1><i class="fas fa-box me-2"></i> Manage Products</h1>
							<p>View and manage all products in your store</p>
						</div>
						<a href="insert-product.php" class="btn btn-primary">
							<i class="fas fa-plus me-2"></i> Add New Product
						</a>
					</div>

					<!-- Success Message -->
					<?php if (isset($_SESSION['delmsg'])) { ?>
						<div class="alert alert-success">
							<i class="fas fa-check-circle me-2"></i>
							<?php echo htmlentities($_SESSION['delmsg']); ?>
							<?php $_SESSION['delmsg'] = ""; ?>
						</div>
					<?php } ?>

					<!-- Products Table -->
					<div class="table-card">
						<table class="table table-hover" id="datatablesSimple">
							<thead>
								<tr>
									<th width="5%">#</th>
									<th>Product Name</th>
									<th>Category</th>
									<th>Subcategory</th>
									<th>Company</th>
									<th>Created</th>
									<th width="12%">Actions</th>
								</tr>
							</thead>
							<tbody>
								<?php
								$query = mysqli_query($con, "SELECT products.*, category.categoryName, subcategory.subcategory 
                                                              FROM products 
                                                              JOIN category ON category.id = products.category 
                                                              JOIN subcategory ON subcategory.id = products.subCategory 
                                                              ORDER BY products.id DESC");
								$cnt = 1;
								while ($row = mysqli_fetch_array($query)) {
									// Image path with fallback
									$imagePath = "productimages/" . $row['id'] . "/" . $row['productImage1'];
									$imageExists = !empty($row['productImage1']) && file_exists($imagePath);
									?>
									<tr>
										<td><?php echo $cnt; ?></td>
										<td>
											<div class="d-flex align-items-center">
												<div class="product-thumb me-3"
													style="width: 40px; height: 40px; flex-shrink: 0;">
													<?php if ($imageExists) { ?>
														<img src="<?php echo $imagePath; ?>" class="rounded border"
															style="width: 100%; height: 100%; object-fit: cover;">
													<?php } else { ?>
														<div
															class="bg-light rounded border d-flex align-items-center justify-content-center w-100 h-100">
															<i class="fas fa-image text-muted opacity-50 small"></i>
														</div>
													<?php } ?>
												</div>
												<div>
													<div class="fw-bold text-dark">
														<?php echo htmlentities($row['productName']); ?></div>
													<small class="text-muted">ID: <?php echo $row['id']; ?></small>
												</div>
											</div>
										</td>
										<td><?php echo htmlentities($row['categoryName']); ?></td>
										<td><?php echo htmlentities($row['subcategory']); ?></td>
										<td><span
												class="badge bg-light text-dark border fw-normal"><?php echo htmlentities($row['productCompany']); ?></span>
										</td>
										<td><small
												class="text-muted"><?php echo date('M d, Y', strtotime($row['postingDate'])); ?></small>
										</td>
										<td>
											<div class="d-flex gap-2">
												<a href="edit-product.php?id=<?php echo $row['id']; ?>"
													class="btn btn-sm btn-outline-primary" title="Edit Product">
													<i class="fas fa-edit"></i>
												</a>
												<a href="manage-products.php?id=<?php echo $row['id']; ?>&del=delete"
													class="btn btn-sm btn-outline-danger" title="Delete Product"
													onclick="return confirm('Are you sure you want to delete this product?')">
													<i class="fas fa-trash"></i>
												</a>
											</div>
										</td>
									</tr>
									<?php $cnt++;
								} ?>
							</tbody>
						</table>
					</div>
				</div>
			</main>
			<?php include_once('includes/footer.php'); ?>
		</div>
	</div>

	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
		crossorigin="anonymous"></script>
	<script src="js/scripts.js"></script>
	<script src="https://cdn.jsdelivr.net/npm/simple-datatables@latest" crossorigin="anonymous"></script>
	<script src="js/datatables-simple-demo.js"></script>
</body>

</html>