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

// 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) {
    header('Location: users.php');
    exit;
}

// Get role-specific information
$role_info = [];
switch ($user_data['role_name']) {
    case 'empresa':
        $stmt = $pdo->prepare("SELECT * FROM companies WHERE user_id = ?");
        $stmt->execute([$user_id]);
        $role_info = $stmt->fetch();
        break;
    case 'alumno':
        $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]);
        $role_info = $stmt->fetch();
        break;
    case 'profesor':
        $stmt = $pdo->prepare("SELECT * FROM teachers WHERE user_id = ?");
        $stmt->execute([$user_id]);
        $role_info = $stmt->fetch();
        break;
    case 'egresado':
        $stmt = $pdo->prepare("SELECT g.*, c.name as career_name FROM graduates g LEFT JOIN careers c ON g.career_id = c.id WHERE g.user_id = ?");
        $stmt->execute([$user_id]);
        $role_info = $stmt->fetch();
        break;
}

$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']);

    if (empty($username) || empty($email)) {
        $error = 'Se requieren nombre de usuario y correo electrónico.';
    } 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 = '../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 role-specific information
                switch ($user_data['role_name']) {
                    case 'empresa':
                        $stmt = $pdo->prepare("UPDATE companies SET company_name = ?, website = ?, phone = ?, address = ? WHERE user_id = ?");
                        $stmt->execute([
                            $_POST['company_name'] ?? '',
                            $_POST['website'] ?? '',
                            $_POST['phone'] ?? '',
                            $_POST['address'] ?? '',
                            $user_id
                        ]);
                        break;
                    case 'alumno':
                        $stmt = $pdo->prepare("UPDATE students SET career_id = ?, dni = ?, birth_date = ?, address = ?, phone = ?, graduation_year = ?, resume = ? WHERE user_id = ?");
                        $graduation_year = !empty($_POST['graduation_year']) ? (int)$_POST['graduation_year'] : null;
                        $birth_date = !empty($_POST['birth_date']) ? $_POST['birth_date'] : null;
                        $stmt->execute([
                            $_POST['career_id'] ?? null,
                            $_POST['dni'] ?? null,
                            $birth_date,
                            $_POST['address'] ?? null,
                            $_POST['phone'] ?? null,
                            $graduation_year,
                            $_POST['resume'] ?? '',
                            $user_id
                        ]);
                        break;
                    case 'profesor':
                        $stmt = $pdo->prepare("UPDATE teachers SET career_id = ?, bio = ?, dni = ?, birth_date = ?, address = ?, phone = ? WHERE user_id = ?");
                        $birth_date = !empty($_POST['birth_date']) ? $_POST['birth_date'] : null;
                        $stmt->execute([
                            $_POST['career_id'] ?? null,
                            $_POST['bio'] ?? '',
                            $_POST['dni'] ?? null,
                            $birth_date,
                            $_POST['address'] ?? null,
                            $_POST['phone'] ?? null,
                            $user_id,
                        ]);
                        break;
                    case 'egresado':
                        // Check if the new columns exist in the graduates table
                        try {
                            $stmt = $pdo->prepare("UPDATE graduates SET career_id = ?, dni = ?, birth_date = ?, address = ?, phone = ?, graduation_year = ?, resume = ? WHERE user_id = ?");
                            $graduation_year = !empty($_POST['graduation_year']) ? (int)$_POST['graduation_year'] : null;
                            $birth_date = !empty($_POST['birth_date']) ? $_POST['birth_date'] : null;
                            $stmt->execute([
                                $_POST['career_id'] ?? null,
                                $_POST['dni'] ?? null,
                                $birth_date,
                                $_POST['address'] ?? null,
                                $_POST['phone'] ?? null,
                                $graduation_year,
                                $_POST['resume'] ?? '',
                                $user_id
                            ]);
                        } catch (PDOException $e) {
                            // If columns don't exist yet, update only the existing columns
                            if (strpos($e->getMessage(), 'Unknown column') !== false) {
                                $stmt = $pdo->prepare("UPDATE graduates SET career_id = ?, graduation_year = ?, resume = ? WHERE user_id = ?");
                                $graduation_year = !empty($_POST['graduation_year']) ? (int)$_POST['graduation_year'] : null;
                                $stmt->execute([
                                    $_POST['career_id'] ?? null,
                                    $graduation_year,
                                    $_POST['resume'] ?? '',
                                    $user_id
                                ]);
                            } else {
                                throw $e; // Re-throw if it's a different error
                            }
                        }
                        break;
                }
                $success = 'Usuario actualizado con éxito.';
                // 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();
            } else {
                $error = 'No se pudo actualizar el usuario.';
            }
        }
    }
}

