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

check_role('profesor');

$user = get_logged_in_user();

// Get teacher
$stmt = $pdo->prepare("SELECT t.*, c.name as career_name FROM teachers t LEFT JOIN careers c ON t.career_id = c.id WHERE t.user_id = ?");
$stmt->execute([$user['id']]);
$teacher = $stmt->fetch();

if (!$teacher) {
    die('Teacher profile not found.');
}

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $department = trim($_POST['department']); // This field seems to be legacy, but we'll keep it for now.
    $career_id = !empty($_POST['career_id']) ? $_POST['career_id'] : null;
    $bio = trim($_POST['bio']);
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    if (empty($first_name) || empty($last_name) || empty($email)) {
        $error = 'Por favor, rellene todos los campos obligatorios.';
    } else {
        // Check if email exists (excluding current user)
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
        $stmt->execute([$email, $user['id']]);
        if ($stmt->fetch()) {
            $error = 'El correo electrónico ya existe.';
        } else {
            // Handle password change
            $update_password = false;
            if (!empty($new_password)) {
                if (empty($current_password)) {
                    $error = 'Se requiere la contraseña actual para cambiar la contraseña.';
                } elseif (!password_verify($current_password, $user['password'])) {
                    $error = 'La contraseña actual es incorrecta.';
                } elseif (strlen($new_password) < 6) {
                    $error = 'La nueva contraseña debe tener al menos 6 caracteres.';
                } elseif ($new_password !== $confirm_password) {
                    $error = 'Las nuevas contraseñas no coinciden.';
                } else {
                    $update_password = true;
                }
            }

            if (!$error) {
                // Handle photo upload
                $photo_path = isset($user['photo']) ? $user['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)) {
                            if (!mkdir($upload_dir, 0755, true)) {
                                $error = 'Error al crear el directorio de carga.';
                            }
                        }

                        if (!$error && is_writable($upload_dir)) {
                            $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;
                            } else {
                                $error = 'No se pudo cargar el archivo de foto.';
                            }
                        } else {
                            $error = 'El directorio de carga no se puede escribir.';
                        }
                    } else {
                        $error = 'Tipo de archivo no válido o demasiado grande. Solo se permiten archivos JPG, PNG y GIF de menos de 2 MB.';
                    }
                }

                if (!$error) {
                    // Update user
                    if ($update_password) {
                        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                        $stmt = $pdo->prepare("UPDATE users SET first_name = ?, last_name = ?, email = ?, password = ?, photo = ? WHERE id = ?");
                        $stmt->execute([$first_name, $last_name, $email, $hashed_password, $photo_path, $user['id']]);
                    } else {
                        $stmt = $pdo->prepare("UPDATE users SET first_name = ?, last_name = ?, email = ?, photo = ? WHERE id = ?");
                        $stmt->execute([$first_name, $last_name, $email, $photo_path, $user['id']]);
                    }

                    // Update teacher
                    $stmt = $pdo->prepare("UPDATE teachers SET department = ?, bio = ?, career_id = ? WHERE user_id = ?");
                    if ($stmt->execute([$department, $bio, $career_id, $user['id']])) {
                        $success = 'Perfil actualizado exitosamente.';
                        // Refresh data
                        $user = get_logged_in_user();
                        $stmt = $pdo->prepare("SELECT t.*, c.name as career_name FROM teachers t LEFT JOIN careers c ON t.career_id = c.id WHERE t.user_id = ?");
                        $stmt->execute([$user['id']]);
                        $teacher = $stmt->fetch();
                    } else {
                        $error = 'No se pudo actualizar el perfil.';
                    }
                }
            }
        }
    }
}

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

// Get teacher statistics
$stats = [];
$stmt = $pdo->prepare("SELECT COUNT(*) as total_students FROM students");
$stmt->execute();
$stats['total_students'] = $stmt->fetch()['total_students'];

$stmt = $pdo->prepare("SELECT COUNT(*) as total_jobs FROM jobs");
$stmt->execute();
$stats['total_jobs'] = $stmt->fetch()['total_jobs'];

$page_title = 'Perfil de Profesor';

