<?php
session_start();
require_once __DIR__ . '/../includes/config.php';
requireAdminLogin();

$adminPageTitle = 'All Products';
$db = getDB();

$search = trim($_GET['search'] ?? '');
$statusFilter = trim($_GET['status'] ?? '');

$sql = "SELECT p.*, (SELECT image_path FROM product_images WHERE product_id = p.id ORDER BY sort_order LIMIT 1) AS main_image,
               (SELECT COUNT(*) FROM product_images WHERE product_id = p.id) AS img_count
        FROM products p WHERE 1=1";
$params = [];
if ($search) { $sql .= " AND (p.name LIKE ? OR p.description LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; }
if ($statusFilter) { $sql .= " AND p.selling_status = ?"; $params[] = $statusFilter; }
$sql .= " ORDER BY p.created_at DESC";
$stmt = $db->prepare($sql);
$stmt->execute($params);
$products = $stmt->fetchAll();

// Flash message
$flash = $_SESSION['flash'] ?? '';
unset($_SESSION['flash']);

include __DIR__ . '/partials/admin_header.php';
?>

<?php if ($flash): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
    <i class="fas fa-check-circle me-2"></i><?= sanitize($flash) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Toolbar -->
<div class="d-flex align-items-center justify-content-between mb-4 flex-wrap gap-3">
    <form class="d-flex gap-2 flex-wrap" action="" method="GET">
        <input type="text" name="search" class="form-control" style="max-width:220px;" placeholder="Search products..." value="<?= sanitize($search) ?>">
        <select name="status" class="form-select" style="max-width:160px;">
            <option value="">All Status</option>
            <option value="available" <?= $statusFilter === 'available' ? 'selected' : '' ?>>Available</option>
            <option value="out_of_stock" <?= $statusFilter === 'out_of_stock' ? 'selected' : '' ?>>Out of Stock</option>
            <option value="coming_soon" <?= $statusFilter === 'coming_soon' ? 'selected' : '' ?>>Coming Soon</option>
        </select>
        <button type="submit" class="btn btn-primary">Filter</button>
        <?php if ($search || $statusFilter): ?><a href="<?= SITE_URL ?>/admin/products.php" class="btn btn-outline-secondary">Clear</a><?php endif; ?>
    </form>
    <a href="<?= SITE_URL ?>/admin/product_add.php" class="btn btn-success">
        <i class="fas fa-plus me-2"></i>Add New Product
    </a>
</div>

<div class="table-card">
    <div class="card-header">
        <i class="fas fa-boxes me-2 text-primary"></i>Products <span class="badge bg-secondary ms-2"><?= count($products) ?></span>
    </div>
    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0">
            <thead class="table-light">
                <tr>
                    <th>Image</th>
                    <th>Name</th>
                    <th>Price</th>
                    <th>Color</th>
                    <th>Status</th>
                    <th>Photos</th>
                    <th>Date</th>
                    <th style="min-width:140px;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($products)): ?>
                <tr><td colspan="8" class="text-center py-5 text-muted">No products found.</td></tr>
                <?php else: ?>
                <?php foreach ($products as $p): ?>
                <tr>
                    <td>
                        <?php if ($p['main_image']): ?>
                            <img src="<?= UPLOAD_URL . sanitize($p['main_image']) ?>" class="product-thumb" alt="">
                        <?php else: ?>
                            <div class="product-thumb d-flex align-items-center justify-content-center bg-light rounded">
                                <i class="fas fa-image text-muted small"></i>
                            </div>
                        <?php endif; ?>
                    </td>
                    <td>
                        <div class="fw-semibold"><?= sanitize($p['name']) ?></div>
                        <small class="text-muted"><?= mb_strimwidth(sanitize($p['description'] ?? ''), 0, 60, '...') ?></small>
                    </td>
                    <td class="fw-bold text-primary"><?= formatPrice($p['price']) ?></td>
                    <td><?= sanitize($p['color'] ?: '—') ?></td>
                    <td><?= getStatusBadge($p['selling_status']) ?></td>
                    <td>
                        <span class="badge bg-<?= $p['img_count'] > 0 ? 'primary' : 'secondary' ?>">
                            <?= $p['img_count'] ?>/<?= MAX_PRODUCT_IMAGES ?>
                        </span>
                    </td>
                    <td class="text-muted small"><?= date('d M Y', strtotime($p['created_at'])) ?></td>
                    <td>
                        <a href="<?= SITE_URL ?>/product.php?id=<?= $p['id'] ?>" class="btn btn-action btn-outline-info me-1" target="_blank" title="View on site">
                            <i class="fas fa-eye"></i>
                        </a>
                        <a href="<?= SITE_URL ?>/admin/product_edit.php?id=<?= $p['id'] ?>" class="btn btn-action btn-outline-primary me-1" title="Edit">
                            <i class="fas fa-edit"></i>
                        </a>
                        <a href="<?= SITE_URL ?>/admin/product_delete.php?id=<?= $p['id'] ?>"
                           class="btn btn-action btn-outline-danger"
                           onclick="return confirm('Delete \'<?= addslashes(sanitize($p['name'])) ?>\' and all its images?')"
                           title="Delete">
                            <i class="fas fa-trash"></i>
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include __DIR__ . '/partials/admin_footer.php'; ?>
