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

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

/* Solicitação + colaborador */
$rr = $pdo->prepare("
  SELECT rr.*, e.matricula, e.nome
  FROM return_requests rr
  JOIN employees e ON e.id = rr.employee_id
  WHERE rr.id = ?
");
$rr->execute([$id]);
$rr = $rr->fetch();
if (!$rr) { http_response_code(404); exit('Solicitação não encontrada'); }

/* Itens da solicitação + status atual do equipamento */
$items = $pdo->prepare("
  SELECT i.*, e.patrimonio, e.serial, et.name tipo, e.modelo, e.status AS eq_status, i.loan_id
  FROM return_request_items i
  JOIN equipment e        ON e.id = i.equipment_id
  JOIN equipment_types et ON et.id = e.type_id
  WHERE i.request_id = ?
  ORDER BY i.id ASC
");
$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">Solicitação de devolução</h2>
    <a class="btn btn-outline-secondary" href="<?= base_url('return_requests.php') ?>">Voltar</a>
  </div>

  <div class="row g-3">
    <div class="col-xl-8">
      <!-- Detalhes -->
      <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($rr['matricula'].' • '.$rr['nome']) ?></dd>

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

            <dt class="col-sm-3">Origem</dt>
            <dd class="col-sm-9"><?= h($rr['source']) ?></dd>

            <dt class="col-sm-3">Prazo</dt>
            <dd class="col-sm-9"><?= br_date($rr['deadline'] ?? null) ?></dd>

            <dt class="col-sm-3">Observações</dt>
            <dd class="col-sm-9"><pre class="mb-0" style="white-space:pre-wrap;"><?= h($rr['notes'] ?? '') ?></pre></dd>

            <?php if ($rr['charge_amount'] !== null): ?>
              <dt class="col-sm-3">Cobrança</dt>
              <dd class="col-sm-9">
                R$ <?= number_format((float)$rr['charge_amount'], 2, ',', '.') ?>
                <?= $rr['charge_notes'] ? ' — '.h($rr['charge_notes']) : '' ?>
              </dd>
            <?php endif; ?>

            <dt class="col-sm-3">Criada em</dt>
            <dd class="col-sm-9"><?= br_datetime($rr['created_at'] ?? null) ?></dd>

            <dt class="col-sm-3">Atualizada</dt>
            <dd class="col-sm-9"><?= br_datetime($rr['updated_at'] ?? null) ?></dd>
          </dl>
        </div>
      </div>

      <!-- Itens -->
      <div class="card border-0 shadow-sm mt-3">
        <div class="card-header bg-white">Itens vinculados</div>
        <div class="card-body p-0">
          <div class="table-responsive">
            <table class="table mb-0 align-middle table-striped">
              <thead>
                <tr>
                  <th>Item</th>
                  <th>PAT</th>
                  <th>SN</th>
                  <th>Status atual</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($items as $it): ?>
                  <?php
                    // Considera devolvido quando o item já voltou ao estoque/manutenção
                    $devolvido = in_array($it['eq_status'], ['EM_ESTOQUE','MANUTENCAO'], true);
                  ?>
                  <tr class="<?= $devolvido ? 'table-success' : '' ?>">
                    <td><?= h(($it['tipo'] ?? '—').($it['modelo'] ? ' • '.$it['modelo'] : '')) ?></td>
                    <td><?= h($it['patrimonio'] ?? '—') ?></td>
                    <td><?= h($it['serial'] ?? '—') ?></td>
                    <td>
                      <?php if ($devolvido): ?>
                        <span class="badge bg-success">Devolvido</span>
                      <?php else: ?>
                        <span class="badge bg-warning text-dark">Pendente</span>
                        <div class="small text-muted">Equipamento: <?= t_status($it['eq_status']) ?></div>
                      <?php endif; ?>
                    </td>
                    <td class="text-end">
                      <a class="btn btn-sm btn-outline-primary"
                         href="<?= base_url('return_checklist.php?loan_id='.(int)$it['loan_id']) ?>">
                        Processar devolução
                      </a>
                    </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>
      </div>

    </div>
    <div class="col-xl-4">
      <!-- Ações de status -->
      <div class="card border-0 shadow-sm mb-3">
        <div class="card-header bg-white">Ações</div>
        <div class="card-body">
          <form class="mb-2" method="post" action="<?= base_url('return_request_update.php') ?>">
            <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="id" value="<?= (int)$rr['id'] ?>">
            <div class="d-grid gap-2">
              <button name="action" value="set_in_progress" class="btn btn-outline-primary" <?= $rr['status']==='ABERTA' ? '' : 'disabled' ?>>Iniciar atendimento</button>
              <button name="action" value="set_done" class="btn btn-success" <?= in_array($rr['status'], ['ABERTA','EM_ANDAMENTO'], true) ? '' : 'disabled' ?>>Concluir (todos devolvidos)</button>
              <button name="action" value="set_cancel" class="btn btn-outline-secondary" <?= in_array($rr['status'], ['ABERTA','EM_ANDAMENTO'], true) ? '' : 'disabled' ?>>Cancelar</button>
            </div>
          </form>

          <hr>
          <!-- Cobrança -->
          <form method="post" action="<?= base_url('return_request_update.php') ?>">
            <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="id" value="<?= (int)$rr['id'] ?>">
            <div class="mb-2">
              <label class="form-label">Cobrança (quando não devolver)</label>
              <div class="input-group">
                <span class="input-group-text">R$</span>
                <input name="charge_amount" type="number" step="0.01" min="0" class="form-control" placeholder="0,00">
              </div>
            </div>
            <div class="mb-2">
              <input name="charge_notes" class="form-control" placeholder="Observações (ex.: valor conforme NF 123)">
            </div>
            <button name="action" value="set_charge" class="btn btn-warning w-100">Marcar como cobrança</button>
          </form>
        </div>
      </div>

      <!-- Prazo / Observações -->
      <div class="card border-0 shadow-sm">
        <div class="card-header bg-white">Prazo/Observações</div>
        <div class="card-body">
          <form method="post" action="<?= base_url('return_request_update.php') ?>">
            <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="id" value="<?= (int)$rr['id'] ?>">
            <div class="mb-2">
              <label class="form-label">Prazo</label>
              <input type="date" name="deadline" class="form-control" value="<?= h($rr['deadline'] ?? '') ?>">
            </div>
            <div class="mb-2">
              <label class="form-label">Observações</label>
              <textarea name="notes" class="form-control" rows="3"><?= h($rr['notes'] ?? '') ?></textarea>
            </div>
            <button name="action" value="update_meta" class="btn btn-outline-primary w-100">Salvar</button>
          </form>
        </div>
      </div>

    </div>
  </div>
</div>
<?php include __DIR__ . '/footer.php'; ?>

