@extends('layouts.app')
@section('title', 'Registrar Incapacidad')

@section('content')
<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="mb-0"><i class="bi bi-bandaid me-2"></i>Registrar Incapacidad</h5>
    <a href="{{ route('incapacidades.index') }}" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-arrow-left me-1"></i>Volver
    </a>
</div>

<div class="row g-3">
<div class="col-lg-7">
<form action="{{ route('incapacidades.store') }}" method="POST">
@csrf
<div class="card mb-3">
    <div class="card-header"><i class="bi bi-person me-1"></i>Datos de la Incapacidad</div>
    <div class="card-body">
        <div class="row g-3">
            <div class="col-12">
                <label class="form-label fw-semibold">Empleado <span class="text-danger">*</span></label>
                <select name="empleado_id" class="form-select @error('empleado_id') is-invalid @enderror" required onchange="actualizarCalculo()">
                    <option value="">-- Seleccionar --</option>
                    @foreach($empleados as $e)
                    <option value="{{ $e->id }}"
                            data-salario="{{ $e->salario }}"
                            {{ old('empleado_id')==$e->id?'selected':'' }}>
                        {{ $e->nombre }} — C.C: {{ $e->cedula }}
                    </option>
                    @endforeach
                </select>
                @error('empleado_id')<div class="invalid-feedback">{{ $message }}</div>@enderror
            </div>
            <div class="col-md-6">
                <label class="form-label fw-semibold">Fecha inicio <span class="text-danger">*</span></label>
                <input type="date" name="fecha_inicio" class="form-control" value="{{ old('fecha_inicio') }}" required onchange="actualizarCalculo()">
            </div>
            <div class="col-md-6">
                <label class="form-label fw-semibold">Fecha fin <span class="text-danger">*</span></label>
                <input type="date" name="fecha_fin" class="form-control" value="{{ old('fecha_fin') }}" required onchange="actualizarCalculo()">
            </div>
            <div class="col-md-6">
                <label class="form-label fw-semibold">Tipo <span class="text-danger">*</span></label>
                <select name="tipo" class="form-select" required onchange="actualizarCalculo()">
                    @foreach(\App\Models\Incapacidad::tiposLabel() as $val => $lbl)
                    <option value="{{ $val }}" {{ old('tipo','enfermedad_general')==$val?'selected':'' }}>{{ $lbl }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-6">
                <label class="form-label fw-semibold">Radicado EPS/ARL</label>
                <input type="text" name="numero_radicado" class="form-control" value="{{ old('numero_radicado') }}" placeholder="Opcional">
            </div>
            <div class="col-12">
                <label class="form-label fw-semibold">Diagnostico</label>
                <input type="text" name="diagnostico" class="form-control" value="{{ old('diagnostico') }}" placeholder="Ej: Lumbalgia aguda — CIE M54.5">
            </div>
            <div class="col-12">
                <label class="form-label fw-semibold">Observaciones</label>
                <textarea name="observaciones" class="form-control" rows="2">{{ old('observaciones') }}</textarea>
            </div>
        </div>
    </div>
</div>

<div class="d-flex gap-2">
    <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i>Guardar</button>
    <a href="{{ route('incapacidades.index') }}" class="btn btn-outline-secondary">Cancelar</a>
</div>
</form>
</div>

{{-- CALCULO EN TIEMPO REAL --}}
<div class="col-lg-5">
    <div class="card" id="cardCalculo" style="opacity:.4">
        <div class="card-header"><i class="bi bi-calculator me-1"></i>Calculo Estimado (Ley Colombiana)</div>
        <div class="card-body p-0">
            <table class="table table-sm mb-0">
                <tbody>
                    <tr><td class="text-muted small">Dias totales</td><td class="fw-bold text-end" id="c-dias">—</td></tr>
                    <tr><td class="text-muted small">Salario dia</td><td class="fw-bold text-end" id="c-saldia">—</td></tr>
                    <tr class="table-warning">
                        <td class="small">Dias empresa (1-2)</td>
                        <td class="fw-bold text-end" id="c-emp">—</td>
                    </tr>
                    <tr class="table-info">
                        <td class="small">Dias EPS (3-90 al 66.67%)</td>
                        <td class="fw-bold text-end" id="c-eps1">—</td>
                    </tr>
                    <tr class="table-info">
                        <td class="small">Dias EPS (91-180 al 50%)</td>
                        <td class="fw-bold text-end" id="c-eps2">—</td>
                    </tr>
                    <tr class="table-danger">
                        <td class="small">Dias ARL (accidente/enf. prof.)</td>
                        <td class="fw-bold text-end" id="c-arl">—</td>
                    </tr>
                    <tr class="table-success">
                        <td class="fw-semibold">Total estimado</td>
                        <td class="fw-bold text-success text-end fs-6" id="c-total">—</td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div class="card-footer" style="font-size:11px;color:#999">
            Calculo aproximado. Los valores exactos los determina la EPS/ARL.
        </div>
    </div>
</div>
</div>

@push('scripts')
<script>
function fmt(v) { return '$ ' + Math.round(v).toLocaleString('es-CO'); }

function actualizarCalculo() {
    const sel    = document.querySelector('[name=empleado_id]');
    const opt    = sel.options[sel.selectedIndex];
    const salario= parseFloat(opt.dataset.salario) || 0;
    const inicio = document.querySelector('[name=fecha_inicio]').value;
    const fin    = document.querySelector('[name=fecha_fin]').value;
    const tipo   = document.querySelector('[name=tipo]').value;

    if (!salario || !inicio || !fin) return;

    const d1   = new Date(inicio), d2 = new Date(fin);
    if (d2 < d1) return;

    const dias = Math.round((d2 - d1) / 86400000) + 1;
    const salDia = salario / 30;

    let emp=0, eps1=0, eps2=0, arl=0;
    let dEmp=0, dEps1=0, dEps2=0, dArl=0;

    if (tipo === 'accidente_trabajo' || tipo === 'enfermedad_profesional') {
        dArl = dias; arl = dias * salDia;
    } else if (tipo === 'maternidad' || tipo === 'paternidad') {
        dEps1 = dias; eps1 = dias * salDia;
    } else {
        dEmp  = Math.min(dias, 2);           emp  = dEmp  * salDia * 0.6667;
        dEps1 = Math.min(Math.max(dias-2,0), 88); eps1 = dEps1 * salDia * 0.6667;
        dEps2 = Math.min(Math.max(dias-90,0),90); eps2 = dEps2 * salDia * 0.5;
    }

    const total = emp + eps1 + eps2 + arl;

    document.getElementById('c-dias').textContent   = dias + ' dias';
    document.getElementById('c-saldia').textContent = fmt(salDia);
    document.getElementById('c-emp').textContent    = dEmp  ? `${dEmp}d = ${fmt(emp)}`   : '—';
    document.getElementById('c-eps1').textContent   = dEps1 ? `${dEps1}d = ${fmt(eps1)}` : '—';
    document.getElementById('c-eps2').textContent   = dEps2 ? `${dEps2}d = ${fmt(eps2)}` : '—';
    document.getElementById('c-arl').textContent    = dArl  ? `${dArl}d = ${fmt(arl)}`   : '—';
    document.getElementById('c-total').textContent  = fmt(total);
    document.getElementById('cardCalculo').style.opacity = '1';
}
</script>
@endpush
@endsection
