<?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;
}

// Get user details
$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;
}

// Get student-specific information
$stmt = $pdo->prepare("SELECT s.*, c.name as career_name FROM students s LEFT JOIN careers c ON s.career_id = c.id WHERE s.user_id = ?");
$stmt->execute([$user_id]);
$student_info = $stmt->fetch();

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $gender = trim($_POST['gender']);
    $career_id = $_POST['career_id'];
    $dni = trim($_POST['dni']);
    $birth_date = $_POST['birth_date'];
    $address = trim($_POST['address']);
    $phone = trim($_POST['phone']);
    $graduation_year = $_POST['graduation_year'];
    $resume = trim($_POST['resume']);

    if (empty($username) || empty($email) || empty($career_id)) {
        $error = 'Se requieren nombre de usuario, correo electrónico y programa de estudio.';
    } else {
        // Check if username or email exists (excluding current user)
        $stmt = $pdo->prepare("SELECT id FROM users WHERE (username = ? OR email = ?) AND id != ?");
        $stmt->execute([$username, $email, $user_id]);
        if ($stmt->fetch()) {
            $error = 'El nombre de usuario o correo electrónico ya existe.';
        } else {
            // Handle photo upload
            $photo_path = $user_data['photo'];
            if (isset($_FILES['photo']) && $_FILES['photo']['error'] == 0) {
                $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
                if (in_array($_FILES['photo']['type'], $allowed_types) && $_FILES['photo']['size'] <= 2097152) { // 2MB
                    $upload_dir = BASE_PATH . '/uploads/photos/';
                    if (!is_dir($upload_dir)) {
                        mkdir($upload_dir, 0777, true);
                    }
                    $file_extension = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
                    $file_name = uniqid() . '.' . $file_extension;
                    $file_path = $upload_dir . $file_name;

                    if (move_uploaded_file($_FILES['photo']['tmp_name'], $file_path)) {
                        // Delete old photo if exists
                        if ($photo_path && file_exists('../' . $photo_path)) {
                            unlink('../' . $photo_path);
                        }
                        $photo_path = 'uploads/photos/' . $file_name;
                    }
                }
            }

            // Update user
            $stmt = $pdo->prepare("UPDATE users SET username = ?, email = ?, first_name = ?, last_name = ?, photo = ? WHERE id = ?");
            if ($stmt->execute([$username, $email, $first_name, $last_name, $photo_path, $user_id])) {
                // Update student information
                $stmt = $pdo->prepare("UPDATE students SET career_id = ?, dni = ?, birth_date = ?, address = ?, phone = ?, graduation_year = ?, resume = ?, gender = ? WHERE user_id = ?");
                $stmt->execute([
                    $career_id,
                    $dni ?: null,
                    $birth_date ?: null,
                    $address ?: null,
                    $phone ?: null,
                    $graduation_year ?: null,
                    $resume ?: '',
                    $gender ?: null,
                    $user_id
                ]);

                $success = 'Alumno actualizado exitosamente.';
                // Refresh user data
                $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();
                // Refresh student info
                $stmt = $pdo->prepare("SELECT s.*, c.name as career_name FROM students s LEFT JOIN careers c ON s.career_id = c.id WHERE s.user_id = ?");
                $stmt->execute([$user_id]);
                $student_info = $stmt->fetch();
            } else {
                $error = 'No se pudo actualizar el alumno.';
            }
        }
    }
}

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

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

$error_alert = $error ? '<div class="alert alert-danger">' . htmlspecialchars($error) . '</div>' : '';
$success_alert = $success ? '<div class="alert alert-success">' . htmlspecialchars($success) . '</div>' : '';

