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

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

// Handle Sending Notification
$successMsg = '';
$errorMsg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['title'], $_POST['message'])) {
    
    $title = trim($_POST['title']);
    $message = trim($_POST['message']);
    $type = 'system';
    $target = $_POST['target']; // 'all' or 'specific_user' (not impl for now)

    if ($target === 'all') {
        try {
            // Get all user IDs (optimize for batch later)
            $users = $pdo->query("SELECT id FROM users")->fetchAll(PDO::FETCH_COLUMN);
            
            $pdo->beginTransaction();
            $sql = "INSERT INTO notifications (user_id, type, title, message) VALUES (?, ?, ?, ?)";
            $stmt = $pdo->prepare($sql);
            
            foreach ($users as $uid) {
                $stmt->execute([$uid, $type, $title, $message]);
            }
            $pdo->commit();
            $successMsg = "Notificación enviada a " . count($users) . " usuarios.";
            
        } catch (Exception $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            $errorMsg = "Error: " . $e->getMessage();
        }
    }
}

renderAdminSidebar('notifications');
?>

<div class="max-w-4xl mx-auto">
    <!-- Header -->
    <div class="mb-8 ">
        <h2 class="text-3xl font-bold text-white tracking-tight">Centro de Notificaciones</h2>
        <p class="text-gray-400 mt-1">Envía alertas globales o mensajes de sistema a todos los usuarios.</p>
    </div>

    <?php if ($successMsg): ?>
        <div class="mb-6 p-4 bg-green-500/10 border border-green-500/50 rounded-xl text-green-400 flex items-center gap-3">
            <i class="fas fa-check-circle text-xl"></i> <?php echo $successMsg; ?>
        </div>
    <?php endif; ?>

    <?php if ($errorMsg): ?>
        <div class="mb-6 p-4 bg-red-500/10 border border-red-500/50 rounded-xl text-red-400 flex items-center gap-3">
            <i class="fas fa-exclamation-circle text-xl"></i> <?php echo $errorMsg; ?>
        </div>
    <?php endif; ?>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- Send Form -->
        <div class="lg:col-span-2 space-y-6">
            <div class="bg-dark-800 rounded-2xl border border-dark-700 shadow-xl p-6">
                <h3 class="text-xl font-bold text-white mb-6 border-b border-dark-700 pb-4">
                    <i class="fas fa-paper-plane text-brand-500 mr-2"></i> Nueva Difusión
                </h3>
                
                <form method="POST">
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-400 mb-1">Destinatarios</label>
                            <select name="target" class="w-full bg-dark-900 border border-dark-700 rounded-lg p-2.5 text-white focus:border-brand-500 transition">
                                <option value="all">👥 Todos los Usuarios (Global)</option>
                                <option value="vip" disabled>💎 Solo Usuarios VIP (Proximamente)</option>
                                <option value="staff" disabled>🛡️ Solo Staff (Proximamente)</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-400 mb-1">Título de la Alerta</label>
                            <input type="text" name="title" required placeholder="Ej: ¡Nuevo Evento en Vivo!" 
                                class="w-full bg-dark-900 border border-dark-700 rounded-lg p-2.5 text-white placeholder-gray-600 focus:border-brand-500 transition">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-400 mb-1">Mensaje</label>
                            <textarea name="message" rows="4" required placeholder="Escribe el contenido de la notificación..." 
                                class="w-full bg-dark-900 border border-dark-700 rounded-lg p-2.5 text-white placeholder-gray-600 focus:border-brand-500 transition"></textarea>
                        </div>
                        
                        <div class="pt-4 flex justify-end">
                            <button type="submit" class="bg-gradient-to-r from-brand-600 to-indigo-600 hover:from-brand-500 hover:to-indigo-500 text-white font-bold py-3 px-8 rounded-xl shadow-lg shadow-brand-500/20 transition transform hover:scale-[1.02]">
                                <i class="fas fa-paper-plane mr-2"></i> Enviar Ahora
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- History / Stats -->
        <div class="space-y-6">
             <div class="bg-dark-800 rounded-2xl border border-dark-700 shadow-xl p-6">
                <h3 class="text-sm font-bold text-gray-400 uppercase tracking-wider mb-4">Historial Reciente</h3>
                
                <div class="space-y-4">
                    <!-- Mock History Items -->
                    <div class="bg-dark-900 rounded-lg p-3 border border-dark-700 border-l-4 border-l-brand-500">
                        <p class="text-white font-bold text-sm">Mantenimiento Programado</p>
                        <p class="text-xs text-gray-500 mt-1">Hace 2 días • Enviado a Todos</p>
                    </div>

                    <div class="bg-dark-900 rounded-lg p-3 border border-dark-700 border-l-4 border-l-green-500">
                        <p class="text-white font-bold text-sm">¡Regalo de Bienvenida!</p>
                        <p class="text-xs text-gray-500 mt-1">Hace 1 semana • Enviado a Todos</p>
                    </div>
                </div>
                 <button class="w-full mt-4 text-xs text-brand-400 hover:text-brand-300 font-medium">Ver todo el historial</button>
            </div>

            <div class="bg-gradient-to-br from-indigo-900 to-purple-900 rounded-2xl p-6 text-white relative overflow-hidden">
                <div class="relative z-10">
                    <h3 class="text-2xl font-bold">Tips</h3>
                    <p class="text-sm text-indigo-200 mt-2">Usa títulos cortos y llamativos. Las notificaciones globales tienen un 40% más de apertura si incluyen emojis.</p>
                </div>
                <i class="fas fa-lightbulb absolute -bottom-4 -right-4 text-9xl text-white opacity-5"></i>
            </div>
        </div>
    </div>
</div>

<?php renderAdminFooter(); ?>
