<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once '../includes/db.php';
require_once '../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.');
}

// Get student's languages
$stmt = $pdo->prepare("SELECT * FROM student_languages WHERE student_id = ? ORDER BY created_at DESC");
$stmt->execute([$student['id']]);
$student_languages = $stmt->fetchAll();

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['add_language'])) {
        $language_name = trim($_POST['language_name']);
        $proficiency_level = trim($_POST['proficiency_level']);
        $obtained_date = !empty($_POST['obtained_date']) ? $_POST['obtained_date'] : null;
        $expiry_date = !empty($_POST['expiry_date']) ? $_POST['expiry_date'] : null;
        $issuing_organization = trim($_POST['issuing_organization']);

        if (empty($language_name)) {
            $error = 'El nombre del idioma es obligatorio.';
        } else {
            // Handle certificate upload
            $certificate_path = '';
            if (isset($_FILES['certificate_file']) && $_FILES['certificate_file']['error'] == 0) {
                $allowed_types = ['application/pdf'];
                if (in_array($_FILES['certificate_file']['type'], $allowed_types) && $_FILES['certificate_file']['size'] <= 10485760) { // 10MB
                    $upload_dir = '../uploads/language_certificates/';
                    if (!is_dir($upload_dir)) {
                        mkdir($upload_dir, 0777, true);
                    }

                    $file_extension = pathinfo($_FILES['certificate_file']['name'], PATHINFO_EXTENSION);
                    $file_name = 'lang_cert_' . $student['id'] . '_' . time() . '_' . uniqid() . '.' . $file_extension;
                    $file_path = $upload_dir . $file_name;

                    if (move_uploaded_file($_FILES['certificate_file']['tmp_name'], $file_path)) {
                        $certificate_path = 'uploads/language_certificates/' . $file_name;
                    } else {
                        $error = 'No se pudo cargar el archivo del certificado.';
                    }
                } else {
                    $error = 'Tipo de archivo no válido o archivo demasiado grande. Solo se permiten archivos PDF de menos de 10 MB.';
                }
            }

            if (!$error) {
                $stmt = $pdo->prepare("INSERT INTO student_languages (student_id, language_name, proficiency_level, certificate_file, obtained_date, expiry_date, issuing_organization) VALUES (?, ?, ?, ?, ?, ?, ?)");
                if ($stmt->execute([$student['id'], $language_name, $proficiency_level, $certificate_path, $obtained_date, $expiry_date, $issuing_organization])) {
                    $success = 'Idioma agregado exitosamente.';
                    // Refresh languages list
                    $stmt = $pdo->prepare("SELECT * FROM student_languages WHERE student_id = ? ORDER BY created_at DESC");
                    $stmt->execute([$student['id']]);
                    $student_languages = $stmt->fetchAll();
                } else {
                    $error = 'No se pudo agregar el idioma.';
                }
            }
        }
    } elseif (isset($_POST['edit_language'])) {
        $language_id = $_POST['language_id'];
        $language_name = trim($_POST['language_name']);
        $proficiency_level = trim($_POST['proficiency_level']);
        $obtained_date = !empty($_POST['obtained_date']) ? $_POST['obtained_date'] : null;
        $expiry_date = !empty($_POST['expiry_date']) ? $_POST['expiry_date'] : null;
        $issuing_organization = trim($_POST['issuing_organization']);

        if (empty($language_name)) {
            $error = 'El nombre del idioma es obligatorio.';
        } else {
            // Handle certificate upload (optional for edit)
            $certificate_path = '';
            if (isset($_FILES['certificate_file']) && $_FILES['certificate_file']['error'] == 0) {
                $allowed_types = ['application/pdf'];
                if (in_array($_FILES['certificate_file']['type'], $allowed_types) && $_FILES['certificate_file']['size'] <= 10485760) { // 10MB
                    $upload_dir = '../uploads/language_certificates/';
                    if (!is_dir($upload_dir)) {
                        mkdir($upload_dir, 0777, true);
                    }

                    // Get old certificate to delete if exists
                    $stmt = $pdo->prepare("SELECT certificate_file FROM student_languages WHERE id = ? AND student_id = ?");
                    $stmt->execute([$language_id, $student['id']]);
                    $old_lang = $stmt->fetch();
                    if ($old_lang && $old_lang['certificate_file'] && file_exists('../' . $old_lang['certificate_file'])) {
                        unlink('../' . $old_lang['certificate_file']);
                    }

                    $file_extension = pathinfo($_FILES['certificate_file']['name'], PATHINFO_EXTENSION);
                    $file_name = 'lang_cert_' . $student['id'] . '_' . time() . '_' . uniqid() . '.' . $file_extension;
                    $file_path = $upload_dir . $file_name;

                    if (move_uploaded_file($_FILES['certificate_file']['tmp_name'], $file_path)) {
                        $certificate_path = 'uploads/language_certificates/' . $file_name;
                    } else {
                        $error = 'No se pudo cargar el archivo del certificado.';
                    }
                } else {
                    $error = 'Tipo de archivo no válido o archivo demasiado grande. Solo se permiten archivos PDF de menos de 10 MB.';
                }
            }

            if (!$error) {
                if ($certificate_path) {
                    $stmt = $pdo->prepare("UPDATE student_languages SET language_name = ?, proficiency_level = ?, certificate_file = ?, obtained_date = ?, expiry_date = ?, issuing_organization = ? WHERE id = ? AND student_id = ?");
                    $params = [$language_name, $proficiency_level, $certificate_path, $obtained_date, $expiry_date, $issuing_organization, $language_id, $student['id']];
                } else {
                    $stmt = $pdo->prepare("UPDATE student_languages SET language_name = ?, proficiency_level = ?, obtained_date = ?, expiry_date = ?, issuing_organization = ? WHERE id = ? AND student_id = ?");
                    $params = [$language_name, $proficiency_level, $obtained_date, $expiry_date, $issuing_organization, $language_id, $student['id']];
                }

                if ($stmt->execute($params)) {
                    $success = 'Idioma actualizado exitosamente.';
                    // Refresh languages list
                    $stmt = $pdo->prepare("SELECT * FROM student_languages WHERE student_id = ? ORDER BY created_at DESC");
                    $stmt->execute([$student['id']]);
                    $student_languages = $stmt->fetchAll();
                } else {
                    $error = 'No se pudo actualizar el idioma.';
                }
            }
        }
    } elseif (isset($_POST['delete_language'])) {
        $language_id = $_POST['language_id'];

        // Get certificate file path before deleting
        $stmt = $pdo->prepare("SELECT certificate_file FROM student_languages WHERE id = ? AND student_id = ?");
        $stmt->execute([$language_id, $student['id']]);
        $lang = $stmt->fetch();

        if ($lang && $lang['certificate_file'] && file_exists('../' . $lang['certificate_file'])) {
            unlink('../' . $lang['certificate_file']);
        }

        $stmt = $pdo->prepare("DELETE FROM student_languages WHERE id = ? AND student_id = ?");
        if ($stmt->execute([$language_id, $student['id']])) {
            $success = 'Idioma eliminado exitosamente.';
            // Refresh languages list
            $stmt = $pdo->prepare("SELECT * FROM student_languages WHERE student_id = ? ORDER BY created_at DESC");
            $stmt->execute([$student['id']]);
            $student_languages = $stmt->fetchAll();
        } else {
            $error = 'No se pudo eliminar el idioma.';
        }
    }
}

