<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/helpers.php';

check_role('administrador');

$user = get_logged_in_user();

$page_title = 'Enviar Notificación';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = trim($_POST['title']);
    $message = trim($_POST['message']);
    $type = $_POST['type'];
    $target_careers = isset($_POST['target_careers']) ? $_POST['target_careers'] : [];

    $errors = [];

    if (empty($title)) {
        $errors[] = 'El título es obligatorio.';
    }

    if (empty($message)) {
        $errors[] = 'El mensaje es obligatorio.';
    }

    if (!in_array($type, ['info', 'success', 'warning', 'danger'])) {
        $errors[] = 'Tipo de notificación inválido.';
    }

    if (empty($target_careers)) {
        $errors[] = 'Debe seleccionar al menos una carrera.';
    }

    if (empty($errors)) {
        $notifications_sent = 0;

        // Get user IDs from selected careers (students and graduates)
        $user_ids = [];
        if (!empty($target_careers)) {
            $placeholders = str_repeat('?,', count($target_careers) - 1) . '?';

            // Get students with selected careers
            $stmt = $pdo->prepare("SELECT u.id FROM users u JOIN students s ON u.id = s.user_id WHERE s.career_id IN ($placeholders)");
            $stmt->execute($target_careers);
            $career_students = $stmt->fetchAll(PDO::FETCH_COLUMN);

            // Get graduates with selected careers
            $stmt = $pdo->prepare("SELECT u.id FROM users u JOIN graduates g ON u.id = g.user_id WHERE g.career_id IN ($placeholders)");
            $stmt->execute($target_careers);
            $career_graduates = $stmt->fetchAll(PDO::FETCH_COLUMN);

            $career_users = array_merge($career_students, $career_graduates);
            $user_ids = array_merge($user_ids, $career_users);
        }

        // Remove duplicates
        $user_ids = array_unique($user_ids);

        // Insert notifications
        $stmt = $pdo->prepare("INSERT INTO notifications (user_id, career_id, type, title, message, created_at) VALUES (?, ?, ?, ?, ?, NOW())");

        foreach ($user_ids as $user_id) {
            // Determine career_id for this user (if applicable)
            $career_id = null;
            if (!empty($target_careers)) {
                // If we sent to specific careers, set the career_id
                $career_id = $target_careers[0]; // Use the first career if multiple were selected
            }
            $stmt->execute([$user_id, $career_id, $type, $title, $message]);
            $notifications_sent++;
        }

        $success = "Notificación enviada exitosamente a $notifications_sent usuario(s).";
    }
}

// Get careers for selection
$stmt = $pdo->query("SELECT * FROM careers ORDER BY name");
$all_careers = $stmt->fetchAll();

$content = (isset($success) ? '<div class="alert alert-success">' . $success . '</div>' : '') .
           (isset($errors) && !empty($errors) ? '<div class="alert alert-danger"><ul>' . implode('', array_map(function($error) { return '<li>' . $error . '</li>'; }, $errors)) . '</ul></div>' : '') . '

<div class="row">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Enviar Notificación</h3>
            </div>
            <form method="post">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="title">Título *</label>
                                <input type="text" class="form-control" id="title" name="title" required maxlength="255" value="' . (isset($_POST['title']) ? htmlspecialchars($_POST['title']) : '') . '">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="type">Tipo de Notificación *</label>
                                <select class="form-control" id="type" name="type" required>
                                    <option value="info" ' . (isset($_POST['type']) && $_POST['type'] == 'info' ? 'selected' : '') . '>Información</option>
                                    <option value="success" ' . (isset($_POST['type']) && $_POST['type'] == 'success' ? 'selected' : '') . '>Éxito</option>
                                    <option value="warning" ' . (isset($_POST['type']) && $_POST['type'] == 'warning' ? 'selected' : '') . '>Advertencia</option>
                                    <option value="danger" ' . (isset($_POST['type']) && $_POST['type'] == 'danger' ? 'selected' : '') . '>Peligro</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="message">Mensaje *</label>
                        <textarea class="form-control" id="message" name="message" rows="4" required maxlength="1000">' . (isset($_POST['message']) ? htmlspecialchars($_POST['message']) : '') . '</textarea>
                        <small class="form-text text-muted">Máximo 1000 caracteres.</small>
                    </div>

                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label>Enviar por Programas</label>
                                <div class="border p-3" style="max-height: 200px; overflow-y: auto;">
                                    ' . implode('', array_map(function($career) {
                                        return '<div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="target_careers[]" value="' . $career['id'] . '" id="career_' . $career['id'] . '" ' . (isset($_POST['target_careers']) && in_array($career['id'], $_POST['target_careers']) ? 'checked' : '') . '>
                                            <label class="form-check-label" for="career_' . $career['id'] . '">
                                                ' . htmlspecialchars($career['name']) . '
                                            </label>
                                        </div>';
                                    }, $all_careers)) . '
                                </div>
                                <small class="form-text text-muted">Aplica a alumnos y egresados de estos programas .</small>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-paper-plane"></i> Enviar Notificación
                    </button>
                    <a href="' . route_url('admin_notifications') . '" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Volver a Notificaciones
                    </a>
                </div>
            </form>
        </div>
    </div>

    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Vista Previa</h3>
            </div>
            <div class="card-body">
                <div id="preview-container">
                    <div class="alert alert-info">
                        <h5 id="preview-title">Título de la notificación</h5>
                        <p id="preview-message">Mensaje de la notificación aparecerá aquí...</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Estadísticas</h3>
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-6">
                        <h4 id="total-users">' . $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn() . '</h4>
                        <small>Total Usuarios</small>
                    </div>
                    <div class="col-6">
                        <h4 id="selected-users">0</h4>
                        <small>Seleccionados</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>';

include '../includes/layout.php';
?>

<script>
$(document).ready(function() {
    // Update preview in real-time
    $('#title, #message, #type').on('input change', function() {
        updatePreview();
    });

    // Update selected users count
    $('input[type="checkbox"]').change(function() {
        updateSelectedCount();
    });

    function updatePreview() {
        const title = $('#title').val() || 'Título de la notificación';
        const message = $('#message').val() || 'Mensaje de la notificación aparecerá aquí...';
        const type = $('#type').val();

        $('#preview-title').text(title);
        $('#preview-message').text(message);

        // Update alert class
        const alertEl = $('#preview-container .alert');
        alertEl.removeClass('alert-info alert-success alert-warning alert-danger');
        alertEl.addClass('alert-' + type);
    }

    function updateSelectedCount() {
        const selectedCareers = $('input[name="target_careers[]"]:checked').length;

        // This is a simple count - in reality you might want to calculate unique users
        $('#selected-users').text(selectedCareers);
    }

    // Initialize
    updatePreview();
    updateSelectedCount();
});
</script>