@extends('admin.layouts.app')

@section('title', $title)
@section('page_title', $title)

@section('content')
    <style>
        .obs-wrap { background:#efefef; border:1px solid #d0d0d0; padding:14px; }
        .obs-title { margin:0 0 12px; color:#00607f; font-size:var(--fs-title-global); font-weight:800; }
        .obs-toolbar { display:flex; gap:8px; align-items:center; justify-content:space-between; flex-wrap:wrap; margin-bottom:10px; }
        .obs-btn {
            border:1px solid #0e6f88; background:#2196d9; color:#fff;
            font-size:var(--fs-button-global); font-weight:700; padding:6px 12px; text-decoration:none; display:inline-block;
            cursor:pointer;
        }
        .obs-search { display:flex; gap:6px; align-items:center; }
        .obs-search input { width:280px; max-width:70vw; }
        .obs-new { border:1px solid #9fb0b8; background:#f8fcfe; padding:10px; margin-bottom:12px; display:none; }
        .obs-new.show { display:block; }
        .obs-new-grid { display:grid; grid-template-columns: 180px 1fr; gap:8px; align-items:center; }
        .obs-new-grid textarea { min-height:80px; resize:vertical; }
        .obs-total { margin:8px 0; font-size:var(--fs-total-global); }
        .obs-note {
            margin: 0 0 10px;
            padding: 8px 10px;
            border: 1px solid #8fb7c9;
            background: #eaf6fc;
            color: #0e5f82;
            font-size: var(--fs-table-cell-global);
        }
        .obs-status {
            margin: 0 0 10px;
            padding: 8px 10px;
            border: 1px solid #79b88e;
            background: #e8f8ee;
            color: #1d6b3b;
            font-size: var(--fs-table-cell-global);
            font-weight: 700;
        }
        .obs-table { width:100%; border-collapse:collapse; }
        .obs-table th, .obs-table td { border:1px solid #9aabb5; padding:7px 8px; vertical-align:top; }
        .obs-table th { background:#d5dddd; font-size:var(--fs-table-head-global); }
        .obs-table td { font-size:var(--fs-table-cell-global); background:#fff; }
        .obs-table tbody tr:nth-child(even) td { background:#ccdbdd; }
        .obs-asunto { white-space:normal; line-height:1.35; text-align:left; }
        .obs-asunto .asunto-item {
            display: grid;
            grid-template-columns: 22px 1fr;
            column-gap: 6px;
            align-items: start;
            margin-bottom: 3px;
        }
        .obs-asunto .asunto-k { font-weight: 700; text-align: left; }
        .obs-asunto .asunto-v { text-align: justify; text-justify: inter-word; }
        .obs-docente { width:190px; }
        .obs-actions { margin-top:6px; display:inline-flex; align-items:center; gap:6px; flex-wrap:nowrap; }
        .obs-actions form { margin:0; display:inline-flex; }
        .obs-icon-btn {
            width:26px; height:26px; display:inline-flex; align-items:center; justify-content:center;
            border:1px solid #9d2f2f; background:#cf3f3f; color:#fff; cursor:pointer; padding:0;
            font-size:14px; line-height:1;
        }
    </style>

    <div class="obs-wrap">
        <h2 class="obs-title">Registros De Desempeno Academico</h2>

        @if(session('status'))
            <div class="obs-status">{{ session('status') }}</div>
        @endif

        <div class="obs-toolbar">
            <button type="button" class="obs-btn" id="btnNuevoRegistro">+ Nuevo Registro</button>
            <form class="obs-search" method="GET">
                <input type="hidden" name="annio" value="{{ (int) $annio }}">
                <input type="text" name="q" value="{{ $q }}" placeholder="Filtra por estudiante o asunto">
                <button type="submit" class="obs-btn" style="background:#0b7285;border-color:#0b7285;">Buscar</button>
            </form>
        </div>

        @if(!empty($isDocente))
            <div class="obs-note">Mostrando estudiantes de tu carga academica.</div>
        @endif

        <div class="obs-new" id="panelNuevoRegistro">
            <form method="POST" action="{{ route('admin.observador.registro_academico.store') }}" enctype="multipart/form-data">
                @csrf
                <div class="obs-new-grid">
                    <label><strong>Año</strong></label>
                    <input type="number" name="annio" value="{{ (int) $annio }}" min="2000" max="2100" required>

                    <label><strong>Periodo</strong></label>
                    <select name="periodo_id" required>
                        @foreach($periodos as $p)
                            <option value="{{ (int) $p->id }}">{{ trim((string) ($p->label ?: $p->periodo)) }}</option>
                        @endforeach
                    </select>

                    <label><strong>Fecha</strong></label>
                    <input type="date" name="fecha" value="{{ now()->format('Y-m-d') }}" required>

                    <label><strong>Estudiante</strong></label>
                    <select name="estudiante_id" required>
                        <option value="">(Seleccione uno)</option>
                        @foreach($students as $s)
                            <option value="{{ (int) $s->id }}">
                                {{ $s->full_name }} {{ $s->salon !== '' ? ('- '.$s->salon) : '' }} [{{ $s->contabilidad_id ?: $s->id }}]
                            </option>
                        @endforeach
                    </select>

                    <label><strong>Fortalezas</strong></label>
                    <textarea name="fortalezas"></textarea>

                    <label><strong>Dificultades</strong></label>
                    <textarea name="dificultades"></textarea>

                    <label><strong>Compromisos</strong></label>
                    <textarea name="compromisos"></textarea>

                    <label><strong>Evidencia</strong></label>
                    <input type="file" name="evidencia" accept=".jpg,.jpeg,.png,.pdf">
                </div>
                <div style="margin-top:10px;text-align:right;">
                    <button type="submit" class="obs-btn" style="background:#d9a106;border-color:#9a7300;">Guardar</button>
                </div>
            </form>
        </div>

        <div class="obs-total">Total Registros: {{ $rows->total() }}</div>

        <table class="obs-table ui-table">
            <thead>
            <tr>
                <th style="width:150px;">Registro</th>
                <th style="width:280px;">Estudiante</th>
                <th>Asunto</th>
                <th class="obs-docente">Acudiente / Docente</th>
            </tr>
            </thead>
            <tbody>
            @forelse($rows as $r)
                <tr>
                    <td>
                        {{ $r->fecha ?: '-' }}<br>
                        {{ (int) $r->annio }}-P{{ (int) $r->periodo_id }}
                    </td>
                    <td>
                        {{ mb_strtoupper((string) ($r->estudiante ?: 'SIN ESTUDIANTE')) }}<br>
                        {{ $r->salon ?: '-' }} [{{ (int) $r->estudiante_id }}]
                    </td>
                    <td class="obs-asunto">
                        @if(trim((string) $r->fortalezas) !== '')
                            <div class="asunto-item">
                                <span class="asunto-k">F:</span>
                                <span class="asunto-v">{{ trim((string) $r->fortalezas) }}</span>
                            </div>
                        @endif
                        @if(trim((string) $r->dificultades) !== '')
                            <div class="asunto-item">
                                <span class="asunto-k">D:</span>
                                <span class="asunto-v">{{ trim((string) $r->dificultades) }}</span>
                            </div>
                        @endif
                        @if(trim((string) $r->compromisos) !== '')
                            <div class="asunto-item">
                                <span class="asunto-k">C:</span>
                                <span class="asunto-v">{{ trim((string) $r->compromisos) }}</span>
                            </div>
                        @endif
                    </td>
                    <td class="obs-docente">
                        Acudiente: {{ trim((string) ($r->acudiente ?: 'sin evidencia')) }}<br>
                        @php
                            $dirCursos = $directorCursosByUser[(int) ($r->created_by ?? 0)] ?? [];
                        @endphp
                        Docente: {{ mb_strtoupper((string) ($r->docente ?: 'SIN DOCENTE')) }}@if(!empty($dirCursos)) - Director(a): {{ implode(', ', $dirCursos) }}@endif<br>
                        @if(!empty($r->foto_acudiente))
                            <a href="{{ asset($r->foto_acudiente) }}" target="_blank">Evidencia</a><br>
                        @endif
                        <div class="obs-actions">
                            <a href="{{ route('admin.observador.registro_academico.edit', ['id' => (int) $r->id]) }}" class="obs-btn" style="padding:4px 8px;background:#b8d4b8;border-color:#7aa37a;color:#1b3d1b;">Editar</a>
                            @if(!empty($canDeleteRegistroAcademico))
                                <form method="POST" action="{{ route('admin.observador.registro_academico.delete', ['id' => (int) $r->id]) }}" onsubmit="return confirm('Eliminar este registro? Esta accion no se puede deshacer.');">
                                    @csrf
                                    <button type="submit" class="obs-icon-btn" title="Eliminar registro" aria-label="Eliminar registro">&#128465;</button>
                                </form>
                            @endif
                        </div>
                    </td>
                </tr>
            @empty
                <tr><td colspan="4">No hay registros de desempeno academico.</td></tr>
            @endforelse
            </tbody>
        </table>

        <div class="pagination" style="margin-top:10px;">
            {{ $rows->links('pagination::bootstrap-4') }}
        </div>
    </div>

    <script>
        (function () {
            var btn = document.getElementById('btnNuevoRegistro');
            var panel = document.getElementById('panelNuevoRegistro');
            if (btn && panel) {
                btn.addEventListener('click', function () {
                    panel.classList.toggle('show');
                });
            }
        })();
    </script>
@endsection
