<?php
ob_start(); // Start output buffering to prevent header issues

// reserved_products.php - Manage Reserved Products with Search & Reserve
// File location: /bidwheels.net/admin/reserved_products.php

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

requireAdmin();

// Handle reserve action (mark product as reserved)
if (isset($_GET['reserve'])) {
    $id = (int)$_GET['reserve'];
    $product = fetchOne("SELECT is_reserved FROM products WHERE id = $id");
    if ($product && $product['is_reserved'] == 0) {
        update('products', ['is_reserved' => 1], "id = $id");
        setSuccess('Product marked as reserved successfully. Bidding has been stopped.');
    } else {
        setError('Product is already reserved or does not exist.');
    }
    redirect('/admin/reserved_products.php');
}

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

// Handle delete product
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    // Get product images to delete files
    $images = fetchAll("SELECT image_path FROM product_images WHERE product_id = $id");
    $upload_dir = $_SERVER['DOCUMENT_ROOT'] . '/bidwheels/uploads/products/';
    foreach ($images as $image) {
        $filepath = $upload_dir . $image['image_path'];
        if (file_exists($filepath)) {
            unlink($filepath);
        }
    }
    delete('products', "id = $id");
    setSuccess('Product deleted successfully.');
    redirect('/admin/reserved_products.php');
}

// Get search query
$search = isset($_GET['search']) ? sanitize($_GET['search']) : '';

// Build where clause for search
$search_where = "";
if (!empty($search)) {
    $search_where = "AND (p.name LIKE '%$search%' OR p.short_desc LIKE '%$search%')";
}

