<?php
declare(strict_types=1);

$config = require __DIR__ . '/app/config.php';
require __DIR__ . '/app/db.php';
require __DIR__ . '/app/auth.php';
require __DIR__ . '/app/helpers.php';
require __DIR__ . '/app/acl.php';
require __DIR__ . '/app/layout.php';

require_login($config);
require_role($config, ['admin','manager','finance','ops']);

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

$row = [
  'name' => '',
  'nif' => '',
  'email' => '',
  'phone' => '',
  'address' => '',
  'notes' => '',
  'is_active' => 1
];

if ($editing) {
  $st = $pdo->prepare("SELECT * FROM suppliers WHERE id=?");
  $st->execute([$id]);
  $dbRow = $st->fetch();
  if (!$dbRow) { header('Location: suppliers.php'); exit; }
  $row = array_merge($row, $dbRow);
}

$err = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();

  $name = trim((string)($_POST['name'] ?? ''));
  $nif = trim((string)($_POST['nif'] ?? ''));
  $email = trim((string)($_POST['email'] ?? ''));
  $phone = trim((string)($_POST['phone'] ?? ''));
  $address = trim((string)($_POST['address'] ?? ''));
  $notes = trim((string)($_POST['notes'] ?? ''));
  $isActive = (int)($_POST['is_active'] ?? 1) ? 1 : 0;

  if ($name === '') $err = 'Nome é obrigatório.';

  if (!$err) {
    if ($editing) {
      $st = $pdo->prepare("UPDATE suppliers SET name=?, nif=?, email=?, phone=?, address=?, notes=?, is_active=? WHERE id=?");
      $st->execute([$name,$nif,$email,$phone,$address,$notes,$isActive,$id]);
    } else {
      $st = $pdo->prepare("INSERT INTO suppliers (name,nif,email,phone,address,notes,is_active) VALUES (?,?,?,?,?,?,?)");
      $st->execute([$name,$nif,$email,$phone,$address,$notes,$isActive]);
      $id = (int)$pdo->lastInsertId();
    }
    header('Location: suppliers.php');
    exit;
  }

  $row = ['name'=>$name,'nif'=>$nif,'email'=>$email,'phone'=>$phone,'address'=>$address,'notes'=>$notes,'is_active'=>$isActive];
}

render_header($config, $editing ? 'Fornecedor' : 'Novo fornecedor');
?>
<div class="card">
  <h1 style="margin-top:0"><?= $editing ? 'Fornecedor' : 'Novo fornecedor' ?></h1>
  <?php if ($err): ?><p class="badge roi-red"><?= e($err) ?></p><?php endif; ?>

  <form method="post" class="grid" style="grid-template-columns:repeat(2,1fr);gap:12px">
    <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">

    <div>
      <label>Nome *</label>
      <input name="name" value="<?= e((string)$row['name']) ?>" required>
    </div>
    <div>
      <label>NIF</label>
      <input name="nif" value="<?= e((string)$row['nif']) ?>">
    </div>

    <div>
      <label>Telefone</label>
      <input name="phone" value="<?= e((string)$row['phone']) ?>">
    </div>
    <div>
      <label>Email</label>
      <input name="email" value="<?= e((string)$row['email']) ?>">
    </div>

    <div style="grid-column:1 / -1">
      <label>Morada</label>
      <input name="address" value="<?= e((string)$row['address']) ?>">
    </div>

    <div style="grid-column:1 / -1">
      <label>Observações</label>
      <textarea name="notes" rows="4"><?= e((string)$row['notes']) ?></textarea>
    </div>

    <div>
      <label>Ativo</label>
      <select name="is_active">
        <option value="1" <?= ((int)$row['is_active']===1)?'selected':'' ?>>Sim</option>
        <option value="0" <?= ((int)$row['is_active']===0)?'selected':'' ?>>Não</option>
      </select>
    </div>

    <div style="display:flex;gap:10px;align-items:end;justify-content:flex-end">
      <a class="btn" href="suppliers.php" style="background:#1118270f;color:#111827">Voltar</a>
      <button class="btn" type="submit">Guardar</button>
    </div>
  </form>
</div>
<?php render_footer(); ?>
