<?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 trainings
$stmt = $pdo->prepare("SELECT * FROM student_trainings WHERE student_id = ? ORDER BY created_at DESC");
$stmt->execute([$student['id']]);
$student_trainings = $stmt->fetchAll();

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['add_training'])) {
        $training_name = trim($_POST['training_name']);
        $institution = trim($_POST['institution']);
        $training_type = $_POST['training_type'];
        $start_date = !empty($_POST['start_date']) ? $_POST['start_date'] : null;
        $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : null;
        $duration_hours = !empty($_POST['duration_hours']) ? (int)$_POST['duration_hours'] : null;

        if (empty($training_name)) {
            $error = 'El nombre de la capacitación 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/training_certificates/';
                    if (!is_dir($upload_dir)) {
                        mkdir($upload_dir, 0777, true);
                    }

                    $file_extension = pathinfo($_FILES['certificate_file']['name'], PATHINFO_EXTENSION);
                    $file_name = 'training_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/training_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_trainings (student_id, training_name, institution, training_type, start_date, end_date, duration_hours, certificate_file) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                if ($stmt->execute([$student['id'], $training_name, $institution, $training_type, $start_date, $end_date, $duration_hours, $certificate_path])) {
                    $success = 'Capacitación agregado exitosamente.';
                    // Refresh trainings list
                    $stmt = $pdo->prepare("SELECT * FROM student_trainings WHERE student_id = ? ORDER BY created_at DESC");
                    $stmt->execute([$student['id']]);
                    $student_trainings = $stmt->fetchAll();
                } else {
                    $error = 'No se pudo agregar la capacitación.';
                }
            }
        }
    } elseif (isset($_POST['edit_training'])) {
        $training_id = $_POST['training_id'];
        $training_name = trim($_POST['training_name']);
        $institution = trim($_POST['institution']);
        $training_type = $_POST['training_type'];
        $start_date = !empty($_POST['start_date']) ? $_POST['start_date'] : null;
        $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : null;
        $duration_hours = !empty($_POST['duration_hours']) ? (int)$_POST['duration_hours'] : null;

        if (empty($training_name)) {
            $error = 'El nombre de la capacitación 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/training_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_trainings WHERE id = ? AND student_id = ?");
                    $stmt->execute([$training_id, $student['id']]);
                    $old_training = $stmt->fetch();
                    if ($old_training && $old_training['certificate_file'] && file_exists('../' . $old_training['certificate_file'])) {
                        unlink('../' . $old_training['certificate_file']);
                    }

                    $file_extension = pathinfo($_FILES['certificate_file']['name'], PATHINFO_EXTENSION);
                    $file_name = 'training_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/training_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_trainings SET training_name = ?, institution = ?, training_type = ?, start_date = ?, end_date = ?, duration_hours = ?, certificate_file = ? WHERE id = ? AND student_id = ?");
                    $params = [$training_name, $institution, $training_type, $start_date, $end_date, $duration_hours, $certificate_path, $training_id, $student['id']];
                } else {
                    $stmt = $pdo->prepare("UPDATE student_trainings SET training_name = ?, institution = ?, training_type = ?, start_date = ?, end_date = ?, duration_hours = ? WHERE id = ? AND student_id = ?");
                    $params = [$training_name, $institution, $training_type, $start_date, $end_date, $duration_hours, $training_id, $student['id']];
                }

                if ($stmt->execute($params)) {
                    $success = 'Capacitación actualizada exitosamente.';
                    // Refresh trainings list
                    $stmt = $pdo->prepare("SELECT * FROM student_trainings WHERE student_id = ? ORDER BY created_at DESC");
                    $stmt->execute([$student['id']]);
                    $student_trainings = $stmt->fetchAll();
                } else {
                    $error = 'No se pudo actualizar la capacitación.';
                }
            }
        }
    } elseif (isset($_POST['delete_training'])) {
        $training_id = $_POST['training_id'];

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

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

        $stmt = $pdo->prepare("DELETE FROM student_trainings WHERE id = ? AND student_id = ?");
        if ($stmt->execute([$training_id, $student['id']])) {
            $success = 'Capacitación eliminada exitosamente.';
            // Refresh trainings list
            $stmt = $pdo->prepare("SELECT * FROM student_trainings WHERE student_id = ? ORDER BY created_at DESC");
            $stmt->execute([$student['id']]);
            $student_trainings = $stmt->fetchAll();
        } else {
            $error = 'No se pudo eliminar la capacitación.';
        }
    }
}

$page_title = 'Mis Capacitaciones y Cursos';

