<?php
require_once __DIR__ . '/admin_header.php';

// Handle deletion
$msg = '';
$msg_type = 'success';

if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    $prod_id = intval($_GET['id']);
    try {
        // Fetch image filename to delete from disk
        $stmt_img = $pdo->prepare("SELECT image FROM products WHERE id = ?");
        $stmt_img->execute([$prod_id]);
        $img_name = $stmt_img->fetchColumn();

        $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
        $stmt->execute([$prod_id]);

        // Delete custom image
        if (!empty($img_name) && file_exists(__DIR__ . '/../assets/images/' . $img_name) && strpos($img_name, 'prod_') !== false) {
            @unlink(__DIR__ . '/../assets/images/' . $img_name);
        }

        $msg = 'Product removed from collection successfully.';
    } catch (Exception $e) {
        $msg = 'Failed to delete product: ' . $e->getMessage();
        $msg_type = 'danger';
    }
}

// Fetch search queries if any
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$where_clause = '';
$params = [];

if (!empty($search)) {
    $where_clause = " WHERE p.name LIKE ? OR p.description LIKE ? OR c.name LIKE ? ";
    $params = ["%$search%", "%$search%", "%$search%"];
}

// Fetch all products
try {
    $stmt = $pdo->prepare("SELECT p.*, c.name as category_name FROM products p LEFT JOIN categories c ON p.category_id = c.id " . $where_clause . " ORDER BY p.id DESC");
    $stmt->execute($params);
    $products = $stmt->fetchAll();
} catch (Exception $e) {
    $products = [];
}
?>

<div class="d-flex flex-column flex-sm-row justify-content-between align-items-start align-items-sm-center gap-3 mb-4">
    <div>
        <h2 class="text-white mb-1">Catalog Boutique Products</h2>
        <p class="text-muted small">Update inventories, pricing catalogs, and spotlight featured products.</p>
    </div>
    <a href="product_add.php" class="btn-luxury">
        <i class="fa-solid fa-plus-circle me-1"></i> Add Product
    </a>
</div>

<?php if (!empty($msg)): ?>
    <div class="alert alert-<?php echo $msg_type; ?> border-<?php echo $msg_type; ?> bg-dark text-<?php echo $msg_type; ?> alert-dismissible fade show rounded-3 mb-4" role="alert">
        <i class="fa-solid <?php echo ($msg_type === 'success') ? 'fa-circle-check' : 'fa-circle-exclamation'; ?> me-2"></i> <?php echo htmlspecialchars($msg); ?>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<!-- Search bar card -->
<div class="admin-card mb-4 py-3">
    <form action="products.php" method="GET" class="row g-2 align-items-center">
        <div class="col-sm-9 col-md-10">
            <div class="input-group">
                <span class="input-group-text bg-dark border-secondary text-muted"><i class="fa-solid fa-magnifying-glass"></i></span>
                <input type="text" class="form-control" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="Search by product name, description, or category...">
            </div>
        </div>
        <div class="col-sm-3 col-md-2 d-flex gap-2">
            <button type="submit" class="btn btn-warning w-100 rounded-pill text-uppercase tracking-wider fw-bold text-black border-warning" style="font-size: 0.75rem;">Search</button>
            <?php if (!empty($search)): ?>
                <a href="products.php" class="btn btn-outline-secondary rounded-circle" title="Clear Search"><i class="fa-solid fa-xmark"></i></a>
            <?php endif; ?>
        </div>
    </form>
</div>

<div class="admin-card">
    <?php if (empty($products)): ?>
        <div class="text-center py-5 text-muted">
            <i class="fa-solid fa-boxes-stacked display-4 mb-3 d-block opacity-25"></i>
            No products match the criteria. Introduce some luxury couture to display!
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-dark table-luxury align-middle m-0">
                <thead>
                    <tr>
                        <th style="width: 70px;">Item</th>
                        <th>Product Details</th>
                        <th>Classification</th>
                        <th>Boutique Price</th>
                        <th class="text-center">Inventory</th>
                        <th class="text-center">Spotlight</th>
                        <th class="text-end" style="width: 180px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($products as $prod): ?>
                        <tr>
                            <td>
                                <?php if (!empty($prod['image'])): ?>
                                    <img src="../assets/images/<?php echo htmlspecialchars($prod['image']); ?>" alt="Product" class="rounded" style="width: 45px; height: 55px; object-fit: cover; border: 1px solid var(--border-gray);">
                                <?php else: ?>
                                    <div class="rounded d-flex align-items-center justify-content-center bg-dark text-muted" style="width: 45px; height: 55px; border: 1px solid var(--border-gray);">
                                        <i class="fa-solid fa-image"></i>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="fw-bold text-white"><?php echo htmlspecialchars($prod['name']); ?></div>
                                <div class="text-muted small text-truncate" style="max-width: 250px;"><?php echo htmlspecialchars(strip_tags($prod['description'])); ?></div>
                            </td>
                            <td>
                                <span class="badge bg-dark border border-secondary text-white py-1 px-2 rounded">
                                    <i class="fa-solid fa-tag me-1 text-warning" style="font-size: 0.65rem;"></i> <?php echo htmlspecialchars($prod['category_name'] ?? 'Uncategorized'); ?>
                                </span>
                            </td>
                            <td class="fw-bold text-warning">LKR <?php echo number_format($prod['price'], 2); ?></td>
                            <td class="text-center">
                                <?php if ($prod['stock'] > 5): ?>
                                    <span class="badge bg-success py-2 px-3 rounded-pill"><?php echo $prod['stock']; ?> In Stock</span>
                                <?php elseif ($prod['stock'] > 0): ?>
                                    <span class="badge bg-warning text-black py-2 px-3 rounded-pill"><?php echo $prod['stock']; ?> Low Inventory</span>
                                <?php else: ?>
                                    <span class="badge bg-danger py-2 px-3 rounded-pill">Sold Out</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-center">
                                <?php if ($prod['is_featured'] == 1): ?>
                                    <span class="badge bg-dark border border-warning text-warning py-1 px-3 rounded-pill"><i class="fa-solid fa-star me-1"></i> Featured</span>
                                <?php else: ?>
                                    <span class="text-muted small">&mdash;</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-end">
                                <div class="d-flex justify-content-end gap-2">
                                    <a href="product_edit.php?id=<?php echo $prod['id']; ?>" class="btn btn-outline-warning btn-sm rounded-pill px-3" title="Edit Product">
                                        <i class="fa-solid fa-pen-to-square me-1"></i> Edit
                                    </a>
                                    <a href="products.php?action=delete&id=<?php echo $prod['id']; ?>" class="btn btn-outline-danger btn-sm rounded-pill px-3" onclick="return confirm('Are you sure you want to permanently delete product \'<?php echo addslashes($prod['name']); ?>\'?')" title="Delete Product">
                                        <i class="fa-solid fa-trash-can me-1"></i> Delete
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<?php
require_once __DIR__ . '/admin_footer.php';
?>
