<?php
require_once '../config/db.php';
require_once 'layout.php';

// OVERRIDE: Admin panel needs HTML
header('Content-Type: text/html; charset=utf-8');

// Handle Actions (Delete Service)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'], $_POST['service_id'])) {
    if ($_POST['action'] === 'delete') {
        $sid = (int)$_POST['service_id'];
        $pdo->prepare("UPDATE services SET is_active = FALSE WHERE id = ?")->execute([$sid]);
    }
    echo "<script>window.location.href='marketplace.php';</script>";
    exit;
}

// Fetch Services
try {
    $sql_services = "SELECT s.*, u.username, u.email 
                     FROM services s 
                     JOIN users u ON s.seller_id = u.id 
                     WHERE s.is_active = TRUE 
                     ORDER BY s.created_at DESC LIMIT 50";
    $services = $pdo->query($sql_services)->fetchAll(PDO::FETCH_ASSOC);

    // Fetch Orders
    $sql_orders = "SELECT o.*, s.title as service_title, b.username as buyer_name, sel.username as seller_name
                   FROM orders o
                   JOIN services s ON o.service_id = s.id
                   JOIN users b ON o.buyer_id = b.id
                   JOIN users sel ON o.seller_id = sel.id
                   ORDER BY o.created_at DESC LIMIT 50";
    $orders = $pdo->query($sql_orders)->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die("Error DB: " . $e->getMessage());
}

renderAdminSidebar('marketplace');
?>