// Get careers for student, teacher, and graduate roles
$careers = [];
if (in_array($user_data['role_name'], ['alumno', 'profesor', 'egresado'])) {
    $careers = $pdo->query("SELECT * FROM careers ORDER BY name")->fetchAll();
}

$display_name = htmlspecialchars($user_data['first_name'] . ' ' . $user_data['last_name']);
if ($user_data['role_name'] == 'empresa' && !empty($role_info['company_name'])) {
    $display_name = htmlspecialchars($role_info['company_name']);
}
$role_display = ucfirst($user_data['role_name']);
$page_title = 'Editar ' . $role_display . ' - ' . $display_name;

if ($user_data['role_name'] == 'alumno') {
    $cancel_href = 'students.php';
} elseif ($user_data['role_name'] == 'egresado') {
    $cancel_href = 'graduates.php';
} elseif ($user_data['role_name'] == 'profesor') {
    $cancel_href = 'teachers.php';
} else {
    $cancel_href = 'view-user.php?id=' . $user_id;
}

$content = '
<div class="row">
    <div class="col-md-8">
        <div class="card card-primary">
            <div class="card-header">
                <h3 class="card-title">Editar Usuario</h3>
                <div class="card-tools">
                    <a href="view-user.php?id=' . $user_id . '" class="btn btn-info btn-sm"><i class="fas fa-eye"></i> Ver detalles</a>
                </div>
            </div>
            <form method="post" enctype="multipart/form-data">
                <div class="card-body">
                    ' . ($error ? '<div class="alert alert-danger">' . $error . '</div>' : '') . '
                    ' . ($success ? '<div class="alert alert-success">' . $success . '</div>' : '') . '
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="username">Username</label>
                                <input type="text" class="form-control" id="username" name="username" value="' . htmlspecialchars($user_data['username']) . '" required>
                            </div>
                            <div class="form-group">
                                <label for="email">Email</label>
                                <input type="email" class="form-control" id="email" name="email" value="' . htmlspecialchars($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="' . htmlspecialchars($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="' . htmlspecialchars($user_data['last_name'] ?? '') . '">
                            </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">Leave empty to keep current photo. Max 2MB, JPG/PNG/GIF only.</small>
                            </div>
                        </div>
                        <div class="col-md-6">';