$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="#addTrainingModal">
                        <i class="fas fa-plus"></i> Agregar Capacitacion
                    </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>Nombre de la Capacitación/Curso</th>
                                <th>Tipo</th>
                                <th>Institución/Organización</th>
                                <th>Duración</th>
                                <th>Certificado</th>
                                <th>Fecha de Finalización</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>';

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

        $completion_date = $training['end_date'] ? date('d/m/Y', strtotime($training['end_date'])) :
                           ($training['obtained_date'] ? date('d/m/Y', strtotime($training['obtained_date'])) : 'No especificado');

        $training_type_map = [
            'course' => 'Curso',
            'workshop' => 'Taller',
            'seminar' => 'Seminario',
            'certification' => 'Certificacion',
            'diploma' => 'Diploma',
            'other' => 'Otro'
        ];

        $training_type_display = $training_type_map[$training['training_type']] ?? ucfirst(htmlspecialchars($training['training_type']));


        $content .= '<tr>
            <td><strong>' . htmlspecialchars($training['training_name']) . '</strong></td>
            <td>' . $training_type_display . '</td>
            <td>' . htmlspecialchars($training['institution'] ?: 'No especificado') . '</td>
            <td>' . $duration_text . '</td>
            <td>' . $certificate_link . '</td>
            <td>' . $completion_date . '</td>
            <td>
                <div class="btn-group">
                    <button type="button" class="btn btn-warning btn-sm" onclick="editTraining(' . $training['id'] . ', \'' . addslashes($training['training_name']) . '\', \'' . addslashes($training['training_type']) . '\', \'' . addslashes($training['institution']) . '\', \'' . $training['start_date'] . '\', \'' . $training['end_date'] . '\', ' . ($training['duration_hours'] ?: 'null') . ')">
                        <i class="fas fa-edit"></i> Editar
                    </button>
                    <form method="post" style="display: inline;">
                        <input type="hidden" name="training_id" value="' . $training['id'] . '">
                        <button type="submit" name="delete_training" class="btn btn-danger btn-sm" onclick="return confirm(\'Estás seguro de que deseas eliminar esta capacitación?\')">
                            <i class="fas fa-trash"></i> Borrar
                        </button>
                    </form>
                </div>
            </td>
        </tr>';
    }
} else {
    $content .= '<tr><td colspan="7" class="text-center text-muted">No trainings added yet. Click "Add Training" to get started.</td></tr>';
}

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

<!-- Add Training Modal -->
<div class="modal fade" id="addTrainingModal" tabindex="-1" role="dialog" aria-labelledby="addTrainingModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addTrainingModalLabel">Agregar Nueva Capacitación/Curso</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="post" enctype="multipart/form-data" id="trainingForm">
                <input type="hidden" name="training_id" id="edit_training_id">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="training_name">Nombre de la Capacitación/Curso*</label>
                                <input type="text" class="form-control" id="training_name" name="training_name" required>
                            </div>
                            <div class="form-group">
                                <label for="training_type">Tipo</label>
                                <select class="form-control" id="training_type" name="training_type">
                                    <option value="course">Curso</option>
                                    <option value="workshop">Taller</option>
                                    <option value="seminar">Seminario</option>
                                    <option value="certification">Certificacion</option>
                                    <option value="diploma">Diploma</option>
                                    <option value="other">Otro</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="institution">Institución/Organización</label>
                                <input type="text" class="form-control" id="institution" name="institution" placeholder="e.g., Universidad Nacional, Google, Microsoft">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="start_date">Fecha de inicio</label>
                                <input type="date" class="form-control" id="start_date" name="start_date">
                            </div>
                            <div class="form-group">
                                <label for="end_date">Fecha de fin</label>
                                <input type="date" class="form-control" id="end_date" name="end_date">
                            </div>
                            <div class="form-group">
                                <label for="duration_hours">Duración (horas)</label>
                                <input type="number" class="form-control" id="duration_hours" name="duration_hours" min="1" placeholder="Total de horas de la capacitación">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="certificate_file">Certificado 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 training certificate or completion document. 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_training" id="submitBtn" class="btn btn-primary">Agregar Capacitación</button>
                </div>
            </form>
        </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 editTraining(id, name, type, institution, startDate, endDate, duration) {
    document.getElementById(\'edit_training_id\').value = id;
    document.getElementById(\'training_name\').value = name;
    document.getElementById(\'training_type\').value = type;
    document.getElementById(\'institution\').value = institution;
    document.getElementById(\'start_date\').value = startDate;
    document.getElementById(\'end_date\').value = endDate;
    document.getElementById(\'duration_hours\').value = duration;
    document.getElementById(\'submitBtn\').name = \'edit_training\';
    document.getElementById(\'submitBtn\').textContent = \'Actualizar Capacitación\';
    document.getElementById(\'addTrainingModalLabel\').textContent = \'Editar Capacitación\';
    $(\'#addTrainingModal\').modal(\'show\');
}

$(\'#addTrainingModal\').on(\'hidden.bs.modal\', function () {
    document.getElementById(\'trainingForm\').reset();
    document.getElementById(\'edit_training_id\').value = \'\';
    document.getElementById(\'submitBtn\').name = \'add_training\';
    document.getElementById(\'submitBtn\').textContent = \'Agregar Capacitación\';
    document.getElementById(\'addTrainingModalLabel\').textContent = \'Agregar Nueva Capacitación/Curso\';
});
</script>';

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