<?php
// equipment.php — Lista (agregada/detalhada), busca, exclusão (admin), edição e cadastro com lote
$title = 'Equipamentos / Estoque';
require_once __DIR__ . '/auth.php';
require_login();
require_perm('equipment.view');
check_csrf();

/* ----------------------------- helpers de schema ----------------------------- */
function eq_has_col($name){
  static $cols=null; global $pdo;
  if($cols===null){
    $cols=[];
    $q=$pdo->query("SELECT COLUMN_NAME FROM information_schema.COLUMNS
                    WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='equipment'");
    foreach($q as $r) $cols[$r['COLUMN_NAME']]=true;
  }
  return isset($cols[$name]);
}
function is_admin_role(){
  return user_has_perm('equipment.*');
}

/* ------------------------------- POST: criar -------------------------------- */
$err=''; $ok='';
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action'] ?? '')==='create') {
  require_perm('equipment.*');

  $type_id  = (int)($_POST['type_id'] ?? 0);
  $modelo   = trim($_POST['modelo'] ?? '');
  $patr     = trim($_POST['patrimonio'] ?? '');
  $serial   = trim($_POST['serial'] ?? '');
  $status   = trim($_POST['status'] ?? 'EM_ESTOQUE');
  $loc_id   = (int)($_POST['location_id'] ?? 0);
  $qtd_lote = max(1, (int)($_POST['qtd_lote'] ?? 1));

  // adicionais (guardar somente se a coluna existir)
  $condicao = trim($_POST['condicao'] ?? 'NOVO');
  $forn     = trim($_POST['fornecedor'] ?? '');
  $nf       = trim($_POST['nota_fiscal'] ?? '');
  $dtCompra = $_POST['data_compra'] ?: null;
  $vlCompra = $_POST['valor_compra'] ?? null;
  if ($vlCompra!=='') $vlCompra = str_replace(['.',' '],'', str_replace(',','.',$vlCompra));
  $garMeses = ($_POST['garantia_meses']!=='') ? (int)$_POST['garantia_meses'] : null;
  $garAte   = $_POST['garantia_ate'] ?: null;
  $garForn  = trim($_POST['garantia_fornecedor'] ?? '');
  $acess    = trim($_POST['acessorios'] ?? '');
  $obsCond  = trim($_POST['obs_condicao'] ?? '');

  if ($type_id<=0)        $err='Selecione o tipo.';
  elseif ($modelo==='')   $err='Informe o modelo.';

  if (!$garAte && $garMeses && $dtCompra) {
    try { $d=new DateTime($dtCompra); $d->modify("+{$garMeses} months"); $garAte=$d->format('Y-m-d'); } catch(Throwable $e){}
  }

  if ($err==='') {
    try {
      $cols = ['type_id','modelo','patrimonio','serial','status','location_id'];
      $valsTmpl = [$type_id, null, null, null, $status, $loc_id];

      if (eq_has_col('condicao'))            { $cols[]='condicao';            $valsTmpl[]=$condicao; }
      if (eq_has_col('fornecedor'))          { $cols[]='fornecedor';          $valsTmpl[]=$forn; }
      if (eq_has_col('nota_fiscal'))         { $cols[]='nota_fiscal';         $valsTmpl[]=$nf; }
      if (eq_has_col('data_compra'))         { $cols[]='data_compra';         $valsTmpl[]=$dtCompra; }
      if (eq_has_col('valor_compra'))        { $cols[]='valor_compra';        $valsTmpl[]=($vlCompra!==''?$vlCompra:null); }
      if (eq_has_col('garantia_meses'))      { $cols[]='garantia_meses';      $valsTmpl[]=$garMeses; }
      if (eq_has_col('garantia_ate'))        { $cols[]='garantia_ate';        $valsTmpl[]=$garAte; }
      if (eq_has_col('garantia_fornecedor')) { $cols[]='garantia_fornecedor'; $valsTmpl[]=$garForn; }
      if (eq_has_col('acessorios'))          { $cols[]='acessorios';          $valsTmpl[]=$acess; }
      if (eq_has_col('obs_condicao'))        { $cols[]='obs_condicao';        $valsTmpl[]=$obsCond; }

      $ph = implode(',', array_fill(0, count($cols), '?'));
      $sql = "INSERT INTO equipment (".implode(',', $cols).") VALUES ($ph)";
      $ins = $pdo->prepare($sql);

      $pdo->beginTransaction();
      for ($i=0; $i<$qtd_lote; $i++){
        $vals = $valsTmpl;
        // modelo
        $vals[array_search('modelo',$cols)] = $modelo;
        // PAT/SN só na 1ª peça para evitar duplicidade quando há UNIQUE
        $vals[array_search('patrimonio',$cols)] = ($i===0 ? ($patr?:null) : null);
        $vals[array_search('serial',$cols)]     = ($i===0 ? ($serial?:null) : null);
        $ins->execute($vals);
      }
      $pdo->commit();
      $ok = "Equipamento(s) cadastrado(s) com sucesso.";
    } catch(Throwable $e){
      if ($pdo->inTransaction()) $pdo->rollBack();
      $err='Erro ao salvar: '.$e->getMessage();
    }
  }
}