// Add role-specific fields
switch ($user_data['role_name']) {
    case 'empresa':
        $content .= '<div class="form-group">
                            <label for="company_name">Razón social</label>
                            <input type="text" class="form-control" id="company_name" name="company_name" value="' . htmlspecialchars($role_info['company_name'] ?? '') . '">
                        </div>
                        <div class="form-group">
                            <label for="website">Website</label>
                            <input type="url" class="form-control" id="website" name="website" value="' . htmlspecialchars($role_info['website'] ?? '') . '">
                        </div>
                        <div class="form-group">
                            <label for="phone">Telefóno</label>
                            <input type="tel" class="form-control" id="phone" name="phone" value="' . htmlspecialchars($role_info['phone'] ?? '') . '">
                        </div>
                        <div class="form-group">
                            <label for="address">Dirección</label>
                            <textarea class="form-control" id="address" name="address" rows="3">' . htmlspecialchars($role_info['address'] ?? '') . '</textarea>
                        </div>';
        break;
    case 'alumno':
        $content .= '<div class="form-group">
                            <label for="career_id">Programa de Estudio</label>
                            <select class="form-control" id="career_id" name="career_id">
                                <option value="">Seleccionar programa</option>';
        foreach ($careers as $career) {
            $selected = ($role_info['career_id'] == $career['id']) ? 'selected' : '';
            $content .= '<option value="' . $career['id'] . '" ' . $selected . '>' . htmlspecialchars($career['name']) . '</option>';
        }
        $content .= '</select>
                        </div>
                        <div class="form-group">
                            <label for="dni">DNI</label>
                            <input type="text" class="form-control" id="dni" name="dni" value="' . htmlspecialchars($role_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="' . htmlspecialchars($role_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">' . htmlspecialchars($role_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="' . htmlspecialchars($role_info['phone'] ?? '') . '" placeholder="Número de teléfono">
                        </div>
                        <div class="form-group">
                            <label for="graduation_year">Año de Egreso</label>
                            <input type="number" class="form-control" id="graduation_year" name="graduation_year" min="1950" max="' . date('Y') . '" value="' . htmlspecialchars($role_info['graduation_year'] ?? '') . '" placeholder="ej. 2023">
                        </div>
                        <div class="form-group">
                            <label for="resume">Resumen/CV</label>
                            <textarea class="form-control" id="resume" name="resume" rows="3" placeholder="Antecedentes profesionales, logros, etc.">' . htmlspecialchars($role_info['resume'] ?? '') . '</textarea>
                        </div>';
        break;
    case 'profesor':
        $content .= '<div class="form-group">
                             <label for="teacher_career_id">Programa de Estudio</label>
                             <select class="form-control" id="teacher_career_id" name="career_id">
                                 <option value="">Select Career</option>';
        foreach ($careers as $career) {
            $selected = ($role_info['career_id'] == $career['id']) ? 'selected' : '';
            $content .= '<option value="' . $career['id'] . '" ' . $selected . '>' . htmlspecialchars($career['name']) . '</option>';
        }
        $content .= '</select>
                         </div>
                         <div class="form-group">
                             <label for="dni">DNI</label>
                             <input type="text" class="form-control" id="dni" name="dni" value="' . htmlspecialchars($role_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="' . htmlspecialchars($role_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">' . htmlspecialchars($role_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="' . htmlspecialchars($role_info['phone'] ?? '') . '" placeholder="Número de teléfono">
                         </div>
                         <div class="form-group">
                             <label for="bio">Bio</label>
                             <textarea class="form-control" id="bio" name="bio" rows="4" placeholder="Brief biography">' . htmlspecialchars($role_info['bio'] ?? '') . '</textarea>
                         </div>';
        break;
    case 'egresado':
        $content .= '<div class="form-group">
                             <label for="graduate_career_id">Programa de Estudio</label>
                             <select class="form-control" id="graduate_career_id" name="career_id">
                                 <option value="">Seleccionar programa</option>';
        foreach ($careers as $career) {
            $selected = ($role_info['career_id'] == $career['id']) ? 'selected' : '';
            $content .= '<option value="' . $career['id'] . '" ' . $selected . '>' . htmlspecialchars($career['name']) . '</option>';
        }
        $content .= '</select>
                         </div>
                         <div class="form-group">
                             <label for="dni">DNI</label>
                             <input type="text" class="form-control" id="dni" name="dni" value="' . htmlspecialchars($role_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="' . htmlspecialchars($role_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">' . htmlspecialchars($role_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="' . htmlspecialchars($role_info['phone'] ?? '') . '" placeholder="Número de teléfono">
                         </div>
                         <div class="form-group">
                             <label for="graduation_year">Año de Egreso</label>
                             <input type="number" class="form-control" id="graduation_year" name="graduation_year" min="1950" max="' . date('Y') . '" value="' . htmlspecialchars($role_info['graduation_year'] ?? '') . '" placeholder="e.g., 2023">
                         </div>
                         <div class="form-group">
                             <label for="resume">Resumen/CV</label>
                             <textarea class="form-control" id="resume" name="resume" rows="3" placeholder="Professional background, achievements, etc.">' . htmlspecialchars($role_info['resume'] ?? '') . '</textarea>
                         </div>';
        break;
}

$content .= '</div>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">Actualizar Usuario</button>
                    <a href="' . $cancel_href . '" class="btn btn-secondary">Cancelar</a>
                </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">
                ' . ((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>') . '
            </div>
        </div>
    </div>
</div>';

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