<?php
// products.php - Manage Products
// File location: /bidwheels.net/admin/products.php

require_once '../includes/auth.php';
require_once '../includes/functions.php';
require_once 'includes/admin_header.php';

requireAdmin();

// Handle reserve/unreserve action
if (isset($_GET['reserve'])) {
    $id = (int)$_GET['reserve'];
    update('products', ['is_reserved' => 1], "id = $id");
    setSuccess('Product marked as reserved. Bidding stopped.');
    redirect('/admin/products.php');
}

if (isset($_GET['unreserve'])) {
    $id = (int)$_GET['unreserve'];
    update('products', ['is_reserved' => 0], "id = $id");
    setSuccess('Product unreserved. Bidding resumed.');
    redirect('/admin/products.php');
}

if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    delete('products', "id = $id");
    setSuccess('Product deleted successfully.');
    redirect('/admin/products.php');
}

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * 20;
$search = isset($_GET['search']) ? sanitize($_GET['search']) : '';

$where = "1=1";
if ($search) {
    $where .= " AND (p.name LIKE '%$search%' OR p.short_desc LIKE '%$search%')";
}

$total = getCount('products p', $where);
$total_pages = ceil($total / 20);

$products = fetchAll("
    SELECT p.*, c.name as category_name,
           (SELECT COUNT(*) FROM bids WHERE product_id = p.id) as bid_count
    FROM products p
    LEFT JOIN categories c ON p.category_id = c.id
    WHERE $where
    ORDER BY p.created_at DESC
    LIMIT $offset, 20
");
?>

<div class="admin-page">
    <div class="page-header">
        <h1 class="page-title">Manage Products</h1>
        <a href="add_product.php" class="btn btn-primary"><i class="fas fa-plus"></i> Add Product</a>
    </div>
    
    <div class="search-box">
        <form method="GET" action="">
            <input type="text" name="search" placeholder="Search products..." value="<?php echo htmlspecialchars($search); ?>">
            <button type="submit"><i class="fas fa-search"></i> Search</button>
        </form>
    </div>
    
    <?php echo getMessage(); ?>
    
    <div class="table-responsive">
        <table class="admin-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Image</th>
                    <th>Name</th>
                    <th>Category</th>
                    <th>Starting Price</th>
                    <th>Current Bid</th>
                    <th>Bids</th>
                    <th>Status</th>
                    <th>End Time</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (count($products) > 0): ?>
                    <?php foreach ($products as $product): ?>
                        <tr>
                            <td><?php echo $product['id']; ?></td>
                            <td>
                                <img src="<?php echo getFeaturedImage($product['id']); ?>" style="width: 50px; height: 50px; object-fit: cover;">
                            </td>
                            <td><?php echo htmlspecialchars($product['name']); ?></td>
                            <td><?php echo htmlspecialchars($product['category_name']); ?></td>
                            <td><?php echo formatPrice($product['starting_price']); ?></td>
                            <td><?php echo formatPrice($product['current_highest_bid'] ?? $product['starting_price']); ?></td>
                            <td><?php echo $product['bid_count']; ?></td>
                            <td>
                                <?php if ($product['is_reserved']): ?>
                                    <span class="badge badge-danger">Reserved</span>
                                <?php elseif (strtotime($product['end_time']) < time()): ?>
                                    <span class="badge badge-dark">Ended</span>
                                <?php else: ?>
                                    <span class="badge badge-success">Active</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo date('M d, Y', strtotime($product['end_time'])); ?></td>
                            <td class="actions">
                                <a href="edit_product.php?id=<?php echo $product['id']; ?>" class="btn-icon"><i class="fas fa-edit"></i></a>
                                <?php if ($product['is_reserved']): ?>
                                    <a href="?unreserve=<?php echo $product['id']; ?>" class="btn-icon btn-success" onclick="return confirm('Unreserve this product?')"><i class="fas fa-check-circle"></i></a>
                                <?php else: ?>
                                    <a href="?reserve=<?php echo $product['id']; ?>" class="btn-icon btn-warning" onclick="return confirm('Mark as reserved? Bidding will stop.')"><i class="fas fa-ban"></i></a>
                                <?php endif; ?>
                                <a href="?delete=<?php echo $product['id']; ?>" class="btn-icon btn-danger" onclick="return confirm('Delete this product? This cannot be undone.')"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="10" style="text-align: center;">No products found.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <?php if ($total_pages > 1): ?>
        <div class="pagination">
            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <a href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>" class="<?php echo $i == $page ? 'active' : ''; ?>"><?php echo $i; ?></a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>
</div>

<style>
.admin-page {
    max-width: 1400px;
}
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}
.search-box {
    margin-bottom: 20px;
}
.search-box form {
    display: flex;
    gap: 10px;
}
.search-box input {
    flex: 1;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
}
.search-box button {
    padding: 10px 20px;
    background: #e63946;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}
.admin-table th, .admin-table td {
    padding: 12px;
    vertical-align: middle;
}
.actions {
    display: flex;
    gap: 8px;
}
.btn-icon {
    padding: 5px 8px;
    border-radius: 3px;
    color: white;
    text-decoration: none;
    display: inline-block;
}
.btn-icon i {
    font-size: 12px;
}
.btn-success {
    background: #28a745;
}
.btn-warning {
    background: #ffc107;
    color: #333;
}
.btn-danger {
    background: #dc3545;
}
.badge {
    padding: 4px 8px;
    border-radius: 3px;
    font-size: 11px;
    font-weight: bold;
}
.badge-success {
    background: #d4edda;
    color: #155724;
}
.badge-danger {
    background: #f8d7da;
    color: #721c24;
}
.badge-dark {
    background: #343a40;
    color: white;
}
.pagination {
    margin-top: 20px;
    display: flex;
    gap: 5px;
    justify-content: center;
}
.pagination a {
    padding: 8px 12px;
    background: white;
    border: 1px solid #ddd;
    color: #333;
    text-decoration: none;
    border-radius: 3px;
}
.pagination a.active {
    background: #e63946;
    color: white;
    border-color: #e63946;
}
</style>

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