<?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
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'], $_POST['report_id'])) {
    $rid = (int)$_POST['report_id'];
    $reported_uid = isset($_POST['reported_user_id']) ? (int)$_POST['reported_user_id'] : 0;

    if ($_POST['action'] === 'resolve') {
        $pdo->prepare("UPDATE reports SET status = 'resolved' WHERE id = ?")->execute([$rid]);
    } elseif ($_POST['action'] === 'reject') {
        $pdo->prepare("UPDATE reports SET status = 'rejected' WHERE id = ?")->execute([$rid]);
    } elseif ($_POST['action'] === 'ban' && $reported_uid > 0) {
        $pdo->beginTransaction();
        try {
            // Ban User
            $pdo->prepare("UPDATE users SET status = 'banned' WHERE id = ?")->execute([$reported_uid]);
            // Resolve Report automatically
            $pdo->prepare("UPDATE reports SET status = 'resolved' WHERE id = ?")->execute([$rid]);
            $pdo->commit();
        } catch (Exception $e) {
            $pdo->rollBack();
        }
    }
    
    // Refresh
    echo "<script>window.location.href='reports.php';</script>";
    exit;
}

// Fetch Reports
try {
    // Counts
    $pending_count = $pdo->query("SELECT COUNT(*) FROM reports WHERE status = 'pending'")->fetchColumn();
    $resolved_today = $pdo->query("SELECT COUNT(*) FROM reports WHERE status = 'resolved' AND DATE(updated_at) = CURDATE()")->fetchColumn();

    // List
    $status_filter = isset($_GET['status']) ? $_GET['status'] : 'pending';
    
    $sql = "SELECT r.*, 
            u1.username as reporter_name, u1.avatar as reporter_avatar,
            u2.username as reported_name, u2.avatar as reported_avatar, u2.status as reported_status
            FROM reports r
            JOIN users u1 ON r.reporter_id = u1.id
            LEFT JOIN users u2 ON r.reported_id = u2.id
            WHERE r.status = ?
            ORDER BY r.created_at DESC";
            
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$status_filter]);
    $reports = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

renderAdminSidebar('reports');
?>

