<?php
/**
 * Admin Products Management
 * Digital Marketplace
 */

require_once __DIR__ . '/../config/database.php';
require_login();

if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
    header('Location: ' . BASE_URL . '/index.php');
    exit;
}

$page_title = 'Products';

// Handle delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    try {
        $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
        $stmt->execute([$id]);
        set_flash_message('Product deleted successfully!', 'success');
    } catch (PDOException $e) {
        set_flash_message('Failed to delete product.', 'error');
    }
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Handle status toggle
if (isset($_GET['toggle'])) {
    $id = (int)$_GET['toggle'];
    try {
        $stmt = $pdo->prepare("UPDATE products SET status = IF(status = 'active', 'inactive', 'active') WHERE id = ?");
        $stmt->execute([$id]);
        set_flash_message('Product status updated!', 'success');
    } catch (PDOException $e) {
        set_flash_message('Failed to update status.', 'error');
    }
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Pagination
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Search
$search = sanitize($_GET['search'] ?? '');
$category_filter = (int)($_GET['category'] ?? 0);
$status_filter = sanitize($_GET['status'] ?? '');

// Build query
$sql = "SELECT p.*, c.name as category_name FROM products p LEFT JOIN categories c ON p.category_id = c.id WHERE 1=1";
$count_sql = "SELECT COUNT(*) FROM products p LEFT JOIN categories c ON p.category_id = c.id WHERE 1=1";
$params = [];

if ($search) {
    $sql .= " AND (p.name LIKE ? OR p.description LIKE ?)";
    $count_sql .= " AND (p.name LIKE ? OR p.description LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($category_filter) {
    $sql .= " AND p.category_id = ?";
    $count_sql .= " AND p.category_id = ?";
    $params[] = $category_filter;
}

if ($status_filter) {
    $sql .= " AND p.status = ?";
    $count_sql .= " AND p.status = ?";
    $params[] = $status_filter;
}

$sql .= " ORDER BY p.created_at DESC LIMIT ? OFFSET ?";

// Get total count
$stmt = $pdo->prepare($count_sql);
$stmt->execute($params);
$total_products = $stmt->fetchColumn();
$total_pages = ceil($total_products / $per_page);

// Get products
$stmt = $pdo->prepare($sql);
$stmt->execute(array_merge($params, [$per_page, $offset]));
$products = $stmt->fetchAll();

// Get categories for filter
$categories = get_all_categories(false);

include __DIR__ . '/includes/header.php';
?>

<div class="admin-content">
    <div class="admin-header d-flex justify-content-between align-items-center">
        <h1><i class="fas fa-box me-2"></i>Products</h1>
        <a href="product-edit.php" class="btn btn-primary">
            <i class="fas fa-plus me-2"></i>Add Product
        </a>
    </div>
    
    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-4">
                    <input type="text" name="search" class="form-control" placeholder="Search products..." 
                           value="<?php echo $search; ?>">
                </div>
                <div class="col-md-3">
                    <select name="category" class="form-select">
                        <option value="">All Categories</option>
                        <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo $cat['id']; ?>" <?php echo $category_filter == $cat['id'] ? 'selected' : ''; ?>>
                            <?php echo sanitize($cat['name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <select name="status" class="form-select">
                        <option value="">All Status</option>
                        <option value="active" <?php echo $status_filter === 'active' ? 'selected' : ''; ?>>Active</option>
                        <option value="inactive" <?php echo $status_filter === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-search me-2"></i>Filter
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Products Table -->
    <div class="card">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th>Product</th>
                            <th>Category</th>
                            <th>Price</th>
                            <th>Stock</th>
                            <th>Sales</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($products as $product): ?>
                        <tr>
                            <td>
                                <div class="d-flex align-items-center">
                                    <img src="<?php echo get_product_image_url($product); ?>" 
                                         alt="" class="rounded me-2"
                                         style="width: 50px; height: 50px; object-fit: cover;"
                                         onerror="this.src='<?php echo ASSETS_URL; ?>/images/no-image.jpg'">
                                    <div>
                                        <strong><?php echo sanitize($product['name']); ?></strong>
                                        <small class="d-block text-muted"><?php echo $product['slug']; ?></small>
                                    </div>
                                </div>
                            </td>
                            <td><?php echo sanitize($product['category_name'] ?? '-'); ?></td>
                            <td>
                                <?php if ($product['sale_price'] > 0 && $product['sale_price'] < $product['price']): ?>
                                    <span class="text-success"><?php echo format_price($product['sale_price']); ?></span>
                                    <small class="text-decoration-line-through text-muted"><?php echo format_price($product['price']); ?></small>
                                <?php else: ?>
                                    <?php echo format_price($product['price']); ?>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($product['stock'] > 10): ?>
                                    <span class="badge bg-success"><?php echo $product['stock']; ?></span>
                                <?php elseif ($product['stock'] > 0): ?>
                                    <span class="badge bg-warning"><?php echo $product['stock']; ?></span>
                                <?php else: ?>
                                    <span class="badge bg-danger">Out of Stock</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo number_format($product['times_sold']); ?></td>
                            <td>
                                <a href="?toggle=<?php echo $product['id']; ?>" class="badge bg-<?php echo $product['status'] === 'active' ? 'success' : 'secondary'; ?> text-decoration-none">
                                    <?php echo ucfirst($product['status']); ?>
                                </a>
                            </td>
                            <td>
                                <a href="product-edit.php?id=<?php echo $product['id']; ?>" class="btn btn-sm btn-primary" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="?delete=<?php echo $product['id']; ?>" class="btn btn-sm btn-danger confirm-delete" title="Delete">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="card-footer">
            <nav>
                <ul class="pagination justify-content-center mb-0">
                    <?php if ($page > 1): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo $search; ?>&category=<?php echo $category_filter; ?>&status=<?php echo $status_filter; ?>">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                    </li>
                    <?php endif; ?>
                    
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo $search; ?>&category=<?php echo $category_filter; ?>&status=<?php echo $status_filter; ?>"><?php echo $i; ?></a>
                    </li>
                    <?php endfor; ?>
                    
                    <?php if ($page < $total_pages): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo $search; ?>&category=<?php echo $category_filter; ?>&status=<?php echo $status_filter; ?>">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                    </li>
                    <?php endif; ?>
                </ul>
            </nav>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
