<?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 __DIR__ . '/app/leads_stage.php';

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

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

$customers = $pdo->query("SELECT id, COALESCE(customer_code,'') AS customer_code, name, phone, email FROM customers ORDER BY name ASC")->fetchAll();
$vehicles = $pdo->query("SELECT id, internal_code, brand, model, plate, status FROM vehicles ORDER BY entry_date DESC, id DESC")->fetchAll();

$row = [
  'source' => 'outro',
  'customer_id' => null,
  'name' => '',
  'phone' => '',
  'email' => '',
  'vehicle_id' => null,
  'stage' => 'novo',
  'offer_amount' => '',
  'lost_reason' => '',
  'notes' => ''
];

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

  $ev = $pdo->prepare("SELECT * FROM lead_stage_events WHERE lead_id=? ORDER BY changed_at DESC LIMIT 100");
  $ev->execute([$id]);
  $events = $ev->fetchAll();
}

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

  $source = (string)($_POST['source'] ?? 'outro');
  $customerId = (int)($_POST['customer_id'] ?? 0);
  $name = trim((string)($_POST['name'] ?? ''));
  $phone = trim((string)($_POST['phone'] ?? ''));
  $email = trim((string)($_POST['email'] ?? ''));
  $vehicleId = (int)($_POST['vehicle_id'] ?? 0);
  $stage = (string)($_POST['stage'] ?? 'novo');
  $offer = ($_POST['offer_amount'] ?? '');
  $offerAmount = ($offer === '' ? null : (float)$offer);
  $lostReason = trim((string)($_POST['lost_reason'] ?? ''));
  $notes = trim((string)($_POST['notes'] ?? ''));

  $allowedSource = ['standvirtual','olx','marketplace','google','referencia','outro'];
  if (!in_array($source, $allowedSource, true)) $source = 'outro';

  $allowedStage = ['novo','contactado','test_drive','proposta','financiamento','fechado','perdido'];
  if (!in_array($stage, $allowedStage, true)) $stage = 'novo';

  if ($name === '') $err = 'Nome é obrigatório (podes colocar "Lead sem nome").';

  $custVal = $customerId > 0 ? $customerId : null;
  $vehVal = $vehicleId > 0 ? $vehicleId : null;

  if (!$err) {
    $userId = (int)($_SESSION['user_id'] ?? 0);

    if ($editing) {
      // stage event
      $st = $pdo->prepare("SELECT stage FROM leads WHERE id=?");
      $st->execute([$id]);
      $fromStage = (string)($st->fetchColumn() ?? 'novo');

      $st = $pdo->prepare("UPDATE leads SET source=?, customer_id=?, name=?, phone=?, email=?, vehicle_id=?, stage=?, offer_amount=?, lost_reason=?, notes=?, updated_at=NOW() WHERE id=?");
      $st->execute([$source,$custVal,$name,$phone,$email,$vehVal,$stage,$offerAmount,$lostReason,$notes,$id]);

      if ($fromStage !== $stage) {
        log_lead_stage($pdo, $id, $fromStage, $stage, $userId, null);
      }
    } else {
      $st = $pdo->prepare("INSERT INTO leads (source,customer_id,name,phone,email,vehicle_id,stage,offer_amount,lost_reason,notes,owner_user_id) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
      $st->execute([$source,$custVal,$name,$phone,$email,$vehVal,$stage,$offerAmount,$lostReason,$notes,$userId]);
      $id = (int)$pdo->lastInsertId();
      log_lead_stage($pdo, $id, null, $stage, $userId, 'criado');
    }

    header('Location: leads.php');
    exit;
  }

  $row = [
    'source'=>$source,'customer_id'=>$custVal,'name'=>$name,'phone'=>$phone,'email'=>$email,'vehicle_id'=>$vehVal,'stage'=>$stage,
    'offer_amount'=>$offer,'lost_reason'=>$lostReason,'notes'=>$notes
  ];
}

render_header($config, $editing ? 'Lead' : 'Novo lead');
?>
<div class="card">
  <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap">
    <h1 style="margin:0"><?= $editing ? 'Lead' : 'Novo lead' ?></h1>
    <a class="btn" href="leads.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>Origem</label>
      <select name="source">
        <?php foreach (['standvirtual','olx','marketplace','google','referencia','outro'] as $s): ?>
          <option value="<?= e($s) ?>" <?= ((string)$row['source']===$s)?'selected':'' ?>><?= e($s) ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div>
      <label>Fase</label>
      <select name="stage">
        <?php foreach (['novo','contactado','test_drive','proposta','financiamento','fechado','perdido'] as $stg): ?>
          <option value="<?= e($stg) ?>" <?= ((string)$row['stage']===$stg)?'selected':'' ?>><?= e($stg) ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div style="grid-column:1 / -1">
      <label>Cliente (opcional)</label>
      <select name="customer_id">
        <option value="0">— sem cliente —</option>
        <?php foreach ($customers as $c): ?>
          <?php $lbl = trim(($c['customer_code']?($c['customer_code'].' · '):'') . $c['name']); ?>
          <option value="<?= (int)$c['id'] ?>" <?= ((int)($row['customer_id'] ?? 0) === (int)$c['id'])?'selected':'' ?>><?= e($lbl) ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div style="grid-column:1 / -1">
      <label>Nome *</label>
      <input name="name" value="<?= e((string)$row['name']) ?>" required>
    </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>Viatura (opcional)</label>
      <select name="vehicle_id">
        <option value="0">— sem viatura —</option>
        <?php foreach ($vehicles as $v): ?>
          <?php $vlbl = trim($v['internal_code'].' '.$v['brand'].' '.$v['model'].' ('.$v['plate'].')'); ?>
          <option value="<?= (int)$v['id'] ?>" <?= ((int)($row['vehicle_id'] ?? 0) === (int)$v['id'])?'selected':'' ?>><?= e($vlbl) ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div>
      <label>Oferta (€)</label>
      <input name="offer_amount" value="<?= e((string)$row['offer_amount']) ?>">
    </div>

    <div>
      <label>Motivo perda (se aplicável)</label>
      <input name="lost_reason" value="<?= e((string)$row['lost_reason']) ?>">
    </div>

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

    <div style="grid-column:1 / -1;display:flex;justify-content:flex-end">
      <button class="btn" type="submit">Guardar</button>
    </div>
  </form>
</div>

<?php if ($editing): ?>
  <div class="card" style="margin-top:14px">
    <h3 style="margin-top:0">Histórico de etapas</h3>
    <table>
      <thead><tr><th>Data</th><th>De</th><th>Para</th><th>Por</th><th>Notas</th></tr></thead>
      <tbody>
        <?php foreach ($events as $ev): ?>
          <tr>
            <td><?= e((string)$ev['changed_at']) ?></td>
            <td><?= e((string)$ev['from_stage']) ?></td>
            <td><span class="badge"><?= e((string)$ev['to_stage']) ?></span></td>
            <td><?= e((string)$ev['changed_by']) ?></td>
            <td><?= e((string)$ev['notes']) ?></td>
          </tr>
        <?php endforeach; ?>
        <?php if (count($events)===0): ?>
          <tr><td colspan="5" style="color:#6b7280">Sem eventos ainda.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
<?php endif; ?>

<?php render_footer(); ?>