/* -------------------------- POST: excluir selecionados ----------------------- */
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action'] ?? '')==='bulk_delete') {
  require_perm('equipment.*');
  $ids = array_map('intval', $_POST['selected'] ?? []);
  if ($ids){
    try{
      $in = implode(',', array_fill(0,count($ids),'?'));
      $pdo->prepare("DELETE FROM equipment WHERE id IN ($in)")->execute($ids);
      $ok = 'Registros excluídos.';
    }catch(Throwable $e){ $err='Erro ao excluir: '.$e->getMessage(); }
  }
}

/* -------------------------------- POST: update ------------------------------ */
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action'] ?? '')==='update_one') {
  require_perm('equipment.*');
  $id = (int)($_POST['id'] ?? 0);
  if ($id>0){
    $modelo = trim($_POST['u_modelo'] ?? '');
    $patr   = trim($_POST['u_patrimonio'] ?? '');
    $serial = trim($_POST['u_serial'] ?? '');
    $status = trim($_POST['u_status'] ?? '');
    $loc_id = (int)($_POST['u_location_id'] ?? 0);
    $cond   = trim($_POST['u_condicao'] ?? '');

    try{
      $set = ['modelo=?','patrimonio=?','serial=?','status=?','location_id=?'];
      $vals= [$modelo, ($patr!==''?$patr:null), ($serial!==''?$serial:null), $status, $loc_id];
      if (eq_has_col('condicao')) { $set[]='condicao=?'; $vals[]=$cond; }
      $vals[]=$id;
      $sql = "UPDATE equipment SET ".implode(',',$set)." WHERE id=?";
      $pdo->prepare($sql)->execute($vals);
      $ok='Registro atualizado.';
    }catch(Throwable $e){ $err='Erro ao atualizar: '.$e->getMessage(); }
  }
}

/* ---------------------------------- filtros --------------------------------- */
$status_f = $_GET['status'] ?? '';
$type_f   = (int)($_GET['type'] ?? 0);
$q        = trim($_GET['q'] ?? '');
$detailed = isset($_GET['detailed']) && $_GET['detailed']=='1'; // visão item-a-item

$where = []; $bind=[];
if ($status_f!==''){ $where[]='e.status=?'; $bind[]=$status_f; }
if ($type_f>0)     { $where[]='e.type_id=?'; $bind[]=$type_f; }
if ($q!==''){
  $where[]="(t.name LIKE ? OR e.modelo LIKE ? OR e.patrimonio LIKE ? OR e.serial LIKE ? OR l.name LIKE ?)";
  $bind[]=$bind[]=$bind[]=$bind[]=$bind[]="%{$q}%";
}

