<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['usu_id'])) {
    header("Location: ../login.php");
    exit();
}

$bd = new clsbdd();
?>

<div class="row g-4">
    <div class="col-12">
        <div class="card shadow-sm rounded-4 border-0">
            <div class="card-header bg-white p-3 border-0 d-flex align-items-center">
                <div class="bg-primary-subtle text-primary rounded-3 p-2 me-3">
                    <i class="fas fa-chalkboard-teacher fs-4"></i>
                </div>
                <div>
                    <h5 class="fw-bold mb-0" id="form-title">Ficha de Registro de Profesor</h5>
                    <small class="text-muted" id="form-subtitle">Ingrese la información básica y asigne el grupo correspondiente</small>
                </div>
            </div>
            <div class="card-body bg-light-subtle rounded-bottom-4 p-4">
                <form action="controlador/ProfesorController.php?action=guardar" method="POST" id="form-profesor">
                    <input type="hidden" name="prof_id" id="prof_id" value="">

                    <div class="row g-3">
                        <div class="col-md-3">
                            <label class="form-label small fw-bold text-secondary">Cédula / Identificación *</label>
                            <div class="input-group">
                                <span class="input-group-text bg-white border-end-0 text-muted"><i class="fas fa-id-card"></i></span>
                                <input type="text" name="prof_cedula" id="prof_cedula" class="form-control border-start-0 ps-0" placeholder="Ej. 1726354712" required>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label small fw-bold text-secondary">Nombres Completos *</label>
                            <div class="input-group">
                                <span class="input-group-text bg-white border-end-0 text-muted"><i class="fas fa-user"></i></span>
                                <input type="text" name="prof_nombres" id="prof_nombres" class="form-control border-start-0 ps-0" placeholder="Nombres" required>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label small fw-bold text-secondary">Apellidos Completos *</label>
                            <div class="input-group">
                                <span class="input-group-text bg-white border-end-0 text-muted"><i class="fas fa-user"></i></span>
                                <input type="text" name="prof_apellidos" id="prof_apellidos" class="form-control border-start-0 ps-0" placeholder="Apellidos" required>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label small fw-bold text-secondary">Grupo / Clasificación Asignada *</label>
                            <div class="input-group">
                                <span class="input-group-text bg-white border-end-0 text-muted"><i class="fas fa-layer-group"></i></span>
                                <select name="cla_id" id="cla_id" class="form-select border-start-0 ps-0" required>
                                    <option value="">Seleccione un grupo...</option>
                                    <?php 
                                    $res_clas = $bd->ejecutar("SELECT cla_id, cla_categoria, cla_nivel FROM bas_clasificaciones ORDER BY cla_categoria ASC");
                                    if ($res_clas) {
                                        while($row_cla = $res_clas->fetch_assoc()) {
                                            echo "<option value='{$row_cla['cla_id']}'>" . htmlspecialchars($row_cla['cla_categoria'] . " - " . $row_cla['cla_nivel']) . "</option>";
                                        }
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-12 text-end mt-4">
                            <button type="button" class="btn btn-light rounded-pill me-2 fw-bold px-4" id="btn-cancelar" onclick="cancelarEdicion()" style="display: none;">Cancelar</button>
                            <button type="reset" class="btn btn-light rounded-pill me-2 fw-bold px-4" id="btn-limpiar">Limpiar Ficha</button>
                            <button type="submit" class="btn btn-primary rounded-pill fw-bold px-4 shadow-sm" id="btn-submit">
                                <i class="fas fa-save me-2"></i> Registrar e Guardar Profesor
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-12">
        <div class="card shadow-sm rounded-4 border-0">
            <div class="card-header bg-white p-3 border-0 d-flex justify-content-between align-items-center">
                <h6 class="fw-bold mb-0 text-secondary">
                    <i class="fas fa-list me-2 text-primary"></i> Nómina de Docentes y Grupos Activos
                </h6>
                <span class="badge bg-primary rounded-pill px-3 py-2 small">Stage Dance Class</span>
            </div>
            <div class="table-responsive p-3">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light text-secondary small text-uppercase">
                        <tr>
                            <th class="ps-3" style="width: 120px;">Identificación</th>
                            <th>Docente</th>
                            <th>Grupo Asignado</th>
                            <th class="text-center" style="width: 140px;">Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $sql_listado = "SELECT p.*, c.cla_categoria, c.cla_nivel 
                                        FROM bas_profesores p 
                                        LEFT JOIN bas_clasificaciones c ON p.cla_id = c.cla_id 
                                        ORDER BY p.prof_apellidos ASC";
                        $res_profesores = $bd->ejecutar($sql_listado);

                        if ($res_profesores && $res_profesores->num_rows > 0):
                            while ($prof = $res_profesores->fetch_assoc()):
                        ?>
                            <tr>
                                <td class="ps-3 font-monospace small fw-bold text-secondary">
                                    <?= htmlspecialchars($prof['prof_cedula']) ?>
                                </td>
                                <td>
                                    <div class="fw-bold text-dark"><?= htmlspecialchars($prof['prof_apellidos'] . " " . $prof['prof_nombres']) ?></div>
                                    <span class="text-muted small">Profesor Técnico</span>
                                </td>
                                <td>
                                    <?php if (!empty($prof['cla_id'])): ?>
                                        <span class="badge bg-info-subtle text-info rounded-pill px-3 py-1.5 fw-bold">
                                            <i class="fas fa-users me-1"></i> 
                                            <?= htmlspecialchars($prof['cla_categoria'] . " (" . $prof['cla_nivel'] . ")") ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="badge bg-warning-subtle text-warning rounded-pill px-3 py-1.5 fw-bold">
                                            <i class="fas fa-exclamation-triangle me-1"></i> Sin Asignación
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <div class="btn-group">
                                        <button type="button" class="btn btn-sm btn-outline-info rounded-pill px-2.5 me-1" title="Ver Ficha Completa" onclick="verFichaProfesor(<?= $prof['prof_id'] ?>)">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                        <button type="button" class="btn btn-sm btn-outline-secondary rounded-pill px-2.5" title="Editar Ficha" onclick="editarProfesor(<?= htmlspecialchars(json_encode($prof)) ?>)">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        <?php 
                            endwhile;
                        else:
                        ?>
                            <tr>
                                <td colspan="4" class="text-center py-4 text-muted small">
                                    <i class="fas fa-info-circle fs-4 mb-2 d-block text-warning"></i>
                                    No existen profesores registrados en la plataforma actualmente.
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalVerProfesor" isset-tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content rounded-4 border-0 shadow">
            <div class="modal-header border-0 bg-light p-3 rounded-top-4">
                <h6 class="modal-title fw-bold text-dark"><i class="fas fa-address-card text-primary me-2"></i> Perfil e Ficha del Profesor</h6>
                <button type="button" class="btn-close" data-bs-submit="modal" aria-label="Close" onclick="cerrarModalProfesor()"></button>
            </div>
            <div class="modal-body p-4" id="contenido-ficha-profesor">
                <div class="text-center text-muted">
                    <div class="spinner-border text-primary mb-2" role="status"></div>
                    <p class="small mb-0">Consultando base de datos...</p>
                </div>
            </div>
            <div class="modal-footer border-0 bg-light p-2 rounded-bottom-4">
                <button type="button" class="btn btn-sm btn-secondary rounded-pill px-3" onclick="cerrarModalProfesor()">Cerrar Vista</button>
            </div>
        </div>
    </div>
</div>

<script>
let instanciaModalProf = null;

function verFichaProfesor(prof_id) {
    const contenedor = document.getElementById('contenido-ficha-profesor');
    contenedor.innerHTML = `<div class="text-center text-muted py-3"><div class="spinner-border text-primary mb-2" role="status"></div><p class="small mb-0">Cargando...</p></div>`;
    
    if(!instanciaModalProf) {
        instanciaModalProf = new bootstrap.Modal(document.getElementById('modalVerProfesor'));
    }
    instanciaModalProf.show();

    fetch(`controlador/ProfesorController.php?action=consultar&prof_id=${prof_id}`)
    .then(response => response.json())
    .then(data => {
        if(data.status === 'success') {
            const p = data.data;
            contenedor.innerHTML = `
                <div class="text-center mb-3">
                    <div class="avatar bg-primary text-white rounded-circle d-inline-flex align-items-center justify-content-center mb-2" style="width: 65px; height: 65px; font-size: 24px;">
                        <i class="fas fa-chalkboard-teacher"></i>
                    </div>
                    <h5 class="fw-bold text-dark mb-1">${p.prof_apellidos} ${p.prof_nombres}</h5>
                    <span class="badge bg-secondary rounded-pill small px-3">ID Docente: #${p.prof_id}</span>
                </div>
                <hr class="text-muted opacity-25 my-3">
                <div class="row g-3 text-secondary small">
                    <div class="col-6">
                        <span class="d-block text-muted fw-bold text-uppercase" style="font-size:0.65rem;">Cédula / Pasaporte</span>
                        <span class="text-dark fw-bold font-monospace">${p.prof_cedula}</span>
                    </div>
                    <div class="col-6">
                        <span class="d-block text-muted fw-bold text-uppercase" style="font-size:0.65rem;">Estado Operativo</span>
                        <span class="badge ${p.prof_estado == 1 ? 'bg-success-subtle text-success' : 'bg-danger-subtle text-danger'} rounded-pill px-2.5">${p.prof_estado == 1 ? 'ACTIVO' : 'INACTIVO'}</span>
                    </div>
                    <div class="col-6">
                        <span class="d-block text-muted fw-bold text-uppercase" style="font-size:0.65rem;">Teléfono / Contacto</span>
                        <span class="text-dark">${p.prof_telefono ? p.prof_telefono : 'No registrado'}</span>
                    </div>
                    <div class="col-6">
                        <span class="d-block text-muted fw-bold text-uppercase" style="font-size:0.65rem;">Correo Electrónico</span>
                        <span class="text-dark">${p.prof_correo ? p.prof_correo : 'No registrado'}</span>
                    </div>
                    <div class="col-12">
                        <span class="d-block text-muted fw-bold text-uppercase" style="font-size:0.65rem;">Especialidad / Rama Técnica</span>
                        <span class="text-dark">${p.prof_especialidad ? p.prof_especialidad : 'Instructor General'}</span>
                    </div>
                    <div class="col-12 bg-light p-2.5 rounded-3 border border-light-subtle">
                        <span class="d-block text-muted fw-bold text-uppercase mb-1" style="font-size:0.65rem;"><i class="fas fa-layer-group text-primary me-1"></i> Clasificación y Grupo Dictado</span>
                        <span class="text-dark fw-bold">${p.cla_categoria ? p.cla_categoria + ' - ' + p.cla_nivel : 'Sin grupo asignado estructuralmente.'}</span>
                    </div>
                </div>
            `;
        } else {
            contenedor.innerHTML = `<div class="alert alert-danger border-0 small m-0">${data.message}</div>`;
        }
    })
    .catch(err => {
        contenedor.innerHTML = `<div class="alert alert-danger border-0 small m-0">Error en la comunicación con el servidor.</div>`;
    });
}

function cerrarModalProfesor() {
    if(instanciaModalProf) instanciaModalProf.hide();
}

function editarProfesor(datos) {
    document.getElementById('prof_id').value = datos.prof_id;
    document.getElementById('prof_cedula').value = datos.prof_cedula;
    document.getElementById('prof_nombres').value = datos.prof_nombres;
    document.getElementById('prof_apellidos').value = datos.prof_apellidos;
    document.getElementById('cla_id').value = datos.cla_id ? datos.cla_id : '';

    document.getElementById('form-title').innerText = "Modificar Ficha de Profesor";
    document.getElementById('form-subtitle').innerText = "Está editando la información del docente seleccionado. Guarde los cambios para actualizar.";
    
    const btnSubmit = document.getElementById('btn-submit');
    btnSubmit.innerHTML = '<i class="fas fa-sync-alt me-2"></i> Actualizar Profesor';
    btnSubmit.className = "btn btn-warning rounded-pill fw-bold px-4 shadow-sm text-dark";
    
    document.getElementById('btn-limpiar').style.display = 'none';
    document.getElementById('btn-cancelar').style.display = 'inline-block';

    window.scrollTo({ top: 0, behavior: 'smooth' });
}

function cancelarEdicion() {
    document.getElementById('form-profesor').reset();
    document.getElementById('prof_id').value = '';
    document.getElementById('form-title').innerText = "Ficha de Registro de Profesor";
    document.getElementById('form-subtitle').innerText = "Ingrese la información básica y asigne el grupo correspondiente";

    const btnSubmit = document.getElementById('btn-submit');
    btnSubmit.innerHTML = '<i class="fas fa-save me-2"></i> Registrar e Guardar Profesor';
    btnSubmit.className = "btn btn-primary rounded-pill fw-bold px-4 shadow-sm";

    document.getElementById('btn-limpiar').style.display = 'inline-block';
    document.getElementById('btn-cancelar').style.display = 'none';
}
</script>