<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>

<?php
/*
|--------------------------------------------------------------------------
| Kaiteki Student Portal - Calificaciones
|--------------------------------------------------------------------------
| Ruta sugerida:
| /crm/application/views/themes/perfex/views/califications.php
|
| Espera recibir desde Clients.php:
| $grades = [
|   [
|     'course' => [...],
|     'grades' => [... respuesta de gradereport_user_get_grade_items ...]
|   ]
| ];
|--------------------------------------------------------------------------
*/

$grades = isset($grades) && is_array($grades) ? $grades : [];

$is_active = function ($segment) {
    $uri = uri_string();

    if ($segment === 'home') {
        return $uri === 'clients' || $uri === 'clients/';
    }

    return strpos($uri, $segment) !== false;
};

$format_grade = function ($value) {
    if ($value === null || $value === '' || $value === '-') {
        return '-';
    }

    if (is_numeric($value)) {
        return rtrim(rtrim(number_format((float) $value, 2, '.', ''), '0'), '.');
    }

    return strip_tags((string) $value);
};

$get_grade_items = function ($grade_response) {
    if (!is_array($grade_response)) {
        return [];
    }

    if (isset($grade_response['usergrades'][0]['gradeitems']) && is_array($grade_response['usergrades'][0]['gradeitems'])) {
        return $grade_response['usergrades'][0]['gradeitems'];
    }

    if (isset($grade_response[0]['usergrades'][0]['gradeitems']) && is_array($grade_response[0]['usergrades'][0]['gradeitems'])) {
        return $grade_response[0]['usergrades'][0]['gradeitems'];
    }

    if (isset($grade_response['gradeitems']) && is_array($grade_response['gradeitems'])) {
        return $grade_response['gradeitems'];
    }

    return [];
};
?>

<style>
:root {
    --kaiteki-blue: #082E7A;
    --kaiteki-teal: #009A97;
    --kaiteki-green: #007F4F;
    --kaiteki-bg: #F4F8FB;
    --kaiteki-text: #1F2937;
}

.kaiteki-layout {
    max-width: 1280px;
    margin: 0 auto;
    display: grid;
    grid-template-columns: 260px 1fr;
    gap: 38px;
    align-items: start;
}

.kaiteki-sidebar {
    background: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 14px;
    box-shadow: 0 8px 28px rgba(15, 23, 42, .07);
    overflow: hidden;
    margin-top: 18px;
}

.kaiteki-sidebar a {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 17px 18px;
    color: #2b2b2b !important;
    font-weight: 800;
    font-size: 15px;
    text-decoration: none !important;
    border-bottom: 1px solid #f2f2f2;
}

.kaiteki-sidebar a:last-child {
    border-bottom: none;
}

.kaiteki-sidebar a i {
    color: #c9c9c9;
    font-size: 16px;
}

.kaiteki-sidebar a.active,
.kaiteki-sidebar a:hover {
    background: linear-gradient(135deg, var(--kaiteki-blue), var(--kaiteki-teal));
    color: #fff !important;
}

.kaiteki-sidebar a.active i,
.kaiteki-sidebar a:hover i {
    color: #fff;
}

.kaiteki-wrapper {
    max-width: 1000px;
    margin: 0 auto;
}

.kaiteki-title {
    text-align: center;
    font-size: 32px;
    font-weight: 900;
    margin: 10px 0 35px;
    color: var(--kaiteki-blue);
}

.kaiteki-card {
    background: #fff;
    border-radius: 18px;
    padding: 28px;
    box-shadow: 0 8px 28px rgba(15, 23, 42, .07);
    border: 1px solid #eef2f7;
    margin-bottom: 25px;
}

.kaiteki-course-head {
    display: flex;
    justify-content: space-between;
    gap: 18px;
    align-items: center;
    margin-bottom: 20px;
    border-bottom: 1px solid #eef2f7;
    padding-bottom: 18px;
}

.kaiteki-course-title {
    font-size: 21px;
    font-weight: 900;
    color: var(--kaiteki-blue);
    margin: 0;
}

.kaiteki-course-code {
    background: #E7F8F2;
    color: var(--kaiteki-green);
    padding: 7px 13px;
    border-radius: 999px;
    font-weight: 800;
    font-size: 12px;
    white-space: nowrap;
}

