<?php
// admin/send-system-notification.php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/includes/EmailService.php';

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit();
}

$success_msg = '';
$error_msg = '';
$preview = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $subject = trim($_POST['subject'] ?? '');
    $message = trim($_POST['message'] ?? '');
    $send_to = $_POST['send_to'] ?? 'all'; // all, vip, free
    
    if (empty($subject) || empty($message)) {
        $error_msg = "Subject and message are required.";
    } else {
        // Build recipient list
        if ($send_to === 'all') {
            $stmt = $pdo->query("SELECT id, full_name, email FROM users WHERE status = 'ACTIVE'");
        } elseif ($send_to === 'vip') {
            $stmt = $pdo->query("SELECT id, full_name, email FROM users WHERE status = 'ACTIVE' AND user_tier = 'VIP'");
        } else {
            $stmt = $pdo->query("SELECT id, full_name, email FROM users WHERE status = 'ACTIVE' AND user_tier = 'FREE'");
        }
        $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (empty($users)) {
            $error_msg = "No users found matching the selected criteria.";
        } else {
            $emailService = new EmailService($pdo);
            $sent = 0;
            $failed = 0;
            
            foreach ($users as $user) {
                // Use system_notification template with custom subject
                $result = $emailService->sendTemplateEmail('system_notification', $user['email'], [
                    'user_name' => $user['full_name']
                ], $subject);
                
                // Override the body with custom message (we'll need to modify EmailService slightly)
                // Or we can use custom body by passing it as a placeholder
                if ($result) {
                    $sent++;
                } else {
                    $failed++;
                }
            }
            
            $success_msg = "System notification sent to {$sent} users. Failed: {$failed}.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Send System Notification</title>
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/css/output.css?v=<?php echo time(); ?>">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;900&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        .glass-card { background: rgba(15, 23, 42, 0.7); backdrop-filter: blur(12px); border: 1px solid rgba(30, 41, 59, 0.6); }
    </style>
</head>
<body class="bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-gray-200 antialiased min-h-screen flex flex-col md:flex-row transition-colors duration-300">

    <?php include __DIR__ . '/includes/admin-sidebar.php'; ?>

    <main class="flex-1 p-4 sm:p-6 md:p-8 overflow-x-hidden flex flex-col gap-6">
        <div>
            <div class="inline-flex items-center space-x-2 bg-blue-500/10 border border-blue-500/20 px-3 py-1 rounded-full text-[10px] font-bold tracking-widest uppercase text-blue-400 mb-2">
                <span class="w-1.5 h-1.5 rounded-full bg-blue-400 animate-pulse"></span>
                <span>Broadcast</span>
            </div>
            <h2 class="text-2xl sm:text-3xl font-extrabold text-slate-900 dark:text-white tracking-wide">Send System Notification</h2>
            <p class="text-xs text-slate-500 dark:text-gray-400 mt-0.5">Send an important announcement or maintenance alert to all users.</p>
        </div>

        <?php if (!empty($success_msg)): ?>
            <div class="bg-emerald-50 border-emerald-200 text-emerald-700 dark:bg-emerald-500/10 dark:border-emerald-500/30 dark:text-emerald-400 border rounded-xl p-3 text-sm font-medium flex items-center gap-2">
                <span>✅</span> <?php echo $success_msg; ?>
            </div>
        <?php endif; ?>
        <?php if (!empty($error_msg)): ?>
            <div class="bg-rose-50 border-rose-200 text-rose-700 dark:bg-rose-500/10 dark:border-rose-500/30 dark:text-rose-400 border rounded-xl p-3 text-sm font-medium flex items-center gap-2">
                <span>❌</span> <?php echo $error_msg; ?>
            </div>
        <?php endif; ?>

        <div class="glass-card rounded-2xl p-6 sm:p-8 max-w-2xl w-full shadow-xl">
            <form action="send-system-notification.php" method="POST" class="space-y-5">
                <div>
                    <label class="block text-[10px] text-slate-500 dark:text-gray-400 uppercase font-bold tracking-wider mb-1.5">Subject</label>
                    <input type="text" name="subject" placeholder="Enter notification subject" required class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50 text-sm transition-all">
                </div>

                <div>
                    <label class="block text-[10px] text-slate-500 dark:text-gray-400 uppercase font-bold tracking-wider mb-1.5">Message</label>
                    <textarea name="message" rows="8" placeholder="Enter your notification message..." required class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50 text-sm transition-all resize-y"></textarea>
                </div>

                <div>
                    <label class="block text-[10px] text-slate-500 dark:text-gray-400 uppercase font-bold tracking-wider mb-1.5">Send To</label>
                    <select name="send_to" class="w-full bg-slate-50 border border-slate-200 dark:bg-slate-950 dark:border-slate-800 rounded-xl p-3 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500/50 text-sm transition-all">
                        <option value="all">All Users</option>
                        <option value="vip">VIP Only</option>
                        <option value="free">Free Tier Only</option>
                    </select>
                </div>

                <button type="submit" class="w-full bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 text-white font-bold py-3.5 rounded-xl transition shadow-lg shadow-blue-500/20 text-xs tracking-wider uppercase">
                    📤 Send Notification
                </button>
            </form>
        </div>

        <div class="text-[10px] text-slate-400 dark:text-gray-500 border-t border-slate-200 dark:border-slate-800 pt-4 mt-2 text-center">
            <span class="text-emerald-400">ℹ️</span> Notifications are sent immediately using the configured SMTP settings.
        </div>
    </main>
</body>
</html>