<div class="flex flex-col h-[calc(100vh-140px)]">
    <!-- Header -->
    <div class="flex justify-between items-center mb-6">
        <div>
             <h2 class="text-3xl font-bold text-white tracking-tight">Reportes & Moderación</h2>
            <p class="text-gray-400 text-sm">Gestiona tickets de usuarios y contenido reportado.</p>
        </div>
        <div class="flex gap-2">
            <span class="px-3 py-1 bg-yellow-500/20 text-yellow-400 text-xs font-bold rounded-lg border border-yellow-500/30 flex items-center gap-2">
                <i class="fas fa-exclamation-triangle"></i> <?php echo $pending_count; ?> Pendientes
            </span>
             <span class="px-3 py-1 bg-green-500/20 text-green-400 text-xs font-bold rounded-lg border border-green-500/30 flex items-center gap-2">
                <i class="fas fa-check"></i> <?php echo $resolved_today; ?> Resueltos (Hoy)
            </span>
        </div>
    </div>

    <!-- Reports Container -->
    <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">
            <a href="?status=pending" class="px-6 py-4 text-sm font-bold <?php echo $status_filter==='pending' ? 'text-brand-500 border-b-2 border-brand-500 bg-dark-800' : 'text-gray-400 hover:text-white'; ?> transition">
                Pendientes
            </a>
            <a href="?status=resolved" class="px-6 py-4 text-sm font-bold <?php echo $status_filter==='resolved' ? 'text-brand-500 border-b-2 border-brand-500 bg-dark-800' : 'text-gray-400 hover:text-white'; ?> transition">
                Resueltos
            </a>
            <a href="?status=rejected" class="px-6 py-4 text-sm font-bold <?php echo $status_filter==='rejected' ? 'text-brand-500 border-b-2 border-brand-500 bg-dark-800' : 'text-gray-400 hover:text-white'; ?> transition">
                Rechazados
            </a>
        </div>

        <!-- List -->
        <div class="flex-1 overflow-y-auto divide-y divide-dark-700">
            
            <?php foreach ($reports as $r): ?>
            <div class="p-6 hover:bg-dark-700/30 transition group">
                <div class="flex justify-between items-start">
                    <div class="flex gap-4">
                        <!-- Icon based on type -->
                        <?php 
                            $icon = 'fa-flag';
                            $color = 'text-gray-400';
                            $bg = 'bg-gray-500/20';
                            
                            switch($r['type']) {
                                case 'spam': $icon='fa-bug'; $color='text-red-400'; $bg='bg-red-500/20'; break;
                                case 'bug': $icon='fa-code'; $color='text-blue-400'; $bg='bg-blue-500/20'; break;
                                case 'harassment': $icon='fa-user-slash'; $color='text-orange-400'; $bg='bg-orange-500/20'; break;
                                case 'billing': $icon='fa-receipt'; $color='text-green-400'; $bg='bg-green-500/20'; break;
                            }
                        ?>
                        <div class="w-10 h-10 rounded-full <?php echo $bg . ' ' . $color; ?> flex items-center justify-center flex-shrink-0">
                            <i class="fas <?php echo $icon; ?>"></i>
                        </div>
                        
                        <div>
                            <h4 class="text-white font-bold text-sm">
                                <?php echo ucfirst($r['type']); ?> 
                                <span class="text-gray-500 font-normal">#<?php echo $r['id']; ?></span>
                            </h4>
                            
                            <p class="text-xs text-gray-400 mt-1">
                                Reportado por <span class="text-brand-400 font-bold"><?php echo htmlspecialchars($r['reporter_name']); ?></span>
                                <?php if($r['reported_id']): ?>
                                    contra <span class="text-red-400 font-bold"><?php echo htmlspecialchars($r['reported_name']); ?></span>
                                    <?php if($r['reported_status'] === 'banned'): ?>
                                        <span class="bg-red-600 text-white px-1 rounded text-[10px] ml-1">BANNED</span>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </p>
                            
                            <?php if($r['description']): ?>
                            <div class="mt-3 p-3 bg-dark-900 rounded-lg border border-dark-700 text-sm text-gray-300 italic">
                                "<?php echo nl2br(htmlspecialchars($r['description'])); ?>"
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="text-right">
                        <span class="text-xs text-gray-500 block mb-2"><?php echo date('d M H:i', strtotime($r['created_at'])); ?></span>
                        
                        <?php if($status_filter === 'pending'): ?>
                        <div class="flex gap-2 opacity-100 transition">
                            <!-- Resolve Button -->
                            <form method="POST">
                                <input type="hidden" name="action" value="resolve">
                                <input type="hidden" name="report_id" value="<?php echo $r['id']; ?>">
                                <button class="px-3 py-1 bg-green-600 hover:bg-green-700 text-white text-xs rounded shadow transition">
                                    <i class="fas fa-check mr-1"></i> Resolver
                                </button>
                            </form>
                            
                            <!-- Reject/Ignore Button -->
                            <form method="POST">
                                <input type="hidden" name="action" value="reject">
                                <input type="hidden" name="report_id" value="<?php echo $r['id']; ?>">
                                <button class="px-3 py-1 bg-gray-600 hover:bg-gray-700 text-white text-xs rounded shadow transition" title="Marcar como invalido">
                                    <i class="fas fa-times"></i>
                                </button>
                            </form>

                            <!-- Ban Button (Only if Reported User Exists) -->
                            <?php if($r['reported_id']): ?>
                            <form method="POST" onsubmit="return confirm('¿Seguro que quieres BANEAR a este usuario?');">
                                <input type="hidden" name="action" value="ban">
                                <input type="hidden" name="report_id" value="<?php echo $r['id']; ?>">
                                <input type="hidden" name="reported_user_id" value="<?php echo $r['reported_id']; ?>">
                                <button class="px-3 py-1 bg-red-600 hover:bg-red-700 text-white text-xs rounded shadow transition">
                                    <i class="fas fa-gavel mr-1"></i> Banear
                                </button>
                            </form>
                            <?php endif; ?>
                        </div>
                        <?php else: ?>
                            <span class="px-2 py-1 bg-dark-900 rounded text-xs text-gray-500 uppercase font-bold"><?php echo $r['status']; ?></span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>

            <?php if(empty($reports)): ?>
                <div class="p-12 text-center text-gray-500">
                    <div class="w-16 h-16 bg-dark-900 rounded-full flex items-center justify-center mx-auto mb-4 text-gray-600 opacity-50">
                        <i class="fas fa-clipboard-check text-2xl"></i>
                    </div>
                    No hay reportes en esta sección.
                </div>
            <?php endif; ?>

        </div>
    </div>
</div>

<?php renderAdminFooter(); ?>
