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

$id = (int)($_GET['id'] ?? 0);
if ($id<=0) { header('Location: leads.php'); exit; }

$st = $pdo->prepare("SELECT * FROM leads WHERE id=?");
$st->execute([$id]);
$lead = $st->fetch();
if (!$lead) { http_response_code(404); exit('Lead não encontrada'); }

$msg=''; $err='';
$stages = ['novo','contactado','test_drive','proposta','financiamento','fechado','perdido'];

if ($_SERVER['REQUEST_METHOD']==='POST') {
  csrf_check();
  try{
    $newStage = (string)($_POST['stage'] ?? '');
    $notes = trim((string)($_POST['notes'] ?? ''));
    if (!in_array($newStage,$stages,true)) throw new RuntimeException('Stage inválido.');

    $from = (string)$lead['stage'];
    if ($from !== $newStage) {
      $uId = (int)($_SESSION['user_id'] ?? 0) ?: null;
      $pdo->prepare("UPDATE leads SET stage=?, updated_at=NOW(), notes=CONCAT(IFNULL(notes,''), '\n', ?) WHERE id=?")
          ->execute([$newStage, $notes, $id]);
      log_lead_stage($pdo, $id, $from, $newStage, $uId, $notes);
      $msg = "Stage atualizado: $from → $newStage";
      $st->execute([$id]);
      $lead = $st->fetch();
    } else {
      $msg = "Sem alteração de stage.";
    }
  } catch(Throwable $e){
    $err = $e->getMessage();
  }
}

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

render_header($config, 'Lead');
?>
<div class="card">
  <h1 style="margin-top:0">Lead #<?= (int)$lead['id'] ?> · <?= e($lead['name']) ?> <span class="badge"><?= e($lead['source']) ?></span></h1>

  <?php if ($msg): ?><div class="card" style="border-left:6px solid #1f7a1f"><?= e($msg) ?></div><?php endif; ?>
  <?php if ($err): ?><div class="card" style="border-left:6px solid #b00020"><?= e($err) ?></div><?php endif; ?>

  <form method="post" class="row" style="flex-wrap:wrap;gap:12px">
    <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
    <div style="min-width:220px;flex:1">
      <label>Stage</label>
      <select name="stage">
        <?php foreach ($stages as $s): ?>
          <option value="<?= e($s) ?>" <?= $lead['stage']===$s?'selected':'' ?>><?= e($s) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div style="min-width:320px;flex:2">
      <label>Notas (opcional)</label>
      <input name="notes" placeholder="ex: cliente pediu proposta, agendou test-drive, etc">
    </div>
    <div style="align-self:end">
      <button>Guardar</button>
    </div>
  </form>

  <h3 style="margin-top:18px">Histórico de etapas</h3>
  <table>
    <thead><tr><th>Quando</th><th>De</th><th>Para</th><th>Notas</th></tr></thead>
    <tbody>
      <?php foreach($events as $e): ?>
        <tr>
          <td><?= e((string)$e['changed_at']) ?></td>
          <td><?= e((string)$e['from_stage']) ?></td>
          <td><span class="badge"><?= e((string)$e['to_stage']) ?></span></td>
          <td><?= e((string)$e['notes']) ?></td>
        </tr>
      <?php endforeach; ?>
      <?php if (count($events)===0): ?>
        <tr><td colspan="4" style="color:#6b7280">Sem eventos ainda (vai começar a registar a partir de agora).</td></tr>
      <?php endif; ?>
    </tbody>
  </table>
</div>
<?php render_footer(); ?>