/* -------------------------------- listagens --------------------------------- */
$types = $pdo->query("SELECT id,name FROM equipment_types ORDER BY name")->fetchAll();
$locs  = $pdo->query("SELECT id,name FROM locations ORDER BY name")->fetchAll();

if (!$detailed){
  // VISÃO AGREGADA (lote compacto)
  $sql = "SELECT
            e.type_id, t.name AS tipo, e.modelo, COALESCE(e.condicao,'—') AS condicao,
            e.location_id, COALESCE(l.name,'—') AS local_name,
            e.status, COUNT(*) AS qtd,
            MIN(e.id) AS sample_id
          FROM equipment e
          LEFT JOIN equipment_types t ON t.id=e.type_id
          LEFT JOIN locations l ON l.id=e.location_id";
  if ($where) $sql .= " WHERE ".implode(' AND ',$where);
  // Apenas colunas do GROUP BY + agregadas no ORDER BY (evita ONLY_FULL_GROUP_BY)
  $sql .= " GROUP BY e.type_id, e.modelo, e.condicao, e.location_id, e.status
            ORDER BY t.name, e.modelo, sample_id DESC";
  $rows = $pdo->prepare($sql); $rows->execute($bind); $rows=$rows->fetchAll(PDO::FETCH_ASSOC);
} else {
  // VISÃO DETALHADA
  $sql = "SELECT e.*, t.name AS tipo, l.name AS local_name
            FROM equipment e
            LEFT JOIN equipment_types t ON t.id=e.type_id
            LEFT JOIN locations l ON l.id=e.location_id";
  if ($where) $sql .= " WHERE ".implode(' AND ',$where);
  $sql .= " ORDER BY e.id DESC";
  $rows = $pdo->prepare($sql); $rows->execute($bind); $rows=$rows->fetchAll(PDO::FETCH_ASSOC);
}