$page_title = 'Idiomas';

$content = '
<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title"></h3>
                <div class="card-tools">
                    <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addLanguageModal">
                        <i class="fas fa-plus"></i> Agregar idioma
                    </button>
                </div>
            </div>
            <div class="card-body">
                ' . ($error ? '<div class="alert alert-danger">' . $error . '</div>' : '') . '
                ' . ($success ? '<div class="alert alert-success">' . $success . '</div>' : '') . '

                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>Idioma</th>
                                <th>Nivel</th>
                                <th>Certificado</th>
                                <th>Institución</th>
                                <th>Fecha de Obtención</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>';

if (count($student_languages) > 0) {
    foreach ($student_languages as $lang) {
        $certificate_link = $lang['certificate_file'] ?
            '<a href="../' . htmlspecialchars($lang['certificate_file']) . '" target="_blank" class="btn btn-sm btn-info"><i class="fas fa-file-pdf"></i> Ver</a>' :
            '<span class="text-muted">No certificate</span>';

        $content .= '<tr>
            <td><strong>' . htmlspecialchars($lang['language_name']) . '</strong></td>
            <td>' . htmlspecialchars($lang['proficiency_level'] ?: 'Not specified') . '</td>
            <td>' . $certificate_link . '</td>
            <td>' . htmlspecialchars($lang['issuing_organization'] ?: 'Not specified') . '</td>
            <td>' . ($lang['obtained_date'] ? date('d/m/Y', strtotime($lang['obtained_date'])) : 'No especificado') . '</td>
            <td>
                <div class="btn-group">
                    <button type="button" class="btn btn-warning btn-sm" onclick="editLanguage(' . $lang['id'] . ', \'' . addslashes($lang['language_name']) . '\', \'' . addslashes($lang['proficiency_level']) . '\', \'' . addslashes($lang['issuing_organization']) . '\', \'' . $lang['obtained_date'] . '\', \'' . $lang['expiry_date'] . '\')">
                        <i class="fas fa-edit"></i> Editar
                    </button>&nbsp;&nbsp;
                    <form method="post" style="display: inline;">
                        <input type="hidden" name="language_id" value="' . $lang['id'] . '">
                        <button type="submit" name="delete_language" class="btn btn-danger btn-sm" onclick="return confirm(\'Estás seguro de que deseas eliminar este idioma?\')">
                            <i class="fas fa-trash"></i> Borrar
                        </button>
                    </form>
                </div>
            </td>
        </tr>';
    }
} else {
    $content .= '<tr><td colspan="6" class="text-center text-muted">No languages added yet. Click "Add Language" to get started.</td></tr>';
}

