<?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','sales']);

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

$row = [
  'customer_code' => '',
  'type' => 'particular',
  'name' => '',
  'nif' => '',
  'address' => '',
  'phone' => '',
  'email' => '',
  'notes' => ''
];

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

$err = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $type = (string)($_POST['type'] ?? 'particular');
  $name = trim((string)($_POST['name'] ?? ''));
  $nif = trim((string)($_POST['nif'] ?? ''));
  $address = trim((string)($_POST['address'] ?? ''));
  $phone = trim((string)($_POST['phone'] ?? ''));
  $email = trim((string)($_POST['email'] ?? ''));
  $notes = trim((string)($_POST['notes'] ?? ''));

  if ($name === '') $err = 'Nome é obrigatório.';
  if (!in_array($type, ['particular','empresa'], true)) $type = 'particular';

  if (!$err) {
    if ($editing) {
      $st = $pdo->prepare("UPDATE customers SET type=?, name=?, nif=?, address=?, phone=?, email=?, notes=? WHERE id=?");
      $st->execute([$type,$name,$nif,$address,$phone,$email,$notes,$id]);
    } else {
      $st = $pdo->prepare("INSERT INTO customers (type,name,nif,address,phone,email,notes) VALUES (?,?,?,?,?,?,?)");
      $st->execute([$type,$name,$nif,$address,$phone,$email,$notes]);
      $id = (int)$pdo->lastInsertId();
      // auto-code
      $code = generate_next_code($pdo, 'customers', 'customer_code', 'C', 5);
      $up = $pdo->prepare("UPDATE customers SET customer_code=? WHERE id=?");
      $up->execute([$code, $id]);
    }
    header('Location: customers.php');
    exit;
  }

  $row = ['customer_code'=>$row['customer_code'] ?? '', 'type'=>$type,'name'=>$name,'nif'=>$nif,'address'=>$address,'phone'=>$phone,'email'=>$email,'notes'=>$notes];
}

render_header($config, $editing ? 'Cliente' : 'Novo cliente');
?>
<div class="card">
  <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap">
    <h1 style="margin:0"><?= $editing ? 'Cliente' : 'Novo cliente' ?></h1>
    <a class="btn" href="customers.php">Voltar</a>
  </div>

  <?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;margin-top:10px">
    <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">

    <div>
      <label>Código</label>
      <input value="<?= e((string)($row['customer_code'] ?? 'auto')) ?>" disabled>
    </div>

    <div>
      <label>Tipo</label>
      <select name="type">
        <option value="particular" <?= (($row['type'] ?? 'particular')==='particular')?'selected':'' ?>>Particular</option>
        <option value="empresa" <?= (($row['type'] ?? '')==='empresa')?'selected':'' ?>>Empresa</option>
      </select>
    </div>

    <div style="grid-column:1 / -1">
      <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 style="grid-column:1 / -1;display:flex;justify-content:flex-end;gap:10px">
      <button class="btn" type="submit">Guardar</button>
    </div>
  </form>
</div>
<?php render_footer(); ?>