<div class="flex flex-col h-[calc(100vh-140px)]">
    <!-- Header -->
    <div class="mb-6">
        <h2 class="text-3xl font-bold text-white tracking-tight">Marketplace Global</h2>
        <p class="text-gray-400 mt-1">Gestiona los servicios publicados y monitorea las transacciones.</p>
    </div>

    <!-- Main Content -->
    <div class="flex-1 bg-dark-800 rounded-2xl border border-dark-700 shadow-xl overflow-hidden flex flex-col">
        <!-- Tabs -->
        <div class="flex border-b border-dark-700 bg-dark-900/50">
            <button onclick="switchTab('services')" id="tab-services" class="px-6 py-4 text-sm font-bold text-brand-500 border-b-2 border-brand-500 bg-dark-800 transition">
                <i class="fas fa-store mr-2"></i> Servicios Activos
            </button>
            <button onclick="switchTab('orders')" id="tab-orders" class="px-6 py-4 text-sm font-medium text-gray-400 hover:text-white hover:bg-dark-800 transition border-b-2 border-transparent">
                <i class="fas fa-receipt mr-2"></i> Historial de Pedidos
            </button>
        </div>

        <!-- Content: Services -->
        <div id="content-services" class="flex-1 overflow-y-auto">
            <div class="p-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                <?php foreach ($services as $svc): ?>
                <!-- Service Card -->
                <div class="bg-dark-900 border border-dark-700 rounded-xl overflow-hidden group hover:border-brand-500 transition">
                    <div class="h-32 bg-gray-800 relative">
                        <?php if($svc['image_url']): ?>
                            <img src="<?php echo htmlspecialchars($svc['image_url']); ?>" class="w-full h-full object-cover opacity-80 group-hover:opacity-100 transition">
                        <?php else: ?>
                            <div class="w-full h-full flex items-center justify-center text-gray-600">
                                <i class="fas fa-image text-3xl"></i>
                            </div>
                        <?php endif; ?>
                        <div class="absolute top-2 right-2 bg-black/60 backdrop-blur px-2 py-1 rounded text-xs text-white font-bold">
                            <?php echo number_format($svc['price']); ?> 💎
                        </div>
                    </div>
                    <div class="p-4">
                        <div class="flex justify-between items-start mb-2">
                             <h3 class="text-white font-bold text-sm truncate pr-2"><?php echo htmlspecialchars($svc['title']); ?></h3>
                        </div>
                        <p class="text-gray-500 text-xs mb-3 line-clamp-2 h-8"><?php echo htmlspecialchars($svc['description']); ?></p>
                        
                        <div class="flex justify-between items-center pt-3 border-t border-dark-700">
                             <div class="flex items-center gap-2">
                                <div class="w-5 h-5 rounded-full bg-brand-500/20 text-brand-400 flex items-center justify-center text-[10px] font-bold">
                                    <?php echo strtoupper(substr($svc['username'], 0, 1)); ?>
                                </div>
                                <span class="text-xs text-gray-400 truncate max-w-[80px]"><?php echo htmlspecialchars($svc['username']); ?></span>
                            </div>
                            <form method="POST" onsubmit="return confirm('¿Eliminar servicio?');">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="service_id" value="<?php echo $svc['id']; ?>">
                                <button type="submit" class="text-xs text-red-500 hover:text-red-400 hover:underline">Eliminar</button>
                            </form>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
                
                <?php if(empty($services)): ?>
                    <div class="col-span-full py-12 text-center text-gray-500">
                        <i class="fas fa-box-open text-4xl mb-2 opacity-50"></i>
                         <p>No hay servicios activos.</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Content: Orders -->
        <div id="content-orders" class="flex-1 overflow-y-auto hidden">
             <table class="w-full text-left text-sm text-gray-400">
                <thead class="bg-dark-900 text-gray-200 font-medium uppercase text-xs sticky top-0">
                    <tr>
                        <th class="px-6 py-4 bg-dark-900">ID</th>
                        <th class="px-6 py-4 bg-dark-900">Servicio</th>
                        <th class="px-6 py-4 bg-dark-900">Comprador</th>
                        <th class="px-6 py-4 bg-dark-900">Vendedor</th>
                        <th class="px-6 py-4 bg-dark-900">Monto</th>
                        <th class="px-6 py-4 bg-dark-900">Estado</th>
                        <th class="px-6 py-4 bg-dark-900">Fecha</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-dark-700">
                    <?php foreach ($orders as $ord): ?>
                    <tr class="hover:bg-dark-700/50 transition">
                        <td class="px-6 py-4 font-mono text-xs">#<?php echo $ord['id']; ?></td>
                        <td class="px-6 py-4 text-white font-medium"><?php echo htmlspecialchars($ord['service_title']); ?></td>
                        <td class="px-6 py-4 text-blue-400"><?php echo htmlspecialchars($ord['buyer_name']); ?></td>
                        <td class="px-6 py-4 text-purple-400"><?php echo htmlspecialchars($ord['seller_name']); ?></td>
                        <td class="px-6 py-4 font-bold text-yellow-500"><?php echo number_format($ord['amount']); ?> 💎</td>
                        <td class="px-6 py-4">
                            <span class="px-2 py-0.5 rounded text-[10px] uppercase font-bold bg-green-500/20 text-green-400 border border-green-500/20">
                                <?php echo $ord['status']; ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 text-xs"><?php echo date('d M H:i', strtotime($ord['created_at'])); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
function switchTab(tab) {
    // Buttons
    document.getElementById('tab-services').className = tab === 'services' 
        ? 'px-6 py-4 text-sm font-bold text-brand-500 border-b-2 border-brand-500 bg-dark-800 transition'
        : 'px-6 py-4 text-sm font-medium text-gray-400 hover:text-white hover:bg-dark-800 transition border-b-2 border-transparent';
    
    document.getElementById('tab-orders').className = tab === 'orders'
        ? 'px-6 py-4 text-sm font-bold text-brand-500 border-b-2 border-brand-500 bg-dark-800 transition'
        : 'px-6 py-4 text-sm font-medium text-gray-400 hover:text-white hover:bg-dark-800 transition border-b-2 border-transparent';

    // Content
    document.getElementById('content-services').classList.toggle('hidden', tab !== 'services');
    document.getElementById('content-orders').classList.toggle('hidden', tab !== 'orders');
}
</script>

<?php renderAdminFooter(); ?>