$content .= '</tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Language Modal -->
<div class="modal fade" id="addLanguageModal" tabindex="-1" role="dialog" aria-labelledby="addLanguageModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addLanguageModalLabel">Agregar Nuevo Idioma</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post" enctype="multipart/form-data" id="languageForm">
                <input type="hidden" name="language_id" id="edit_language_id">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="language_name">Nombre del idioma *</label>
                                <input type="text" class="form-control" id="language_name" name="language_name" required>
                            </div>
                            <div class="form-group">
                                <label for="proficiency_level">Nivel</label>
                                <select class="form-control" id="proficiency_level" name="proficiency_level">
                                    <option value="">Select Level</option>
                                    <option value="Basico">Basico</option>
                                    <option value="Intermedio">Intermedio</option>
                                    <option value="Avanzado">Avanzado</option>

                                </select>
                            </div>
                            <div class="form-group">
                                <label for="issuing_organization">Institución</label>
                                <input type="text" class="form-control" id="issuing_organization" name="issuing_organization" placeholder="e.g., Cambridge, Goethe Institute, DELE">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="obtained_date">Fecha de Obtención</label>
                                <input type="date" class="form-control" id="obtained_date" name="obtained_date">
                            </div>
                            <div class="form-group">
                                <label for="expiry_date">Fecha de Expiración</label>
                                <input type="date" class="form-control" id="expiry_date" name="expiry_date">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="certificate_file">Certificate archivo (PDF)</label>
                        <input type="file" class="form-control" id="certificate_file" name="certificate_file" accept=".pdf">
                        <small class="form-text text-muted">Upload your language certificate or proficiency test results. Max 10MB.</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="add_language" id="submitBtn" class="btn btn-primary">Agregar Idioma</button>
                </div>
            </form>
        </div>
    </div>
</div>

</div>

<!-- Add Bootstrap and jQuery for modal functionality -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<script>
function editLanguage(id, name, level, organization, obtainedDate, expiryDate) {
    document.getElementById(\'edit_language_id\').value = id;
    document.getElementById(\'language_name\').value = name;
    document.getElementById(\'proficiency_level\').value = level;
    document.getElementById(\'issuing_organization\').value = organization;
    document.getElementById(\'obtained_date\').value = obtainedDate;
    document.getElementById(\'expiry_date\').value = expiryDate;
    document.getElementById(\'submitBtn\').name = \'edit_language\';
    document.getElementById(\'submitBtn\').textContent = \'Actualizar Idioma\';
    document.getElementById(\'addLanguageModalLabel\').textContent = \'Editar Idioma\';
    $(\'#addLanguageModal\').modal(\'show\');
}

$(\'#addLanguageModal\').on(\'hidden.bs.modal\', function () {
    document.getElementById(\'languageForm\').reset();
    document.getElementById(\'edit_language_id\').value = \'\';
    document.getElementById(\'submitBtn\').name = \'add_language\';
    document.getElementById(\'submitBtn\').textContent = \'Agregar Idioma\';
    document.getElementById(\'addLanguageModalLabel\').textContent = \'Agregar Nuevo Idioma\';
});
</script>
';

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