<?php
$title = 'Empréstimo';
require_once __DIR__ . '/auth.php';
require_login();
check_csrf();

$id = (int)($_GET['id'] ?? 0);

// Detalhes do empréstimo + colaborador + operação + usuário que disponibilizou
$loan = $pdo->prepare("SELECT l.*, e.matricula, e.nome, o.name op, u.name responsavel
  FROM loans l
  JOIN employees e ON e.id=l.employee_id
  LEFT JOIN operations o ON o.id=l.operation_id
  JOIN users u ON u.id=l.disponibilizado_por
  WHERE l.id=?");
$loan->execute([$id]);
$loan = $loan->fetch();
if (!$loan) { http_response_code(404); exit('Empréstimo não encontrado'); }

// Termos anexados
$terms = $pdo->prepare('SELECT * FROM loan_terms WHERE loan_id=? ORDER BY id DESC');
$terms->execute([$id]);
$terms = $terms->fetchAll();

// Itens vinculados a este empréstimo
$items = $pdo->prepare("SELECT li.equipment_id, e.patrimonio, e.serial, et.name tipo, e.modelo, e.status
  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([$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">Empréstimo #<?= (int)$loan['id'] ?></h2>
    <a class="btn btn-outline-secondary" href="<?= base_url('loans.php') ?>">Voltar</a>
  </div>

  <div class="row g-3">
    <div class="col-xl-8">
      <div class="card border-0 shadow-sm">
        <div class="card-header bg-white">Detalhes</div>
        <div class="card-body">
          <dl class="row mb-0">
            <dt class="col-sm-3">Colaborador</dt>
            <dd class="col-sm-9"><?= h($loan['matricula'].' • '.$loan['nome']) ?></dd>

            <dt class="col-sm-3">Operação</dt>
            <dd class="col-sm-9"><?= h($loan['op'] ?? '—') ?></dd>

            <dt class="col-sm-3">Qtd. Itens</dt>
            <dd class="col-sm-9"><?= (int)$loan['quantidade'] ?></dd>

            <dt class="col-sm-3">Forma de entrega</dt>
            <dd class="col-sm-9"><?= t_delivery($loan['delivery_method'] ?? 'RETIRADA') ?></dd>

            <dt class="col-sm-3">Entrega em</dt>
            <dd class="col-sm-9"><?= br_date($loan['data_entrega']) ?></dd>

            <dt class="col-sm-3">Devolução prevista</dt>
            <dd class="col-sm-9"><?= br_date($loan['due_date'] ?? null) ?></dd>

            <dt class="col-sm-3">Rastreamento</dt>
            <dd class="col-sm-9"><?= h($loan['shipping_tracking'] ?: '—') ?></dd>

            <dt class="col-sm-3">Chamado GLPI</dt>
            <dd class="col-sm-9"><?= h($loan['chamado_glpi'] ?? '') ?></dd>

            <dt class="col-sm-3">Disponibilizado por</dt>
            <dd class="col-sm-9"><?= h($loan['responsavel']) ?></dd>

            <dt class="col-sm-3">Status</dt>
            <dd class="col-sm-9"><span class="badge bg-secondary"><?= t_status($loan['status']) ?></span></dd>

            <dt class="col-sm-3">Descrição</dt>
            <dd class="col-sm-9"><pre class="mb-0" style="white-space:pre-wrap;"><?= h($loan['descricao'] ?? '') ?></pre></dd>
          </dl>
        </div>
      </div>

      <div class="card border-0 shadow-sm mt-3">
        <div class="card-header bg-white">Itens deste empréstimo</div>
        <div class="card-body p-0">
          <div class="table-responsive">
            <table class="table mb-0">
              <thead>
                <tr><th>#</th><th>Tipo/Modelo</th><th>Patrimônio</th><th>Serial</th><th>Status</th></tr>
              </thead>
              <tbody>
                <?php foreach ($items as $it): ?>
                  <tr>
                    <td>#<?= (int)$it['equipment_id'] ?></td>
                    <td><?= h(($it['tipo'] ?? '—') . ($it['modelo'] ? ' • '.$it['modelo'] : '')) ?></td>
                    <td><?= h($it['patrimonio'] ?? '—') ?></td>
                    <td><?= h($it['serial'] ?? '—') ?></td>
                    <td><span class="badge bg-secondary"><?= t_status($it['status']) ?></span></td>
                  </tr>
                <?php endforeach; ?>
                <?php if (!$items): ?>
                  <tr><td colspan="5" class="text-muted">Sem itens vinculados.</td></tr>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>

        <?php if (!$items): ?>
          <div class="p-3">
            <a class="btn btn-outline-primary" href="<?= base_url('loan_attach_items.php?loan_id='.(int)$loan['id']) ?>">
              <i class="bi bi-link-45deg me-1"></i>Anexar itens do estoque a este empréstimo
            </a>
          </div>
        <?php endif; ?>
      </div>

      <a class="btn btn-success mt-3" href="<?= base_url('return_checklist.php?loan_id='.(int)$loan['id']) ?>">
        <i class="bi bi-clipboard-check me-1"></i>Checklist de devolução
      </a>
    </div>

    <div class="col-xl-4">
      <div class="card border-0 shadow-sm mb-3">
        <div class="card-header bg-white">Anexar termo</div>
        <div class="card-body">
          <form action="<?= base_url('upload_term.php') ?>" method="post" enctype="multipart/form-data">
            <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="loan_id" value="<?= (int)$loan['id'] ?>">
            <div class="mb-3">
              <input type="file" name="file" class="form-control" accept=".pdf,.png,.jpg,.jpeg" required>
              <div class="form-text">PDF/PNG/JPG até 10 MB.</div>
            </div>
            <button class="btn btn-primary">Enviar</button>
          </form>
        </div>
      </div>

      <div class="card border-0 shadow-sm">
        <div class="card-header bg-white">Termos anexados</div>
        <div class="list-group list-group-flush">
          <?php foreach ($terms as $t): ?>
            <a class="list-group-item list-group-item-action d-flex justify-content-between align-items-center"
               href="<?= base_url('term_download.php?id='.(int)$t['id']) ?>">
              <span><i class="bi bi-file-earmark-text me-2"></i><?= h($t['filename_original']) ?></span>
              <span class="text-muted small">#<?= (int)$t['id'] ?></span>
            </a>
          <?php endforeach; ?>
          <?php if (!$terms): ?>
            <div class="list-group-item text-muted">Nenhum termo anexado.</div>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
</div>
<?php include __DIR__ . '/footer.php'; ?>