$content = '
<div class="row">
    <div class="col-md-4">
        <div class="card card-primary card-outline">
            <div class="card-body box-profile">
                <div class="text-center">
                    <img class="profile-user-img img-fluid img-circle" src="' . ((isset($user['photo']) && $user['photo']) ? '../' . htmlspecialchars($user['photo']) : '../assets/img/avatar.png') . '" alt="Teacher Photo">
                </div>
                <h3 class="profile-username text-center">' . htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) . '</h3>
                <p class="text-muted text-center">Profesor</p>
                <ul class="list-group list-group-unbordered mb-3">
                    <li class="list-group-item">
                        <b>Email</b> <a class="float-right">' . htmlspecialchars($user['email']) . '</a>
                    </li>
                    <li class="list-group-item">
                        <b>Programa de Estudio</b> <a class="float-right">' . htmlspecialchars($teacher['career_name'] ?: 'No especificado') . '</a>
                    </li>
                    
                    <li class="list-group-item">
                        <b>Se unió</b> <a class="float-right">' . date('d M, Y', strtotime($user['created_at'])) . '</a>
                    </li>
                </ul>
            </div>
        </div>
        <p></p>
        <!-- Statistics Card -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Resumen General</h3>
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-6">
                        <div class="small-box bg-info">
                            <div class="inner">
                                <h3>' . $stats['total_students'] . '</h3>
                                <p>Total de Alumnos</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="small-box bg-success">
                            <div class="inner">
                                <h3>' . $stats['total_jobs'] . '</h3>
                                <p>Total de Ofertas</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-8">
        <div class="card card-primary">
            <div class="card-header">
                <h3 class="card-title">Editar Perfil de Profesor</h3>
            </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">
                            <h5>Información Personal</h5>
                            <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['first_name']) . '" required>
                            </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['last_name']) . '" required>
                            </div>
                            <div class="form-group">
                                <label for="email">Email *</label>
                                <input type="email" class="form-control" id="email" name="email" value="' . htmlspecialchars($user['email']) . '" required>
                            </div>
                            <div class="form-group">
                                <label for="username">Usuario</label>
                                <input type="text" class="form-control" id="username" value="' . htmlspecialchars($user['username']) . '" readonly>
                                <small class="form-text text-muted">El usuario no se puede cambiar</small>
                            </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. Max 2MB, JPG/PNG/GIF.</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h5>Información Académica</h5>
                            <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 = ($teacher['career_id'] == $career['id']) ? 'selected' : '';
    $content .= '<option value="' . $career['id'] . '" ' . $selected . '>' . htmlspecialchars($career['name']) . '</option>';
}
$content .= '               </select>
                            </div>
                            <div class="form-group">
                                <label for="department">Departamento</label>
                                <input type="text" class="form-control" id="department" name="department" value="' . htmlspecialchars($teacher['department'] ?? '') . '">
                            </div>

                            <h5>Cambiar Contraseña</h5>
                            <div class="form-group">
                                <label for="current_password">Contraseña Actual</label>
                                <input type="password" class="form-control" id="current_password" name="current_password">
                                <small class="form-text text-muted">Requerido solo si se cambia la contraseña</small>
                            </div>
                            <div class="form-group">
                                <label for="new_password">Nueva Contraseña</label>
                                <input type="password" class="form-control" id="new_password" name="new_password">
                                <small class="form-text text-muted">Dejar vacío para mantener la contraseña actual</small>
                            </div>
                            <div class="form-group">
                                <label for="confirm_password">Confirmar Nueva Contraseña</label>
                                <input type="password" class="form-control" id="confirm_password" name="confirm_password">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-12">
                            <div class="form-group">
                                <label for="bio">Biografía</label>
                                <textarea class="form-control" id="bio" name="bio" rows="4" placeholder="Cuéntanos sobre tu experiencia docente, intereses de investigación y logros...">' . htmlspecialchars($teacher['bio'] ?? '') . '</textarea>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">Actualizar Perfil</button>
                    <a href="dashboard.php" class="btn btn-secondary">Cancelar</a>
                </div>
            </form>
        </div>
        <p></p>
        <!-- Account Information -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Información de la Cuenta</h3>
            </div>
            <div class="card-body">
                <dl class="row">
                    <dt class="col-sm-4">ID de Usuario:</dt>
                    <dd class="col-sm-8">' . $user['id'] . '</dd>

                    <dt class="col-sm-4">Role:</dt>
                    <dd class="col-sm-8">Profesor</dd>

                    <dt class="col-sm-4">Fecha de Registro:</dt>
                    <dd class="col-sm-8">' . date('d M, Y H:i:s', strtotime($user['created_at'])) . '</dd>

                    <dt class="col-sm-4">Última Actualización:</dt>
                    <dd class="col-sm-8">' . ($user['updated_at'] ? date('d M, Y H:i:s', strtotime($user['updated_at'])) : 'Nunca') . '</dd>

                    <dt class="col-sm-4">Estado de la Cuenta:</dt>
                    <dd class="col-sm-8"><span class="badge badge-success">Activo</span></dd>
                </dl>
            </div>
        </div>
    </div>
</div>';

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