$content = <<<HTML
<div class="row">
    <div class="col-md-8">
        <div class="card card-primary">
            <div class="card-header">
                <h3 class="card-title">Editar Alumno</h3>
            </div>
            <form method="post" enctype="multipart/form-data">
                <div class="card-body">
                    {$error_alert}
                    {$success_alert}
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="username">Nombre de Usuario *</label>
                                <input type="text" class="form-control" id="username" name="username" value="{$user_data['username']}" required>
                            </div>
                            <div class="form-group">
                                <label for="email">Correo Electrónico *</label>
                                <input type="email" class="form-control" id="email" name="email" value="{$user_data['email']}" required>
                            </div>
                            <div class="form-group">
                                <label for="first_name">Nombres</label>
                                <input type="text" class="form-control" id="first_name" name="first_name" value="{$user_data['first_name']}">
                            </div>
                            <div class="form-group">
                                <label for="last_name">Apellidos</label>
                                <input type="text" class="form-control" id="last_name" name="last_name" value="{$user_data['last_name']}">
                            </div>
                            <div class="form-group">
                                <label for="gender">Género</label>
                                <select class="form-control" id="gender" name="gender">
                                    <option value="">Seleccionar género</option>
HTML;

foreach (['Masculino', 'Femenino', 'Otro'] as $gender_option) {
   $selected = ($student_info['gender'] == $gender_option) ? 'selected' : '';
   $content .= '<option value="' . $gender_option . '" ' . $selected . '>' . $gender_option . '</option>';
}

$content .= <<<HTML
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="photo">Foto de perfil</label>
                                <input type="file" class="form-control" id="photo" name="photo" accept="image/*">
                                <small class="form-text text-muted">Dejar vacío para mantener la foto actual. Máx 2MB, JPG/PNG/GIF.</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="career_id">Programa de Estudio *</label>
                                <select class="form-control" id="career_id" name="career_id" required>
                                    <option value="">Seleccionar programa</option>
HTML;

foreach ($careers as $career) {
    $selected = ($student_info['career_id'] == $career['id']) ? 'selected' : '';
    $content .= '<option value="' . $career['id'] . '" ' . $selected . '>' . htmlspecialchars($career['name']) . '</option>';
}

$content .= <<<HTML
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="dni">DNI</label>
                                <input type="text" class="form-control" id="dni" name="dni" value="{$student_info['dni']}" placeholder="Número de DNI">
                            </div>
                            <div class="form-group">
                                <label for="birth_date">Fecha de Nacimiento</label>
                                <input type="date" class="form-control" id="birth_date" name="birth_date" value="{$student_info['birth_date']}">
                            </div>
                            <div class="form-group">
                                <label for="address">Dirección</label>
                                <textarea class="form-control" id="address" name="address" rows="2" placeholder="Dirección completa">{$student_info['address']}</textarea>
                            </div>
                            <div class="form-group">
                                <label for="phone">Teléfono</label>
                                <input type="tel" class="form-control" id="phone" name="phone" value="{$student_info['phone']}" placeholder="Número de teléfono">
                            </div>
                            <div class="form-group">
                                <label for="graduation_year">Año de Graduación Esperado</label>
                                <input type="number" class="form-control" id="graduation_year" name="graduation_year" min="2020" max="2030" value="{$student_info['graduation_year']}" placeholder="ej. 2025">
                            </div>
                            <div class="form-group">
                                <label for="resume">Resumen/CV</label>
                                <textarea class="form-control" id="resume" name="resume" rows="3" placeholder="Antecedentes académicos, logros, etc.">{$student_info['resume']}</textarea>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">Actualizar Alumno</button>
                    <button type="button" onclick="history.back()" class="btn btn-secondary">Volver</button>
                </div>
            </form>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Foto actual</h3>
            </div>
            <div class="card-body text-center">
HTML;

$content .= ((isset($user_data['photo']) && !empty($user_data['photo']) && file_exists(BASE_PATH . '/' . $user_data['photo'])) ? '<img src="' . url($user_data['photo']) . '" class="img-fluid rounded-circle" style="width: 150px; height: 150px; object-fit: cover;" alt="Current Photo">' : '<div class="text-muted"><i class="fas fa-user fa-3x mb-2"></i><br>No hay foto actual</div>');

$content .= <<<HTML
            </div>
        </div>
    </div>
</div>
HTML;

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