<?php
$title = 'Checklist de Devolução';
require_once __DIR__ . '/auth.php';
require_login();
check_csrf();

$loan_id = (int)($_GET['loan_id'] ?? 0);
if (!$loan_id) { http_response_code(400); exit('ID inválido'); }

$loan = $pdo->prepare("SELECT l.*, e.matricula, e.nome
  FROM loans l JOIN employees e ON e.id=l.employee_id WHERE l.id=?");
$loan->execute([$loan_id]);
$loan = $loan->fetch();
if (!$loan) { http_response_code(404); exit('Empréstimo não encontrado'); }

$items = $pdo->prepare("SELECT li.equipment_id, e.patrimonio, e.serial, et.name tipo, e.modelo
  FROM loan_items li JOIN equipment e ON e.id=li.equipment_id JOIN equipment_types et ON et.id=e.type_id
  WHERE li.loan_id=?");
$items->execute([$loan_id]);
$items = $items->fetchAll();

include __DIR__ . '/header.php';
?>
<div class="container-fluid">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h2 class="h5 m-0">Checklist — Empréstimo #<?= (int)$loan['id'] ?></h2>
    <a class="btn btn-outline-secondary" href="<?= base_url('loan_view.php?id='.(int)$loan['id']) ?>">Voltar</a>
  </div>

  <div class="card border-0 shadow-sm mb-3">
    <div class="card-body">
      <div class="fw-semibold">Colaborador</div>
      <div><?= h($loan['matricula'].' • '.$loan['nome']) ?></div>
    </div>
  </div>

  <form method="post" action="<?= base_url('return_save.php') ?>" enctype="multipart/form-data" class="mb-5">
    <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
    <input type="hidden" name="loan_id" value="<?= (int)$loan['id'] ?>">

    <?php foreach ($items as $it): $eid=(int)$it['equipment_id']; ?>
      <div class="card border-0 shadow-sm mb-3">
        <div class="card-header bg-white">
          Item #<?= $eid ?> — <?= h(($it['tipo'] ?? '—').($it['modelo']?' • '.$it['modelo']:'')) ?>
          <span class="text-muted small ms-2"><?= h(($it['patrimonio']? 'PAT '.$it['patrimonio']:'').($it['serial']? ' • SN '.$it['serial'] : '')) ?></span>
        </div>
        <div class="card-body">
          <div class="row g-3">
            <div class="col-md-4">
              <label class="form-label">Funciona?</label>
              <div class="d-flex gap-3">
                <label class="form-check"><input class="form-check-input" type="radio" name="funciona[<?= $eid ?>]" value="SIM" checked> <span class="form-check-label">Sim</span></label>
                <label class="form-check"><input class="form-check-input" type="radio" name="funciona[<?= $eid ?>]" value="NAO"> <span class="form-check-label">Não</span></label>
                <label class="form-check"><input class="form-check-input" type="radio" name="funciona[<?= $eid ?>]" value="NA"> <span class="form-check-label">N/A</span></label>
              </div>
            </div>
            <div class="col-md-4">
              <label class="form-label">Acessórios</label>
              <div class="form-check">
                <input class="form-check-input" type="checkbox" name="fonte[<?= $eid ?>]" id="fonte<?= $eid ?>">
                <label class="form-check-label" for="fonte<?= $eid ?>">Fonte/Carregador</label>
              </div>
              <div class="form-check">
                <input class="form-check-input" type="checkbox" name="cabos[<?= $eid ?>]" id="cabos<?= $eid ?>">
                <label class="form-check-label" for="cabos<?= $eid ?>">Cabos (energia/vídeo/USB)</label>
              </div>
            </div>
            <div class="col-md-4">
              <label class="form-label">Periféricos</label>
              <input class="form-control" name="perifericos[<?= $eid ?>]" placeholder="Ex.: mouse, teclado, headset">
            </div>
            <div class="col-md-4">
              <label class="form-label">Avarias</label>
              <select class="form-select" name="avarias[<?= $eid ?>]">
                <option value="NENHUMA">Nenhuma</option>
                <option value="LEVE">Leve</option>
                <option value="GRAVE">Grave</option>
              </select>
            </div>
            <div class="col-md-8">
              <label class="form-label">Observações</label>
              <input class="form-control" name="obs[<?= $eid ?>]" placeholder="Notas sobre o item na devolução">
            </div>
            <div class="col-md-6">
              <label class="form-label">Foto do item (opcional)</label>
              <input type="file" name="photo[<?= $eid ?>]" class="form-control" accept="image/png,image/jpeg">
              <div class="form-text">PNG/JPG até 8 MB.</div>
            </div>
          </div>
        </div>
      </div>
    <?php endforeach; ?>

    <?php if (!$items): ?>
      <div class="alert alert-warning">Nenhum item físico vinculado a este empréstimo.</div>
    <?php endif; ?>

    <div class="card border-0 shadow-sm mb-3">
      <div class="card-header bg-white">Resumo da devolução</div>
      <div class="card-body">
        <div class="mb-3">
          <label class="form-label">Observações gerais</label>
          <textarea class="form-control" name="notes" rows="3"></textarea>
        </div>
      </div>
    </div>

    <div class="d-flex gap-2">
      <button class="btn btn-success"><i class="bi bi-check2-circle me-1"></i> Finalizar devolução</button>
      <a class="btn btn-outline-secondary" href="<?= base_url('loan_view.php?id='.(int)$loan['id']) ?>">Cancelar</a>
    </div>
  </form>
</div>
<?php include __DIR__ . '/footer.php'; ?>
