<?php
// admin/products.php
require '../config/db.php';


if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') { 
    header("Location: ../index.php"); 
    exit; 
}

if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $pdo->prepare("DELETE FROM products WHERE id = ?")->execute([$id]);
    header("Location: admin/products.php"); 
    exit;
}

$items = $pdo->query("SELECT p.*, u.username FROM products p JOIN users u ON p.seller_id = u.id ORDER BY p.created_at DESC")->fetchAll();
include '../includes/header.php';
?>

<div style="max-width: 1100px; margin: 40px auto; padding: 0 20px;">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;">
        <h2 style="color: white; margin: 0;">Global Product Management</h2>
        <a href="admin/" style="color: var(--primary); text-decoration: none; font-weight: 700; font-size: 14px;">
            <i class="fa-solid fa-arrow-left"></i> Back to Dash
        </a>
    </div>

    <table style="width: 100%; border-collapse: collapse; background: var(--nav-bg); border: 1px solid var(--border); border-radius: 12px; overflow: hidden; color: white;">
        <tr style="background: #1c2128; color: var(--text-gray); font-size: 11px; text-align: left; text-transform: uppercase; letter-spacing: 1px;">
            <th style="padding: 15px;">Product</th>
            <th style="padding: 15px;">Seller</th>
            <th style="padding: 15px;">Stock</th>
            <th style="padding: 15px;">Price</th>
            <th style="padding: 15px; text-align: center;">Actions</th>
        </tr>
        <?php foreach($items as $i): ?>
        <tr style="border-bottom: 1px solid var(--border); font-size: 14px; transition: 0.2s;" onmouseover="this.style.background='rgba(255,255,255,0.02)'" onmouseout="this.style.background='transparent'">
            <td style="padding: 15px;"><strong><?php echo htmlspecialchars($i['title']); ?></strong></td>
            <td style="padding: 15px; color: var(--text-gray);">@<?php echo htmlspecialchars($i['username']); ?></td>
            <td style="padding: 15px;"><?php echo $i['stock']; ?></td>
            <td style="padding: 15px; color: var(--primary); font-weight: 700;">$<?php echo number_format($i['price'], 2); ?></td>
            <td style="padding: 15px; text-align: center;">
                <a href="admin/products.php?delete=<?php echo $i['id']; ?>" onclick="return confirm('¿Eliminar producto?')" style="color: #ff4d4d; text-decoration: none; font-size: 18px;">
                    <i class="fa-solid fa-trash-can"></i>
                </a>
            </td>
        </tr>
        <?php endforeach; ?>
    </table>
</div>

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