// Get non-reserved products for search/reserve list
$available_products = fetchAll("
    SELECT p.*, c.name as category_name
    FROM products p
    LEFT JOIN categories c ON p.category_id = c.id
    WHERE p.is_reserved = 0 $search_where
    ORDER BY p.created_at DESC
    LIMIT 50
");

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

// Get reserved products
$reserved_products = fetchAll("
    SELECT p.*, c.name as category_name,
           (SELECT COUNT(*) FROM bids WHERE product_id = p.id) as bid_count,
           (SELECT MAX(amount) FROM bids WHERE product_id = p.id) as highest_bid
    FROM products p
    LEFT JOIN categories c ON p.category_id = c.id
    WHERE p.is_reserved = 1
    ORDER BY p.created_at DESC
    LIMIT $offset, 20
");

$total_reserved = getCount('products', "is_reserved = 1");
$total_pages = ceil($total_reserved / 20);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reserved Products - Admin Panel</title>
    
    <style>
        .admin-page {
            max-width: 1400px;
        }
        
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .page-header h1 {
            font-size: 24px;
            font-weight: 700;
            color: #fff;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .page-header h1 i {
            color: #FF8C3E;
        }
        
        .stats-row {
            display: flex;
            gap: 20px;
            margin-bottom: 25px;
            flex-wrap: wrap;
        }
        
        .stat-box {
            background: white;
            border-radius: 16px;
            padding: 15px 25px;
            display: flex;
            align-items: center;
            gap: 15px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            flex: 1;
            min-width: 180px;
        }
        
        .stat-box-icon {
            width: 45px;
            height: 45px;
            background: #f8f9fa;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .stat-box-icon i {
            font-size: 22px;
            color: #FF8C3E;
        }
        
        .stat-box-info .number {
            font-size: 24px;
            font-weight: 700;
            color: #1a1a1a;
        }
        
        .stat-box-info .label {
            font-size: 12px;
            color: #888;
        }
        
        /* Search Section */
        .search-section {
            background: white;
            border-radius: 20px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        
        .search-section h3 {
            font-size: 18px;
            font-weight: 700;
            color: #1a1a1a;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .search-section h3 i {
            color: #FF8C3E;
        }
        
        .search-form {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            margin-bottom: 20px;
        }
        
        .search-form input {
            flex: 1;
            padding: 12px 18px;
            border: 2px solid #e0e0e0;
            border-radius: 12px;
            font-size: 14px;
            min-width: 200px;
        }
        
        .search-form input:focus {
            outline: none;
            border-color: #FF8C3E;
        }
        
        .search-form button {
            padding: 12px 28px;
            background: #FF8C3E;
            border: none;
            border-radius: 12px;
            color: white;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .search-form button:hover {
            background: #e67a22;
        }
        
        .search-form .reset-btn {
            background: #6c757d;
        }
        
        .search-form .reset-btn:hover {
            background: #5a6268;
        }
        
        .available-products-list {
            margin-top: 20px;
        }
        
        .available-products-list h4 {
            font-size: 14px;
            color: #666;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .product-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 15px;
            border-bottom: 1px solid #f0f0f0;
            transition: all 0.3s;
        }
        
        .product-item:hover {
            background: #fef5ee;
        }
        
        .product-info {
            display: flex;
            align-items: center;
            gap: 15px;
            flex: 1;
        }
        
        .product-thumb {
            width: 50px;
            height: 50px;
            border-radius: 10px;
            object-fit: cover;
        }
        
        .product-details h4 {
            font-size: 14px;
            font-weight: 600;
            color: #1a1a1a;
            margin-bottom: 3px;
        }
        
        .product-details p {
            font-size: 12px;
            color: #888;
        }
        
        .btn-reserve {
            background: #28a745;
            color: white;
            padding: 6px 16px;
            border-radius: 20px;
            text-decoration: none;
            font-size: 12px;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .btn-reserve:hover {
            background: #1e7e34;
        }
        
        .no-results {
            text-align: center;
            padding: 40px;
            color: #888;
        }
        
        /* Reserved Products Table */
        .table-responsive {
            overflow-x: auto;
        }
        
        .admin-table {
            width: 100%;
            background: white;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        
        .admin-table th,
        .admin-table td {
            padding: 14px 12px;
            text-align: left;
            border-bottom: 1px solid #f0f0f0;
            vertical-align: middle;
        }
        
        .admin-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #333;
            font-size: 13px;
        }
        
        .admin-table tr:hover td {
            background: #fef5ee;
        }
        
        .product-thumb-sm {
            width: 45px;
            height: 45px;
            border-radius: 8px;
            object-fit: cover;
        }
        
        .badge-reserved {
            background: #dc3545;
            color: white;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            display: inline-block;
        }
        
        .bid-amount {
            color: #FF8C3E;
            font-weight: 700;
        }
        
        .actions {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        
        .btn-icon {
            padding: 6px 12px;
            border-radius: 8px;
            text-decoration: none;
            font-size: 12px;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            transition: all 0.3s;
        }
        
        .btn-unreserve {
            background: #28a745;
            color: white;
        }
        
        .btn-unreserve:hover {
            background: #1e7e34;
        }
        
        .btn-edit {
            background: #ffc107;
            color: #333;
        }
        
        .btn-edit:hover {
            background: #e0a800;
        }
        
        .btn-delete {
            background: #dc3545;
            color: white;
        }
        
        .btn-delete:hover {
            background: #c82333;
        }
        
        .btn-view {
            background: #17a2b8;
            color: white;
        }
        
        .btn-view:hover {
            background: #138496;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            gap: 8px;
            margin-top: 30px;
            flex-wrap: wrap;
        }
        
        .pagination a {
            padding: 8px 14px;
            background: white;
            color: #333;
            text-decoration: none;
            border-radius: 8px;
            transition: all 0.3s;
        }
        
        .pagination a:hover {
            background: #FF8C3E;
            color: white;
        }
        
        .pagination a.active {
            background: #FF8C3E;
            color: white;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px;
            background: white;
            border-radius: 20px;
        }
        
        .empty-state i {
            font-size: 60px;
            color: #ddd;
            margin-bottom: 15px;
        }
        
        .empty-state h3 {
            font-size: 20px;
            color: #333;
            margin-bottom: 10px;
        }
        
        .empty-state p {
            color: #888;
        }
        
        @media (max-width: 768px) {
            .stats-row {
                flex-direction: column;
            }
            
            .actions {
                flex-direction: column;
            }
            
            .btn-icon {
                justify-content: center;
            }
            
            .admin-table th,
            .admin-table td {
                padding: 10px 8px;
                font-size: 12px;
            }
            
            .product-info {
                flex-wrap: wrap;
            }
        }

        /* Fix text visibility on white background */
.admin-table td,
.admin-table th {
    color: #333;
}

.admin-table td strong,
.admin-table td a,
.admin-table td small {
    color: #333;
}

.admin-table td a:hover {
    color: #FF8C3E;
}

.admin-table td .product-thumb-sm {
    border: 1px solid #eee;
}

.bid-amount {
    color: #FF8C3E;
    font-weight: 700;
}

.badge-reserved {
    background: #dc3545;
    color: white;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
    display: inline-block;
}

/* Action buttons */
.btn-icon {
    color: white;
}

.btn-unreserve {
    background: #28a745;
    color: white;
}

.btn-edit {
    background: #ffc107;
    color: #333;
}

.btn-view {
    background: #17a2b8;
    color: white;
}

.btn-delete {
    background: #dc3545;
    color: white;
}

/* Product name link */
.product-name-link {
    color: #1a1a1a;
    text-decoration: none;
    font-weight: 600;
}

.product-name-link:hover {
    color: #FF8C3E;
}

/* Small text */
small {
    color: #666;
}
    </style>
</head>
<body>

<div class="admin-page">
    <div class="page-header">
        <h1><i class="fas fa-ban"></i> Reserved Products Management</h1>
        <a href="products.php" class="btn-icon" style="background: #6c757d; color: white;">
            <i class="fas fa-arrow-left"></i> Back to Products
        </a>
    </div>
    
    <!-- Stats Row -->
    <div class="stats-row">
        <div class="stat-box">
            <div class="stat-box-icon">
                <i class="fas fa-ban"></i>
            </div>
            <div class="stat-box-info">
                <div class="number"><?php echo $total_reserved; ?></div>
                <div class="label">Reserved Products</div>
            </div>
        </div>
        <div class="stat-box">
            <div class="stat-box-icon">
                <i class="fas fa-dollar-sign"></i>
            </div>
            <div class="stat-box-info">
                <div class="number">
                    <?php 
                    $total_value = fetchOne("SELECT SUM(starting_price) as total FROM products WHERE is_reserved = 1");
                    echo '$' . number_format($total_value['total'] ?? 0, 0);
                    ?>
                </div>
                <div class="label">Total Value</div>
            </div>
        </div>
        <div class="stat-box">
            <div class="stat-box-icon">
                <i class="fas fa-gavel"></i>
            </div>
            <div class="stat-box-info">
                <div class="number">
                    <?php 
                    $total_bids = fetchOne("SELECT COUNT(*) as total FROM bids b JOIN products p ON b.product_id = p.id WHERE p.is_reserved = 1");
                    echo $total_bids['total'] ?? 0;
                    ?>
                </div>
                <div class="label">Total Bids on Reserved</div>
            </div>
        </div>
        <div class="stat-box">
            <div class="stat-box-icon">
                <i class="fas fa-car"></i>
            </div>
            <div class="stat-box-info">
                <div class="number">
                    <?php 
                    $total_available = getCount('products', "is_reserved = 0 AND end_time > NOW()");
                    echo $total_available;
                    ?>
                </div>
                <div class="label">Available Products</div>
            </div>
        </div>
    </div>
    
    <!-- Search & Reserve Section -->
    <div class="search-section">
        <h3><i class="fas fa-search"></i> Find & Reserve Product</h3>
        <form method="GET" action="" class="search-form">
            <input type="text" name="search" placeholder="Search products by name or description..." value="<?php echo htmlspecialchars($search); ?>">
            <button type="submit"><i class="fas fa-search"></i> Search</button>
            <?php if (!empty($search)): ?>
                <a href="reserved_products.php" class="reset-btn" style="padding: 12px 28px; background: #6c757d; color: white; border-radius: 12px; text-decoration: none;"><i class="fas fa-times"></i> Clear</a>
            <?php endif; ?>
        </form>
        
        <div class="available-products-list">
            <h4><i class="fas fa-list"></i> Available Products (Click Reserve to mark as reserved)</h4>
            <?php if (count($available_products) > 0): ?>
                <?php foreach ($available_products as $product): ?>
                    <div class="product-item">
                        <div class="product-info">
                            <img class="product-thumb" src="<?php echo getFeaturedImage($product['id']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>">
                            <div class="product-details">
                                <h4><?php echo htmlspecialchars($product['name']); ?></h4>
                                <p><?php echo htmlspecialchars($product['category_name']); ?> | Starting: <?php echo formatPrice($product['starting_price']); ?></p>
                            </div>
                        </div>
                        <a href="?reserve=<?php echo $product['id']; ?>" class="btn-reserve" onclick="return confirm('Reserve this product? Bidding will be stopped immediately.')">
                            <i class="fas fa-ban"></i> Reserve
                        </a>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="no-results">
                    <?php if (!empty($search)): ?>
                        <p>No products found matching "<strong><?php echo htmlspecialchars($search); ?></strong>"</p>
                        <a href="reserved_products.php" class="btn-reserve" style="background: #6c757d;">Clear Search</a>
                    <?php else: ?>
                        <p>No available products found. All products are either reserved or have ended.</p>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <?php echo getMessage(); ?>
    
    <!-- Reserved Products List -->
    <h3 style="margin-bottom: 20px; color: #fff;"><i class="fas fa-ban"></i> Currently Reserved Products</h3>
    
    <?php if (count($reserved_products) > 0): ?>
    <div class="table-responsive">
        <table class="admin-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Image</th>
                    <th>Product Name</th>
                    <th>Category</th>
                    <th>Starting Price</th>
                    <th>Final Bid</th>
                    <th>Bids</th>
                    <th>Status</th>
                    <th>Reserved On</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($reserved_products as $product): ?>
                <tr>
                    <td><?php echo $product['id']; ?></td>
                    <td>
                        <img class="product-thumb-sm" src="<?php echo getFeaturedImage($product['id']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>">
                    </td>
                    <td>
                        <strong><?php echo htmlspecialchars($product['name']); ?></strong><br>
                        <small style="color: #888;"><?php echo htmlspecialchars(substr($product['short_desc'], 0, 50)); ?>...</small>
                    </td>
                    <td><?php echo htmlspecialchars($product['category_name']); ?></td>
                    <td><?php echo formatPrice($product['starting_price']); ?></td>
                    <td class="bid-amount"><?php echo formatPrice($product['highest_bid'] ?? $product['starting_price']); ?></td>
                    <td><?php echo $product['bid_count']; ?></td>
                    <td><span class="badge-reserved"><i class="fas fa-ban"></i> Reserved</span></td>
                    <td><?php echo date('M d, Y', strtotime($product['created_at'])); ?></td>
                    <td class="actions">
                        <a href="?unreserve=<?php echo $product['id']; ?>" class="btn-icon btn-unreserve" onclick="return confirm('Unreserve this product? Bidding will resume.')">
                            <i class="fas fa-play"></i> Unreserve
                        </a>
                        <a href="edit_product.php?id=<?php echo $product['id']; ?>" class="btn-icon btn-edit">
                            <i class="fas fa-edit"></i> Edit
                        </a>
                        <a href="<?php echo SITE_URL; ?>/product/detail.php?id=<?php echo $product['id']; ?>" target="_blank" class="btn-icon btn-view">
                            <i class="fas fa-eye"></i> View
                        </a>
                        <a href="?delete=<?php echo $product['id']; ?>" class="btn-icon btn-delete" onclick="return confirm('Delete this product? This cannot be undone.')">
                            <i class="fas fa-trash"></i> Delete
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    
    <!-- Pagination -->
    <?php if ($total_pages > 1): ?>
    <div class="pagination">
        <?php if ($page > 1): ?>
            <a href="?page=<?php echo $page - 1; ?>"><i class="fas fa-chevron-left"></i> Prev</a>
        <?php endif; ?>
        
        <?php
        $start_page = max(1, $page - 2);
        $end_page = min($total_pages, $page + 2);
        
        if ($start_page > 1) {
            echo '<a href="?page=1">1</a>';
            if ($start_page > 2) echo '<span style="padding: 8px 6px;">...</span>';
        }
        
        for ($i = $start_page; $i <= $end_page; $i++): ?>
            <a href="?page=<?php echo $i; ?>" class="<?php echo $i == $page ? 'active' : ''; ?>"><?php echo $i; ?></a>
        <?php endfor;
        
        if ($end_page < $total_pages) {
            if ($end_page < $total_pages - 1) echo '<span style="padding: 8px 6px;">...</span>';
            echo '<a href="?page=' . $total_pages . '">' . $total_pages . '</a>';
        }
        ?>
        
        <?php if ($page < $total_pages): ?>
            <a href="?page=<?php echo $page + 1; ?>">Next <i class="fas fa-chevron-right"></i></a>
        <?php endif; ?>
    </div>
    <?php endif; ?>
    
    <?php else: ?>
    <div class="empty-state">
        <i class="fas fa-ban"></i>
        <h3>No Reserved Products</h3>
        <p>No products have been marked as reserved yet. Use the search above to find and reserve products.</p>
    </div>
    <?php endif; ?>
</div>

<?php require_once 'includes/admin_footer.php'; ?>
<?php ob_end_flush(); ?>