<?php
require_once __DIR__ . '/_db.php';

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

$customer = ['name'=>'','email'=>'','company'=>'','phone'=>'','notes'=>'','active'=>1];
if ($editing) {
    $row = $pdo->prepare("SELECT * FROM customers WHERE id = ?");
    $row->execute([$id]);
    $row = $row->fetch();
    if (!$row) { header('Location: index.php'); exit; }
    $customer = $row;
}

$msg = $error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $name    = trim($_POST['name']    ?? '');
    $email   = trim($_POST['email']   ?? '');
    $company = trim($_POST['company'] ?? '');
    $phone   = trim($_POST['phone']   ?? '');
    $notes   = trim($_POST['notes']   ?? '');
    $active  = isset($_POST['active']) ? 1 : 0;

    if (!$name || !$email) {
        $error = 'Nome e e-mail são obrigatórios.';
    } else {
        if ($editing) {
            // Verifica e-mail duplicado em outro cadastro
            $dup = $pdo->prepare("SELECT id FROM customers WHERE email = ? AND id != ?");
            $dup->execute([$email, $id]);
            if ($dup->fetch()) {
                $error = 'Este e-mail já está cadastrado em outro cliente.';
            } else {
                $pdo->prepare("UPDATE customers SET name=?,email=?,company=?,phone=?,notes=?,active=? WHERE id=?")
                    ->execute([$name, $email, $company, $phone, $notes, $active, $id]);
                header('Location: customer_view.php?id=' . $id . '&msg=saved');
                exit;
            }
        } else {
            $dup = $pdo->prepare("SELECT id FROM customers WHERE email = ?");
            $dup->execute([$email]);
            if ($dup->fetch()) {
                $error = 'Este e-mail já está cadastrado.';
            } else {
                $pdo->prepare("INSERT INTO customers (name,email,company,phone,notes,active) VALUES (?,?,?,?,?,?)")
                    ->execute([$name, $email, $company, $phone, $notes, 1]);
                $new_id = (int)$pdo->lastInsertId();
                header('Location: customer_view.php?id=' . $new_id . '&msg=created');
                exit;
            }
        }
        if (!$error) {
            $customer = compact('name','email','company','phone','notes','active');
        }
    }
}

$page_title  = $editing ? 'Editar Cliente' : 'Novo Cliente';
$current_nav = 'customers';
require __DIR__ . '/_layout.php';
?>

<div style="margin-bottom:1rem">
  <a href="<?= $editing ? 'customer_view.php?id='.$id : 'index.php' ?>">← Voltar</a>
</div>

<h1><?= $editing ? 'Editar Cliente' : 'Novo Cliente' ?></h1>

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

<div class="card">
<form method="post">
  <?= csrf_field() ?>
  <div class="form-row">
    <div>
      <label>Nome completo *</label>
      <input type="text" name="name" value="<?= h($customer['name']) ?>" required autofocus>
    </div>
    <div>
      <label>E-mail *</label>
      <input type="email" name="email" value="<?= h($customer['email']) ?>" required>
    </div>
  </div>
  <div class="form-row">
    <div>
      <label>Empresa</label>
      <input type="text" name="company" value="<?= h($customer['company'] ?? '') ?>">
    </div>
    <div>
      <label>Telefone / WhatsApp</label>
      <input type="tel" name="phone" value="<?= h($customer['phone'] ?? '') ?>" placeholder="(99) 99999-9999">
    </div>
  </div>
  <label>Observações</label>
  <textarea name="notes" rows="3"><?= h($customer['notes'] ?? '') ?></textarea>

  <?php if ($editing): ?>
  <label style="margin-top:1rem;display:flex;align-items:center;gap:.5rem;cursor:pointer">
    <input type="checkbox" name="active" <?= $customer['active'] ? 'checked' : '' ?> style="width:auto">
    Cliente ativo
  </label>
  <?php endif; ?>

  <div class="form-actions">
    <button type="submit" class="btn btn-blue"><?= $editing ? 'Salvar Alterações' : 'Cadastrar Cliente' ?></button>
    <a href="<?= $editing ? 'customer_view.php?id='.$id : 'index.php' ?>" class="btn btn-gray">Cancelar</a>
  </div>
</form>
</div>

</div></body></html>
