@extends('layouts.app')
@section('titulo','OT '.$orden->codigo)
@section('contenido')
<div class="d-flex flex-wrap justify-content-between align-items-center mb-3">
  <h4><i class="fa fa-wrench"></i> {{ $orden->codigo }}
    @if($orden->estado)<span class="estado-badge ms-2" style="background: {{ $orden->estado->color }};">{{ $orden->estado->nombre }}</span>@endif
  </h4>
  <div>
    <a href="{{ route('ordenes.pdf',$orden) }}" target="_blank" class="btn btn-outline-danger"><i class="fa fa-file-pdf"></i> PDF</a>
    <div class="btn-group">
      <button class="btn btn-acento dropdown-toggle" data-bs-toggle="dropdown">
        <i class="fa fa-file-lines"></i> Informe Interno
      </button>
      <ul class="dropdown-menu">
        <li><a class="dropdown-item" href="{{ route('ordenes.informe.pdf', $orden) }}" target="_blank">
          <i class="fa fa-file-pdf text-danger"></i> PDF</a></li>
        <li><a class="dropdown-item" href="{{ route('ordenes.informe.word', $orden) }}">
          <i class="fa fa-file-word text-primary"></i> Word (.docx)</a></li>
      </ul>
    </div>
    @can('ordenes.editar')<a href="{{ route('ordenes.edit',$orden) }}" class="btn btn-primario"><i class="fa fa-pen"></i> Editar</a>@endcan
  </div>
</div>

