<?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();

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

if (!$user_id) {
    header('Location: users.php');
    exit;
}

// Prevent admin from deleting themselves
if ($user_id == $_SESSION['user_id']) {
    header('Location: users.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) {
    header('Location: users.php');
    exit;
}

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

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

        // Delete from role-specific tables first
        switch ($user_data['role_name']) {
            case 'empresa':
                // Check if deleted_at column exists, if not, use direct delete
                try {
                    $stmt = $pdo->prepare("UPDATE companies SET deleted_at = NOW() WHERE user_id = ?");
                    $stmt->execute([$user_id]);
                    // Also delete related jobs and applications
                    $stmt = $pdo->prepare("UPDATE jobs SET deleted_at = NOW() WHERE company_id = (SELECT id FROM companies WHERE user_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 applications WHERE job_id IN (SELECT id FROM jobs WHERE company_id = (SELECT id FROM companies WHERE user_id = ?))");
                        $stmt->execute([$user_id]);
                        $stmt = $pdo->prepare("DELETE FROM jobs WHERE company_id = (SELECT id FROM companies WHERE user_id = ?)");
                        $stmt->execute([$user_id]);
                        $stmt = $pdo->prepare("DELETE FROM companies WHERE user_id = ?");
                        $stmt->execute([$user_id]);
                    } else {
                        throw $e;
                    }
                }
                break;
            case 'alumno':
                // Applications are kept, but the user is hidden
                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;
                    }
                }
                break;
            case 'egresado':
                // Applications are kept, but the user is hidden
                try {
                    $stmt = $pdo->prepare("UPDATE graduates 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;
                    }
                }
                break;
            case 'profesor':
                try {
                    $stmt = $pdo->prepare("UPDATE teachers 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;
                    }
                }
                break;
        }

        // Delete user
        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();
        // Redirect based on user role
        $redirect_url = 'users.php';
        if ($user_data['role_name'] === 'alumno') {
            $redirect_url = 'students.php';
        }
        header('Location: ' . $redirect_url . '?success=user_deleted');
        exit;

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

$page_title = 'Borrar Usuario - ' . 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">Borrar Usuario</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 usuario:
                    <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>Todos los datos del usuario y la información del perfil</li>
                        <li>Foto de perfil (si la hay)</li>';

switch ($user_data['role_name']) {
    case 'empresa':
        $content .= '<li>Toda la información de la empresa</li>
                        <li>Todas las ofertas de empleo de esta empresa</li>
                        <li>Todas las solicitudes para sus puestos de trabajo</li>';
        break;
    case 'alumno':
        $content .= '<li>Toda la información del alumno</li>
                        <li>Todas las solicitudes de empleo de trabajo de este alumno</li>';
        break;
    case 'egresado':
        $content .= '<li>Toda la información del egresado</li>
                        <li>Todas las solicitudes de empleo de trabajo de este egresado</li>';
        break;
    case 'profesor':
        $content .= '<li>Toda la información del profesor</li>';
        break;
}

$content .= '</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']) . ' - ' . ucfirst($user_data['role_name']) . '</p>
                </div>
            </div>
            <div class="card-footer">
                <a href="' . route_url('admin_delete_user', ['id' => $user_id, 'confirm' => 'yes']) . '" class="btn btn-danger" onclick="return confirm(\'Estás completamente seguro de que deseas eliminar a este usuario? Esta acción no se puede deshacer.\')">
                    <i class="fas fa-trash"></i> Si, Borrar Usuario
                </a>
                <a href="' . route_url('admin_students') . '" class="btn btn-secondary float-right">
                    <i class="fas fa-times"></i> Cancel
                </a>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Información del usuario</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">Role:</dt>
                    <dd class="col-sm-8">' . ucfirst($user_data['role_name']) . '</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';
?>