.kaiteki-table {
    width: 100%;
    border-collapse: collapse;
}

.kaiteki-table th {
    background: #F4F8FB;
    color: #4b5563;
    font-weight: 900;
    padding: 14px 16px;
    text-align: left;
}

.kaiteki-table td {
    padding: 14px 16px;
    border-bottom: 1px solid #f1f5f9;
    color: #374151;
    vertical-align: middle;
}

.kaiteki-table tr:last-child td {
    border-bottom: none;
}

.kaiteki-item-name {
    font-weight: 800;
    color: #111827;
}

.kaiteki-grade {
    display: inline-block;
    min-width: 70px;
    text-align: center;
    background: #E7F8F2;
    color: var(--kaiteki-green);
    border-radius: 999px;
    padding: 7px 12px;
    font-weight: 900;
}

.kaiteki-grade-muted {
    background: #f3f4f6;
    color: #6b7280;
}

.kaiteki-empty {
    text-align: center;
    padding: 36px 22px;
    color: #6b7280;
    background: #fff;
    border: 1px dashed #cbd5e1;
    border-radius: 16px;
    font-weight: 700;
}

.kaiteki-mobile-menu-btn {
    display: none;
    width: 100%;
    border: 0;
    background: linear-gradient(135deg, var(--kaiteki-blue), var(--kaiteki-teal));
    color: #fff;
    padding: 14px 18px;
    border-radius: 12px;
    font-weight: 900;
    font-size: 15px;
    margin-bottom: 16px;
    text-align: left;
}

.kaiteki-mobile-menu-btn i {
    float: right;
    margin-top: 3px;
}

.kaiteki-sidebar-mobile-title {
    display: none;
}

@media(max-width: 1000px) {
    .kaiteki-layout {
        display: block !important;
        width: 100% !important;
        max-width: 100% !important;
        padding: 0 12px !important;
    }

    .kaiteki-mobile-menu-btn {
        display: block !important;
    }

    .kaiteki-sidebar {
        display: none;
        width: 100% !important;
        margin: 0 0 20px 0 !important;
    }

    .kaiteki-sidebar.kaiteki-sidebar-open {
        display: block !important;
    }

    .kaiteki-sidebar-mobile-title {
        display: block;
        padding: 14px 18px;
        font-weight: 900;
        color: #111827;
        background: #f8fafc;
        border-bottom: 1px solid #eef2f7;
    }

    .kaiteki-wrapper {
        width: 100% !important;
        max-width: 100% !important;
    }

    .kaiteki-table {
        display: block;
        width: 100%;
        overflow-x: auto;
        white-space: nowrap;
        -webkit-overflow-scrolling: touch;
    }
}

@media(max-width: 650px) {
    .kaiteki-title {
        font-size: 26px;
    }

    .kaiteki-card {
        padding: 20px;
    }

    .kaiteki-course-head {
        display: block;
    }

    .kaiteki-course-code {
        display: inline-block;
        margin-top: 10px;
    }
}
</style>

