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

check_role('administrador');

$user = get_logged_in_user();

$user_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$user_id) {
    header('Location: ' . route_url('admin_graduates'));
    exit;
}

// Get current status
$stmt = $pdo->prepare("SELECT g.status FROM graduates g JOIN users u ON g.user_id = u.id WHERE u.id = ? AND u.role_id = (SELECT id FROM roles WHERE name = 'egresado')");
$stmt->execute([$user_id]);
$graduate = $stmt->fetch();

if (!$graduate) {
    header('Location: ' . route_url('admin_graduates'));
    exit;
}

// Toggle status
$new_status = $graduate['status'] == 'active' ? 'inactive' : 'active';

$stmt = $pdo->prepare("UPDATE graduates SET status = ? WHERE user_id = ?");
$stmt->execute([$new_status, $user_id]);

// Send notification to graduate
$notification_title = $new_status == 'active' ? 'Cuenta Activada' : 'Cuenta Desactivada';
$notification_message = $new_status == 'active'
    ? 'Su cuenta de egresado ha sido activada. Ahora puede acceder a todas las funcionalidades del sistema.'
    : 'Su cuenta de egresado ha sido desactivada temporalmente. Contacte al administrador para más información.';

$stmt = $pdo->prepare("INSERT INTO notifications (user_id, title, message, type, career_id) VALUES (?, ?, ?, ?, (SELECT career_id FROM graduates WHERE user_id = ?))");
$stmt->execute([$user_id, $notification_title, $notification_message, $new_status == 'active' ? 'success' : 'danger', $user_id]);

header('Location: ' . route_url('admin_graduates'));
exit;
?>