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

$loan_id = (int)($_GET['loan_id'] ?? $_POST['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'); }

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $ids = array_map('intval', $_POST['equipment_ids'] ?? []);
  $ids = array_values(array_filter($ids));
  if (count($ids) === 0) { $error = 'Selecione ao menos 1 item.'; }
  else {
    try {
      $pdo->beginTransaction();
      $ph = implode(',', array_fill(0, count($ids), '?'));
      $sel = $pdo->prepare("SELECT id, status FROM equipment WHERE id IN ($ph) FOR UPDATE");
      $sel->execute($ids);
      $found = $sel->fetchAll();
      if (count($found) !== count($ids)) throw new Exception('Itens inexistentes.');
      foreach ($found as $r) { if ($r['status'] !== 'EM_ESTOQUE') throw new Exception('Um item já não está em estoque.'); }

      $ins = $pdo->prepare('INSERT INTO loan_items (loan_id, equipment_id) VALUES (?,?)');
      $up  = $pdo->prepare("UPDATE equipment SET status='EMPRESTADO' WHERE id=?");
      $log = $pdo->prepare("INSERT INTO equipment_log (equipment_id,user_id,loan_id,action,from_status,to_status,notes) VALUES (?,?,?,?,?,?,?)");
      $noteBase = 'Emp: '.($loan['matricula'] ?? '').' • '.($loan['nome'] ?? '').' (anexado)';
      foreach ($ids as $eid) {
        $ins->execute([$loan_id, $eid]);
        $up->execute([$eid]);
        $log->execute([$eid, current_user()['id'], $loan_id, 'LOANED', 'EM_ESTOQUE', 'EMPRESTADO', $noteBase]);
      }

      // Atualiza quantidade = total de itens vinculados
      $pdo->prepare('UPDATE loans SET quantidade=(SELECT COUNT(*) FROM loan_items WHERE loan_id=?) WHERE id=?')
          ->execute([$loan_id, $loan_id]);

      $pdo->commit();
      header('Location: ' . base_url('loan_view.php?id='.$loan_id)); exit;
    } catch (Exception $e) {
      if ($pdo->inTransaction()) $pdo->rollBack();
      $error = $e->getMessage();
    }
  }
}

$equipAvail = $pdo->query("SELECT e.id, e.patrimonio, e.serial, et.name tipo, e.modelo
  FROM equipment e JOIN equipment_types et ON et.id=e.type_id
  WHERE e.status='EM_ESTOQUE' ORDER BY e.id DESC LIMIT 500")->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">Anexar itens — 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>

  <?php if (!empty($error)): ?><div class="alert alert-danger"><?= h($error) ?></div><?php endif; ?>

  <div class="card border-0 shadow-sm">
    <div class="card-body">
      <div class="mb-2"><strong>Colaborador:</strong> <?= h($loan['matricula'].' • '.$loan['nome']) ?></div>
      <form method="post">
        <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
        <input type="hidden" name="loan_id" value="<?= (int)$loan['id'] ?>">
        <label class="form-label">Selecionar itens (estoque)</label>
        <select name="equipment_ids[]" class="form-select" multiple size="10" required>
          <?php foreach ($equipAvail as $it): ?>
            <option value="<?= (int)$it['id'] ?>">#<?= (int)$it['id'] ?> • <?= h($it['tipo']) ?> <?= h($it['modelo'] ? '• '.$it['modelo'] : '') ?><?= h($it['patrimonio'] ? ' • PAT '.$it['patrimonio'] : '') ?><?= h($it['serial'] ? ' • SN '.$it['serial'] : '') ?></option>
          <?php endforeach; ?>
        </select>
        <div class="form-text">Os itens selecionados serão marcados como emprestados e adicionados ao empréstimo.</div>
        <button class="btn btn-primary mt-3">Anexar itens</button>
      </form>
    </div>
  </div>
</div>
<?php include __DIR__ . '/footer.php'; ?>