<div class="kaiteki-layout">

    <button type="button" class="kaiteki-mobile-menu-btn" onclick="kaitekiToggleSidebar(this)">
        Menú del estudiante <i class="fa fa-bars"></i>
    </button>

    <aside class="kaiteki-sidebar">
        <div class="kaiteki-sidebar-mobile-title">Portal del Estudiante</div>

        <a href="<?= site_url('clients'); ?>" class="<?= $is_active('home') ? 'active' : ''; ?>">
            <span>Escritorio</span><i class="fa fa-home"></i>
        </a>

        <a href="<?= site_url('clients/invoices'); ?>" class="<?= $is_active('clients/invoices') ? 'active' : ''; ?>">
            <span>Pagos</span><i class="fa fa-dollar-sign"></i>
        </a>

        <a href="<?= site_url('clients/profile'); ?>" class="<?= $is_active('clients/profile') ? 'active' : ''; ?>">
            <span>Información del Estudiante</span><i class="fa fa-user"></i>
        </a>

        <a href="<?= site_url('clients/files'); ?>" class="<?= $is_active('clients/files') ? 'active' : ''; ?>">
            <span>Documentos</span><i class="fa fa-file-text"></i>
        </a>

        <a href="<?= site_url('clients/tickets'); ?>" class="<?= $is_active('clients/tickets') ? 'active' : ''; ?>">
            <span>Ticket de soporte</span><i class="fa fa-paperclip"></i>
        </a>

        <a href="<?= site_url('clients/account'); ?>" class="<?= $is_active('clients/account') ? 'active' : ''; ?>">
            <span>Detalles de la cuenta</span><i class="fa fa-user-circle"></i>
        </a>

        <a href="<?= site_url('clients/califications'); ?>" class="<?= $is_active('clients/califications') ? 'active' : ''; ?>">
            <span>Calificaciones</span><i class="fa fa-table"></i>
        </a>

        <a href="<?= site_url('authentication/logout'); ?>">
            <span>Salir</span><i class="fa fa-sign-out-alt"></i>
        </a>
    </aside>

    <main>
        <div class="kaiteki-wrapper">
            <h2 class="kaiteki-title">Calificaciones</h2>

            <?php if (!empty($grades)) { ?>
                <?php foreach ($grades as $course_grade) { ?>
                    <?php
                        $course = isset($course_grade['course']) && is_array($course_grade['course']) ? $course_grade['course'] : [];
                        $items  = $get_grade_items($course_grade['grades'] ?? []);

                        $course_name = $course['fullname'] ?? $course['displayname'] ?? $course['shortname'] ?? 'Curso';
                        $course_code = $course['shortname'] ?? '';
                    ?>

                    <div class="kaiteki-card">
                        <div class="kaiteki-course-head">
                            <h3 class="kaiteki-course-title"><?= e($course_name); ?></h3>
                            <?php if (!empty($course_code)) { ?>
                                <span class="kaiteki-course-code"><?= e($course_code); ?></span>
                            <?php } ?>
                        </div>

                        <?php if (!empty($items)) { ?>
                            <table class="kaiteki-table">
                                <thead>
                                    <tr>
                                        <th>Actividad / Evaluación</th>
                                        <th>Calificación</th>
                                        <th>Rango</th>
                                        <th>Porcentaje</th>
                                        <th>Retroalimentación</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($items as $item) { ?>
                                        <?php
                                            $item_name = $item['itemname'] ?? $item['itemmodule'] ?? 'Calificación';
                                            $grade_raw = $item['graderaw'] ?? $item['gradeformatted'] ?? $item['grade'] ?? '-';
                                            $range     = $item['rangeformatted'] ?? (($item['grademin'] ?? '') . ' - ' . ($item['grademax'] ?? ''));
                                            $percent   = $item['percentageformatted'] ?? $item['percentage'] ?? '-';
                                            $feedback  = $item['feedback'] ?? $item['feedbackformatted'] ?? '-';

                                            $grade_is_empty = ($grade_raw === null || $grade_raw === '' || $grade_raw === '-');
                                        ?>
                                        <tr>
                                            <td class="kaiteki-item-name"><?= e($item_name); ?></td>
                                            <td>
                                                <span class="kaiteki-grade <?= $grade_is_empty ? 'kaiteki-grade-muted' : ''; ?>">
                                                    <?= e($format_grade($grade_raw)); ?>
                                                </span>
                                            </td>
                                            <td><?= e($format_grade($range)); ?></td>
                                            <td><?= e($format_grade($percent)); ?></td>
                                            <td><?= e($format_grade($feedback)); ?></td>
                                        </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        <?php } else { ?>
                            <div class="kaiteki-empty">
                                Este curso aún no tiene calificaciones disponibles.
                            </div>
                        <?php } ?>
                    </div>
                <?php } ?>
            <?php } else { ?>
                <div class="kaiteki-empty">
                    No hay calificaciones disponibles todavía. Cuando tus docentes registren notas en Moodle, aparecerán aquí.
                </div>
            <?php } ?>
        </div>
    </main>
</div>

<script>
function kaitekiToggleSidebar(btn) {
    var layout = btn.closest('.kaiteki-layout');
    if (!layout) return;
    var sidebar = layout.querySelector('.kaiteki-sidebar');
    if (!sidebar) return;
    sidebar.classList.toggle('kaiteki-sidebar-open');
    var icon = btn.querySelector('i');
    if (icon) {
        icon.className = sidebar.classList.contains('kaiteki-sidebar-open') ? 'fa fa-times' : 'fa fa-bars';
    }
}
</script>