<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../includes/helpers.php';
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: students.php');
    exit;
}

// Prevent admin from deleting themselves
if ($user_id == $_SESSION['user_id']) {
    header('Location: students.php?error=cannot_delete_self');
    exit;
}

// Get user details for confirmation
$stmt = $pdo->prepare("SELECT u.*, r.name as role_name FROM users u JOIN roles r ON u.role_id = r.id WHERE u.id = ?");
$stmt->execute([$user_id]);
$user_data = $stmt->fetch();

if (!$user_data || $user_data['role_name'] !== 'alumno') {
    header('Location: students.php');
    exit;
}

$message = '';
$confirm = isset($_GET['confirm']) ? $_GET['confirm'] : '';

if ($confirm == 'yes') {
    try {
        // Start transaction
        $pdo->beginTransaction();

        // Delete from students table (soft delete if column exists)
        try {
            $stmt = $pdo->prepare("UPDATE students SET deleted_at = NOW() WHERE user_id = ?");
            $stmt->execute([$user_id]);
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), 'Unknown column') !== false) {
                // Column doesn't exist, just mark user as deleted
            } else {
                throw $e;
            }
        }

        // Delete user (soft delete if column exists)
        try {
            $stmt = $pdo->prepare("UPDATE users SET deleted_at = NOW() WHERE id = ?");
            $stmt->execute([$user_id]);
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), 'Unknown column') !== false) {
                // Column doesn't exist, use direct delete
                $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
                $stmt->execute([$user_id]);
            } else {
                throw $e;
            }
        }

        // Delete photo file if exists
        if ($user_data['photo'] && file_exists('../' . $user_data['photo'])) {
            unlink('../' . $user_data['photo']);
        }

        $pdo->commit();
        header('Location: ' . route_url('admin_students') . '?success=student_deleted');
        exit;

    } catch (Exception $e) {
        $pdo->rollBack();
        $message = 'Error deleting student: ' . $e->getMessage();
    }
}

$page_title = 'Borrar Alumno - ' . htmlspecialchars($user_data['first_name'] . ' ' . $user_data['last_name']);

$content = '
<div class="row">
    <div class="col-md-6">
        <div class="card card-danger">
            <div class="card-header">
                <h3 class="card-title text-black">Borrar Alumno</h3>
            </div>
            <div class="card-body">
                ' . ($message ? '<div class="alert alert-danger">' . $message . '</div>' : '') . '
                <div class="alert alert-warning">
                    <h5><i class="icon fas fa-exclamation-triangle"></i> Warning!</h5>
                    Estas a punto de eliminar al alumno:
                    <br><br>
                    <strong>' . htmlspecialchars($user_data['first_name'] . ' ' . $user_data['last_name']) . '</strong> (' . htmlspecialchars($user_data['username']) . ').
                    <br><br>
                    Esta acción no se puede deshacer y también eliminará:
                    <ul>
                        <li>Toda la información del alumno</li>
                        <li>Todas las solicitudes de empleo de trabajo de este alumno</li>
                        <li>Foto de perfil (si la hay)</li>
                    </ul>
                </div>
                <div class="text-center">
                    <img src="' . ((isset($user_data['photo']) && $user_data['photo'] && file_exists(BASE_PATH . '/' . $user_data['photo'])) ? url($user_data['photo']) : url('assets/img/avatar.png')) . '" class="img-fluid rounded-circle mb-3" style="width: 80px; height: 80px; object-fit: cover;" alt="User Photo">
                    <h4>' . htmlspecialchars($user_data['first_name'] . ' ' . $user_data['last_name']) . '</h4>
                    <p class="text-muted">' . htmlspecialchars($user_data['username']) . ' - Alumno</p>
                </div>
            </div>
            <div class="card-footer">
                <a href="' . url('admin/students/delete/' . $user_id . '?confirm=yes') . '" class="btn btn-danger" onclick="return confirm(\'¿Estás completamente seguro de que deseas eliminar a este alumno? Esta acción no se puede deshacer.\')">
                    <i class="fas fa-trash"></i> Si, Borrar Alumno
                </a>
                <a href="students.php" class="btn btn-secondary float-right">
                    <i class="fas fa-arrow-left"></i> Volver
                </a>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Información del alumno</h3>
            </div>
            <div class="card-body">
                <dl class="row">
                    <dt class="col-sm-4">Nombre Completo:</dt>
                    <dd class="col-sm-8">' . htmlspecialchars($user_data['first_name'] . ' ' . $user_data['last_name']) . '</dd>

                    <dt class="col-sm-4">Username:</dt>
                    <dd class="col-sm-8">' . htmlspecialchars($user_data['username']) . '</dd>

                    <dt class="col-sm-4">Email:</dt>
                    <dd class="col-sm-8">' . htmlspecialchars($user_data['email']) . '</dd>

                    <dt class="col-sm-4">Fecha de registro:</dt>
                    <dd class="col-sm-8">' . date('F d, Y', strtotime($user_data['created_at'])) . '</dd>
                </dl>
            </div>
        </div>
    </div>
</div>';

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