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

check_role('alumno');

$user = get_logged_in_user();

// Get student
$stmt = $pdo->prepare("SELECT * FROM students WHERE user_id = ?");
$stmt->execute([$user['id']]);
$student = $stmt->fetch();

if (!$student) {
    die('Student 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']);
    $dni = trim($_POST['dni']);
    $birth_date = !empty($_POST['birth_date']) ? $_POST['birth_date'] : null;
    $phone = trim($_POST['phone']);
    $address = trim($_POST['address']);
    $career_id = !empty($_POST['career_id']) ? $_POST['career_id'] : null;
    $graduation_year = !empty($_POST['graduation_year']) ? $_POST['graduation_year'] : null;
    $resume = trim($_POST['resume']);
    $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 student
                    $stmt = $pdo->prepare("UPDATE students SET dni = ?, birth_date = ?, phone = ?, address = ?, career_id = ?, graduation_year = ?, resume = ? WHERE user_id = ?");
                    if ($stmt->execute([$dni, $birth_date, $phone, $address, $career_id, $graduation_year, $resume, $user['id']])) {
                        $success = 'Perfil actualizado exitosamente.';
                        // Refresh data
                        $user = get_logged_in_user();
                        $stmt = $pdo->prepare("SELECT * FROM students WHERE user_id = ?");
                        $stmt->execute([$user['id']]);
                        $student = $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 student statistics
$stats = [];
$stmt = $pdo->prepare("SELECT COUNT(*) as total_applications FROM applications WHERE applicant_id = ? AND applicant_type = 'student'");
$stmt->execute([$student['id']]);
$stats['total_applications'] = $stmt->fetch()['total_applications'];

$stmt = $pdo->prepare("SELECT COUNT(*) as accepted_applications FROM applications WHERE applicant_id = ? AND applicant_type = 'student' AND status = 'accepted'");
$stmt->execute([$student['id']]);
$stats['accepted_applications'] = $stmt->fetch()['accepted_applications'];

$stmt = $pdo->prepare("SELECT COUNT(*) as pending_applications FROM applications WHERE applicant_id = ? AND applicant_type = 'student' AND status = 'pending'");
$stmt->execute([$student['id']]);
$stats['pending_applications'] = $stmt->fetch()['pending_applications'];

$page_title = 'Perfil del Alumno';

$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="Student Photo">
                </div>
                <h3 class="profile-username text-center">' . htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) . '</h3>
                <p class="text-muted text-center">Student</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</b> <a class="float-right">' . htmlspecialchars($student['career_id'] ? array_column($careers, 'name', 'id')[$student['career_id']] : 'Not specified') . '</a>
                    </li>
                    <li class="list-group-item">
                        <b>Graduación</b> <a class="float-right">' . htmlspecialchars($student['graduation_year'] ?: 'Not specified') . '</a>
                    </li>
                    <li class="list-group-item">
                        <b>Registro</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">Estadísticas de Postulantes</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_applications'] . '</h3>
                                <p>Total Applications</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="small-box bg-success">
                            <div class="inner">
                                <h3>' . $stats['accepted_applications'] . '</h3>
                                <p>Accepted</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row text-center mt-2">
                    <div class="col-12">
                        <div class="small-box bg-warning">
                            <div class="inner">
                                <h3>' . $stats['pending_applications'] . '</h3>
                                <p>Pending</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</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">Nombre Completo *</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="dni">DNI</label>
                                <input type="text" class="form-control" id="dni" name="dni" value="' . htmlspecialchars($student['dni'] ?? '') . '" maxlength="20">
                                <small class="form-text text-muted"></small>
                            </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($student['birth_date'] ?? '') . '">
                            </div>
                            <div class="form-group">
                                <label for="phone">Celular</label>
                                <input type="text" class="form-control" id="phone" name="phone" value="' . htmlspecialchars($student['phone'] ?? '') . '" maxlength="20">
                                <small class="form-text text-muted"></small>
                            </div>
                            <div class="form-group">
                                <label for="address">Dirección</label>
                                <textarea class="form-control" id="address" name="address" rows="2" placeholder="Your complete address...">' . htmlspecialchars($student['address'] ?? '') . '</textarea>
                            </div>
                            <div class="form-group">
                                <label for="username">Username</label>
                                <input type="text" class="form-control" id="username" value="' . htmlspecialchars($user['username']) . '" readonly>
                                <small class="form-text text-muted"></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="">Select Career</option>';
foreach ($careers as $career) {
    $selected = ($student['career_id'] == $career['id']) ? 'selected' : '';
    $content .= '<option value="' . $career['id'] . '" ' . $selected . '>' . htmlspecialchars($career['name']) . '</option>';
}
$content .= '</select>
                            </div>
                            <div class="form-group">
                                <label for="graduation_year">Expectativa de Graduación</label>
                                <input type="number" class="form-control" id="graduation_year" name="graduation_year" min="2020" max="2030" value="' . htmlspecialchars($student['graduation_year'] ?? '') . '">
                            </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">Max 2MB, JPG/PNG/GIF.</small>
                            </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"></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"></small>
                            </div>
                            <div class="form-group">
                                <label for="confirm_password">Confirmar 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="resume">Resume/CV</label>
                                <textarea class="form-control" id="resume" name="resume" rows="4" placeholder="Cuéntanos sobre tu formación académica, experiencia y logros...">' . htmlspecialchars($student['resume'] ?? '') . '</textarea>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">Actualizar Perfil</button>
                    <a href="' . route_url('student_dashboard') . '" class="btn btn-secondary">Volver al Dashboard</a>
                </div>
            </form>
        </div>

    </div>
</div>';

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