include __DIR__ . '/header.php';
?>
<div class="container-fluid">
  <div class="d-flex align-items-center mb-3 gap-2">
    <h2 class="h5 m-0">Equipamentos</h2>

    <form class="ms-auto d-flex gap-2" method="get">
      <input type="hidden" name="detailed" value="<?= $detailed?'1':'0' ?>">
      <select name="status" class="form-select form-select-sm" style="width:170px">
        <option value="">Status (todos)</option>
        <?php foreach (['EM_ESTOQUE'=>'Em estoque','EMPRESTADO'=>'Emprestado','MANUTENCAO'=>'Manutenção','DEFEITO'=>'Defeito','BAIXADO'=>'Baixado','FURTO'=>'Furto/Extravio'] as $k=>$v): ?>
          <option value="<?= h($k) ?>" <?= $status_f===$k?'selected':'' ?>><?= h($v) ?></option>
        <?php endforeach; ?>
      </select>
      <select name="type" class="form-select form-select-sm" style="width:160px">
        <option value="0">Tipo (todos)</option>
        <?php foreach($types as $t): ?>
          <option value="<?= (int)$t['id'] ?>" <?= $type_f==$t['id']?'selected':'' ?>><?= h($t['name']) ?></option>
        <?php endforeach; ?>
      </select>
      <input class="form-control form-control-sm" style="width:260px" name="q" value="<?= h($q) ?>" placeholder="Buscar: modelo, PAT, SN, local…">
      <button class="btn btn-sm btn-outline-primary">Filtrar</button>
      <a class="btn btn-sm btn-outline-secondary" href="<?= base_url('equipment.php') ?>">Limpar</a>
      <a class="btn btn-sm <?= $detailed?'btn-outline-secondary':'btn-outline-dark' ?>"
         href="?<?= http_build_query(['status'=>$status_f,'type'=>$type_f,'q'=>$q,'detailed'=>$detailed?0:1]) ?>">
        <?= $detailed ? 'Exibir agregado' : 'Exibir detalhado' ?>
      </a>
      <?php if (is_admin_role()): ?>
        <button class="btn btn-primary btn-sm" type="button" data-bs-toggle="modal" data-bs-target="#modalNew">
          <i class="bi bi-plus-lg me-1"></i>Novo
        </button>
      <?php endif; ?>
    </form>
  </div>

  <?php if ($err): ?><div class="alert alert-danger"><?= h($err) ?></div><?php endif; ?>
  <?php if ($ok):  ?><div class="alert alert-success"><?= h($ok)  ?></div><?php endif; ?>

  <div class="card border-0 shadow-sm">
    <div class="table-responsive">
      <form method="post">
        <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
        <input type="hidden" name="action" value="bulk_delete">
        <table class="table table-striped align-middle mb-0">
          <thead>
            <tr>
              <?php if ($detailed && is_admin_role()): ?>
                <th style="width:32px">
                  <input class="form-check-input" type="checkbox" onclick="document.querySelectorAll('.rowcheck').forEach(c=>c.checked=this.checked)">
                </th>
              <?php else: ?>
                <th style="width:32px"></th>
              <?php endif; ?>
              <th>Tipo/Modelo</th>
              <th>Condição</th>
              <th>Garantia</th>
              <th>Local</th>
              <th>Status</th>
              <th class="text-end">Ações</th>
            </tr>
          </thead>
          <tbody>
          <?php if (!$detailed): // agregado ?>
            <?php foreach ($rows as $r): ?>
              <tr>
                <td></td>
                <td>
                  <?= h(($r['tipo'] ?? '—').' • '.$r['modelo']) ?>
                  <span class="badge text-bg-light border ms-2">×<?= (int)$r['qtd'] ?></span>
                </td>
                <td><?= h($r['condicao'] ?? '—') ?></td>
                <td>—</td>
                <td><?= h($r['local_name'] ?? '—') ?></td>
                <td><span class="badge bg-secondary"><?= h(t_status($r['status'])) ?></span></td>
                <td class="text-end">
                  <a class="btn btn-outline-secondary btn-sm"
                     title="Listar itens"
                     href="?<?= http_build_query([
                          'detailed'=>1,
                          'status'=>$status_f?:$r['status'],
                          'type'=>$type_f?:$r['type_id'],
                          'q'=>$q!==''?$q:($r['modelo'])
                     ]) ?>">
                    <i class="bi bi-list-ul"></i>
                  </a>
                </td>
              </tr>
            <?php endforeach; ?>
            <?php if (!$rows): ?>
              <tr><td colspan="7" class="text-muted">Nenhum equipamento.</td></tr>
            <?php endif; ?>
          <?php else: // detalhado ?>
            <?php foreach ($rows as $r): ?>
              <tr>
                <?php if (is_admin_role()): ?>
                  <td><input class="form-check-input rowcheck" type="checkbox" name="selected[]" value="<?= (int)$r['id'] ?>"></td>
                <?php else: ?><td></td><?php endif; ?>
                <td><?= h(($r['tipo'] ?? '—').' • '.$r['modelo']) ?></td>
                <td><?= h($r['condicao'] ?? '—') ?></td>
                <td><?= h($r['garantia_ate'] ?? '—') ?></td>
                <td><?= h($r['local_name'] ?? '—') ?></td>
                <td><span class="badge bg-secondary"><?= h(t_status($r['status'])) ?></span></td>
                <td class="text-end">
                  <div class="btn-group btn-group-sm">
                    <a class="btn btn-outline-secondary" title="Histórico"
                       href="<?= base_url('equipment_history.php?id='.(int)$r['id']) ?>">
                      <i class="bi bi-clock-history"></i>
                    </a>
                    <a class="btn btn-outline-secondary" title="QR"
                       href="<?= base_url('qr_label.php?id='.(int)$r['id']) ?>">
                      <i class="bi bi-qr-code"></i>
                    </a>
                    <?php if (is_admin_role()): ?>
                      <button type="button" class="btn btn-outline-secondary"
                              title="Editar" data-bs-toggle="modal" data-bs-target="#modalEdit"
                              data-id="<?= (int)$r['id'] ?>"
                              data-modelo="<?= h($r['modelo']) ?>"
                              data-patrimonio="<?= h($r['patrimonio']) ?>"
                              data-serial="<?= h($r['serial']) ?>"
                              data-status="<?= h($r['status']) ?>"
                              data-location="<?= (int)($r['location_id'] ?? 0) ?>"
                              data-condicao="<?= h($r['condicao'] ?? '') ?>">
                        <i class="bi bi-pencil"></i>
                      </button>
                    <?php endif; ?>
                    <a class="btn btn-outline-secondary" title="Ações"
                       href="<?= base_url('stock.php?focus='.(int)$r['id']) ?>">
                      <i class="bi bi-sliders"></i>
                    </a>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
            <?php if (!$rows): ?>
              <tr><td colspan="7" class="text-muted">Nenhum equipamento.</td></tr>
            <?php endif; ?>
          <?php endif; ?>
          </tbody>
        </table>

        <?php if ($detailed && is_admin_role()): ?>
          <div class="p-2 border-top bg-light d-flex justify-content-between align-items-center">
            <span class="text-muted small">Selecione linhas para excluir.</span>
            <button class="btn btn-danger btn-sm"
                    onclick="return confirm('Excluir os selecionados? Esta ação não pode ser desfeita.')">
              Excluir selecionados
            </button>
          </div>
        <?php endif; ?>
      </form>
    </div>
  </div>