<div class="row g-3">
  <div class="col-lg-8">
    <div class="card mb-3"><div class="card-body">
      <div class="row">
        <div class="col-md-3"><strong>Clase:</strong> {{ ucfirst($orden->clase) }}</div>
        <div class="col-md-3"><strong>Equipo:</strong> {{ optional($orden->equipo)->nombre }}</div>
        <div class="col-md-3"><strong>Área:</strong> {{ optional($orden->equipo->area ?? null)->nombre }}</div>
        <div class="col-md-3"><strong>Programada:</strong> {{ $orden->fecha_programada?->format('d/m/Y') }}</div>
        <div class="col-md-3"><strong>Inicio:</strong> {{ $orden->fecha_inicio?->format('d/m/Y H:i') }}</div>
        <div class="col-md-3"><strong>Cierre:</strong> {{ $orden->fecha_cierre?->format('d/m/Y H:i') }}</div>
        <div class="col-md-3"><strong>Responsable:</strong> {{ optional($orden->responsable)->nombre_completo }}</div>
        <div class="col-md-3"><strong>Prioridad:</strong> {{ optional($orden->prioridad)->nombre }}</div>
      </div>
      @if($orden->descripcion)<p class="mt-2"><strong>Descripción:</strong> {{ $orden->descripcion }}</p>@endif
      @if($orden->observaciones)<p><strong>Observaciones:</strong> {{ $orden->observaciones }}</p>@endif
    </div></div>

    <div class="card mb-3">
      <div class="card-header d-flex flex-wrap justify-content-between align-items-center">
        <strong><i class="fa fa-list-check"></i> Checklist
          <small class="text-muted ms-2">L=Limpieza · I=Inspección · Lu=Lubricación · A=Ajuste</small>
        </strong>
        <div class="d-flex gap-2">
          @if($orden->plan_id)
            <form method="POST" action="{{ route('ordenes.poblar',$orden) }}" class="d-inline"
                  onsubmit="return confirm('¿Cargar todos los ítems desde el plan asociado?');">
              @csrf
              <button class="btn btn-sm btn-outline-primary"><i class="fa fa-download"></i> Llenar desde plan</button>
            </form>
          @endif
          <button class="btn btn-sm btn-primario" data-bs-toggle="collapse" data-bs-target="#nuevoItemOt">
            <i class="fa fa-plus"></i> Agregar ítem
          </button>
        </div>
      </div>
      <div id="nuevoItemOt" class="collapse">
        <form method="POST" action="{{ route('ordenes.items.store',$orden) }}" class="card-body border-bottom">
          @csrf
          <div class="row g-2">
            <div class="col-md-1"><label class="form-label small">N°</label>
              <input type="number" name="numero_item" class="form-control form-control-sm" placeholder="auto"></div>
            <div class="col-md-7"><label class="form-label small">Descripción *</label>
              <input name="descripcion" class="form-control form-control-sm" required maxlength="500"></div>
            <div class="col-md-4"><label class="form-label small">Lectura / condición</label>
              <input name="lectura_condicion" class="form-control form-control-sm" maxlength="100"></div>
            <div class="col-12">
              <div class="d-flex flex-wrap gap-3 mt-2">
                @foreach([['lila_l_limpieza','L (limpieza)'],['lila_i_inspeccion','I (inspección)'],
                          ['lila_l_lubricacion','Lu (lubricación)'],['lila_a_ajuste','A (ajuste)']] as [$c,$lbl])
                  <div class="form-check">
                    <input type="hidden" name="{{ $c }}" value="0">
                    <input type="checkbox" name="{{ $c }}" value="1" id="ni_{{ $c }}" class="form-check-input">
                    <label for="ni_{{ $c }}" class="form-check-label small">{{ $lbl }}</label>
                  </div>
                @endforeach
              </div>
            </div>
          </div>
          <div class="text-end mt-2"><button class="btn btn-sm btn-primario"><i class="fa fa-save"></i> Agregar</button></div>
        </form>
      </div>
      <div class="table-responsive"><table class="table table-sm mb-0 align-middle">
        <thead><tr><th>#</th><th>Descripción</th><th>L</th><th>I</th><th>Lu</th><th>A</th><th>Estado</th><th>Lectura</th><th class="text-end"></th></tr></thead>
        <tbody>
        @forelse($orden->items as $it)
          <tr>
            <form method="POST" action="{{ route('ordenes.items.update',[$orden,$it]) }}">@csrf @method('PUT')
              <td>{{ $it->numero_item }}</td>
              <td>{{ \Illuminate\Support\Str::limit($it->descripcion,80) }}</td>
              @foreach(['lila_l_limpieza','lila_i_inspeccion','lila_l_lubricacion','lila_a_ajuste'] as $f)
                <td class="text-center"><input type="hidden" name="{{ $f }}" value="0"><input type="checkbox" name="{{ $f }}" value="1" {{ $it->$f?'checked':'' }}></td>
              @endforeach
              <td><select name="estado_item" class="form-select form-select-sm" data-no-search>
                <option value="pendiente" @selected($it->estado_item==='pendiente')>Pendiente</option>
                <option value="realizado" @selected($it->estado_item==='realizado')>Realizado</option>
                <option value="no_aplica" @selected($it->estado_item==='no_aplica')>No aplica</option>
                <option value="no_realizado" @selected($it->estado_item==='no_realizado')>No realizado</option>
              </select></td>
              <td><input name="lectura_condicion" value="{{ $it->lectura_condicion }}" class="form-control form-control-sm"></td>
              <td class="text-end text-nowrap">
                <button class="btn btn-sm btn-outline-success" title="Guardar"><i class="fa fa-check"></i></button>
            </form>
            <form method="POST" action="{{ route('ordenes.items.destroy',[$orden,$it]) }}" class="d-inline"
                  onsubmit="return confirm('¿Eliminar este ítem?');">
              @csrf @method('DELETE')
              <button class="btn btn-sm btn-outline-danger" title="Eliminar"><i class="fa fa-trash"></i></button>
            </form>
              </td>
          </tr>
        @empty
          <tr><td colspan="9" class="text-muted text-center py-3">
            Sin ítems.
            @if($orden->plan_id)
              Usa <strong>Llenar desde plan</strong> arriba para cargarlos automáticamente.
            @else
              Usa <strong>Agregar ítem</strong> arriba para crearlos manualmente.
            @endif
          </td></tr>
        @endforelse
        </tbody>
      </table></div>
    </div>

    <div class="card mb-3">
      <div class="card-header d-flex justify-content-between"><strong><i class="fa fa-camera"></i> Evidencias</strong></div>
      <div class="card-body">
        <form method="POST" action="{{ route('ordenes.fotos.store',$orden) }}" enctype="multipart/form-data" class="row g-2 mb-3">@csrf
          <div class="col-md-4"><input type="file" name="foto" accept="image/*" capture="environment" class="form-control" required></div>
          <div class="col-md-3"><select name="tipo" class="form-select">
            <option value="evidencia">Evidencia</option><option value="antes">Antes</option><option value="despues">Después</option>
            <option value="placa">Placa</option><option value="manual">Manual</option><option value="otro">Otro</option>
          </select></div>
          <div class="col-md-3"><input name="descripcion" class="form-control" placeholder="Descripción..."></div>
          <div class="col-md-2"><button class="btn btn-primario w-100"><i class="fa fa-upload"></i> Subir</button></div>
        </form>
        <div class="row g-2">
          @forelse($orden->fotos as $f)
            <div class="col-6 col-md-3"><div class="card">
              <a href="{{ asset('storage/'.$f->ruta) }}" target="_blank">
                <img src="{{ asset('storage/'.$f->ruta) }}" class="card-img-top" style="height:120px; object-fit:cover;">
              </a>
              <div class="card-body p-2">
                <span class="badge text-bg-secondary">{{ $f->tipo }}</span>
                <small class="d-block">{{ $f->descripcion }}</small>
                <form method="POST" action="{{ route('ordenes.fotos.destroy',[$orden,$f]) }}" onsubmit="return confirm('¿Eliminar?');">
                  @csrf @method('DELETE')<button class="btn btn-sm btn-outline-danger mt-1"><i class="fa fa-trash"></i></button>
                </form>
              </div>
            </div></div>
          @empty <div class="col-12 text-muted">Sin fotos.</div>
          @endforelse
        </div>
      </div>
    </div>

    <div class="card mb-3">
      <div class="card-header"><strong><i class="fa fa-dollar-sign"></i> Costos</strong></div>
      <div class="card-body">
        <form method="POST" action="{{ route('ordenes.costos.store',$orden) }}" class="row g-2 mb-3">@csrf
          <div class="col-md-2"><select name="tipo" class="form-select">
            <option value="repuesto">Repuesto</option><option value="mano_obra">Mano de obra</option><option value="otro">Otro</option>
          </select></div>
          <div class="col-md-3"><select name="repuesto_id" class="form-select"><option value="">— Repuesto —</option>
            @foreach($repuestos as $r)<option value="{{ $r->id }}">{{ $r->codigo }} - {{ $r->nombre }} ({{ $r->stock }})</option>@endforeach
          </select></div>
          <div class="col-md-3"><input name="concepto" class="form-control" placeholder="Concepto" required></div>
          <div class="col-md-1"><input name="cantidad" type="number" step="0.001" class="form-control" placeholder="Cant" required></div>
          <div class="col-md-2"><input name="costo_unitario" type="number" step="0.01" class="form-control" placeholder="C. unit." required></div>
          <div class="col-md-1"><button class="btn btn-primario w-100"><i class="fa fa-plus"></i></button></div>
        </form>
        <table class="table table-sm">
          <thead><tr><th>Concepto</th><th>Tipo</th><th class="text-end">Cantidad</th><th class="text-end">C. unit.</th><th class="text-end">Total</th><th></th></tr></thead>
          <tbody>
            @foreach($orden->costos as $c)
              <tr><td>{{ $c->concepto }}</td><td>{{ $c->tipo }}</td>
                <td class="text-end">{{ $c->cantidad }}</td>
                <td class="text-end">{{ number_format($c->costo_unitario,2) }}</td>
                <td class="text-end">{{ number_format($c->costo_total,2) }}</td>
                <td><form method="POST" action="{{ route('ordenes.costos.destroy',[$orden,$c]) }}" onsubmit="return confirm('¿Eliminar?');">
                  @csrf @method('DELETE')<button class="btn btn-sm btn-outline-danger"><i class="fa fa-trash"></i></button></form></td>
              </tr>
            @endforeach
          </tbody>
          <tfoot><tr class="table-light fw-bold"><td colspan="4" class="text-end">Total</td>
            <td class="text-end">{{ number_format($orden->costo_total,2) }}</td><td></td></tr></tfoot>
        </table>
      </div>
    </div>
  </div>

  <div class="col-lg-4">
    <div class="card mb-3"><div class="card-header"><strong>Cambiar estado</strong></div>
      <form method="POST" action="{{ route('ordenes.estado',$orden) }}" class="card-body">@csrf
        <div class="mb-2"><select name="estado_id" class="form-select">
          @foreach($estados as $e)<option value="{{ $e->id }}" @selected($orden->estado_id==$e->id)>{{ $e->nombre }}</option>@endforeach
        </select></div>
        <div class="mb-2"><textarea name="comentario" class="form-control" rows="2" placeholder="Comentario..."></textarea></div>
        <button class="btn btn-primario w-100"><i class="fa fa-arrow-right"></i> Cambiar</button>
      </form>
    </div>

    <div class="card mb-3"><div class="card-header"><strong>Firma con clave personal</strong></div>
      <form method="POST" action="{{ route('ordenes.firmar',$orden) }}" class="card-body">@csrf
        <div class="mb-2"><select name="tipo" class="form-select">
          <option value="responsable">Responsable</option><option value="supervisor">Supervisor</option>
        </select></div>
        <div class="mb-2"><input type="password" name="clave_firma" class="form-control" placeholder="Clave de firma" required></div>
        <button class="btn btn-acento w-100"><i class="fa fa-pen-nib"></i> Firmar</button>
      </form>
      @php
        $renderFirmaWeb = function ($valor) {
            if (!$valor) return '';
            if (str_starts_with($valor, 'IMG:')) {
                [$ruta, $nombre, $fecha] = array_pad(explode('|', substr($valor, 4)), 3, '');
                return '<img src="' . asset('storage/'.$ruta) . '" style="max-height:50px; max-width:180px;"><br>'
                     . '<small class="text-muted">' . e($nombre) . ' — ' . e($fecha) . '</small>';
            }
            if (str_starts_with($valor, 'TXT:')) {
                [$nombre, $fecha] = array_pad(explode('|', substr($valor, 4)), 2, '');
                return '<small>' . e($nombre . ' — ' . $fecha) . '</small>';
            }
            return '<small>' . e($valor) . '</small>';
        };
      @endphp
      @if($orden->firma_responsable)<div class="card-body small text-success"><strong>Responsable:</strong><br>{!! $renderFirmaWeb($orden->firma_responsable) !!}</div>@endif
      @if($orden->firma_supervisor)<div class="card-body small text-success border-top"><strong>Supervisor:</strong><br>{!! $renderFirmaWeb($orden->firma_supervisor) !!}</div>@endif
    </div>

    <div class="card"><div class="card-header"><strong>Bitácora</strong></div>
      <ul class="list-group list-group-flush" style="max-height:400px; overflow-y:auto;">
        @forelse($orden->logs as $l)
          <li class="list-group-item small">
            <strong>{{ $l->accion }}</strong>
            @if($l->estado_anterior || $l->estado_nuevo)<span class="text-muted">[{{ $l->estado_anterior }} → {{ $l->estado_nuevo }}]</span>@endif
            <br><small class="text-muted">{{ optional($l->usuario)->usuario }} — {{ $l->created_at->format('d/m H:i') }}</small>
            @if($l->detalle)<br><em>{{ $l->detalle }}</em>@endif
          </li>
        @empty <li class="list-group-item text-muted">Sin actividad</li>
        @endforelse
      </ul>
    </div>
  </div>
</div>
@endsection