</div>

<?php if (is_admin_role()): ?>
<!-- Modal Novo equipamento -->
<div class="modal fade" id="modalNew" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <form class="modal-content" method="post">
      <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
      <input type="hidden" name="action" value="create">
      <div class="modal-header">
        <h5 class="modal-title">Novo equipamento</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fechar"></button>
      </div>
      <div class="modal-body">
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label">Tipo</label>
            <select name="type_id" class="form-select" required>
              <?php foreach($types as $t): ?>
                <option value="<?= (int)$t['id'] ?>"><?= h($t['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">Modelo</label>
            <input name="modelo" class="form-control" required>
          </div>

          <div class="col-md-4">
            <label class="form-label">Quantidade (lote)</label>
            <input type="number" min="1" name="qtd_lote" value="1" class="form-control">
            <div class="form-text">Cria N peças idênticas. PAT/SN serão usados apenas na 1ª peça.</div>
          </div>
          <div class="col-md-4">
            <label class="form-label">Patrimônio</label>
            <input name="patrimonio" class="form-control" placeholder="(opcional)">
          </div>
          <div class="col-md-4">
            <label class="form-label">Serial</label>
            <input name="serial" class="form-control" placeholder="(opcional)">
          </div>

          <div class="col-md-6">
            <label class="form-label">Local</label>
            <select name="location_id" class="form-select">
              <option value="0">—</option>
              <?php foreach($locs as $l): ?>
                <option value="<?= (int)$l['id'] ?>"><?= h($l['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">Status</label>
            <select name="status" class="form-select">
              <option value="EM_ESTOQUE">Em estoque</option>
              <option value="EMPRESTADO">Emprestado</option>
              <option value="MANUTENCAO">Manutenção</option>
              <option value="DEFEITO">Defeito</option>
              <option value="BAIXADO">Baixado</option>
              <option value="FURTO">Furto/Extravio</option>
            </select>
          </div>

          <div class="col-12"><hr></div>

          <div class="col-md-6">
            <label class="form-label">Condição</label>
            <div class="d-flex gap-3">
              <div class="form-check">
                <input class="form-check-input" type="radio" name="condicao" id="cNovo" value="NOVO" checked>
                <label class="form-check-label" for="cNovo">Novo</label>
              </div>
              <div class="form-check">
                <input class="form-check-input" type="radio" name="condicao" id="cSemi" value="SEMINOVO">
                <label class="form-check-label" for="cSemi">Seminovo</label>
              </div>
            </div>
          </div>
          <div class="col-md-6">
            <label class="form-label">Fornecedor</label>
            <input name="fornecedor" class="form-control" placeholder="Razão social / loja">
          </div>

          <div class="col-md-4">
            <label class="form-label">Nota fiscal</label>
            <input name="nota_fiscal" class="form-control" placeholder="NF-e">
          </div>
          <div class="col-md-4">
            <label class="form-label">Data de compra</label>
            <input type="date" name="data_compra" class="form-control" id="dtCompra">
          </div>
          <div class="col-md-4">
            <label class="form-label">Valor de compra</label>
            <input name="valor_compra" class="form-control" placeholder="0,00">
          </div>

          <div class="col-md-4">
            <label class="form-label">Garantia (meses)</label>
            <input type="number" min="0" name="garantia_meses" class="form-control" id="garMeses">
          </div>
          <div class="col-md-4">
            <label class="form-label">Garantia até</label>
            <input type="date" name="garantia_ate" class="form-control" id="garAte">
            <div class="form-text">Calculado se informar meses + data compra.</div>
          </div>
          <div class="col-md-4">
            <label class="form-label">Garantia — fornecedor</label>
            <input name="garantia_fornecedor" class="form-control">
          </div>

          <div class="col-md-6">
            <label class="form-label">Acessórios enviados</label>
            <input name="acessorios" class="form-control" placeholder="Fonte, cabo, case…">
          </div>
          <div class="col-md-6">
            <label class="form-label">Condição (observações)</label>
            <textarea name="obs_condicao" class="form-control" rows="2"></textarea>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary">Salvar</button>
      </div>
    </form>
  </div>
</div>
<?php endif; ?>

<!-- Modal Editar -->
<div class="modal fade" id="modalEdit" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <form class="modal-content" method="post">
      <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
      <input type="hidden" name="action" value="update_one">
      <input type="hidden" name="id" id="u_id">
      <div class="modal-header">
        <h5 class="modal-title">Editar equipamento</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fechar"></button>
      </div>
      <div class="modal-body">
        <div class="row g-3">
          <div class="col-12">
            <label class="form-label">Modelo</label>
            <input class="form-control" name="u_modelo" id="u_modelo" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Patrimônio</label>
            <input class="form-control" name="u_patrimonio" id="u_patrimonio">
          </div>
          <div class="col-md-6">
            <label class="form-label">Serial</label>
            <input class="form-control" name="u_serial" id="u_serial">
          </div>
          <div class="col-md-6">
            <label class="form-label">Status</label>
            <select name="u_status" id="u_status" class="form-select">
              <option value="EM_ESTOQUE">Em estoque</option>
              <option value="EMPRESTADO">Emprestado</option>
              <option value="MANUTENCAO">Manutenção</option>
              <option value="DEFEITO">Defeito</option>
              <option value="BAIXADO">Baixado</option>
              <option value="FURTO">Furto/Extravio</option>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">Local</label>
            <select name="u_location_id" id="u_location" class="form-select">
              <option value="0">—</option>
              <?php foreach($locs as $l): ?>
                <option value="<?= (int)$l['id'] ?>"><?= h($l['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <?php if (eq_has_col('condicao')): ?>
          <div class="col-12">
            <label class="form-label">Condição</label>
            <select name="u_condicao" id="u_condicao" class="form-select">
              <option value="">—</option>
              <option value="NOVO">Novo</option>
              <option value="SEMINOVO">Seminovo</option>
            </select>
          </div>
          <?php endif; ?>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary">Salvar alterações</button>
      </div>
    </form>
  </div>
</div>

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

