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

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

$vehSt = $pdo->prepare("SELECT * FROM vehicles WHERE id=?");
$vehSt->execute([$vehicleId]);
$v = $vehSt->fetch();
if (!$v) { http_response_code(404); exit('Viatura não encontrada'); }

// customers list
$customers = $pdo->query("SELECT id,name,nif FROM customers ORDER BY created_at DESC LIMIT 500")->fetchAll();
// leads for vehicle
$leadSt = $pdo->prepare("SELECT * FROM leads WHERE vehicle_id=? ORDER BY created_at DESC");
$leadSt->execute([$vehicleId]);
$leads = $leadSt->fetchAll();

$defaultChannel = 'sem_canal';
if (count($leads)>0) $defaultChannel = (string)$leads[0]['source'];

$msg=''; $err='';

if ($_SERVER['REQUEST_METHOD']==='POST') {
  csrf_check();
  try{
    $customerId = (int)($_POST['customer_id'] ?? 0);
    $saleDate = (string)($_POST['sale_date'] ?? date('Y-m-d'));
    $salePrice = (float)($_POST['sale_price'] ?? 0);
    $payment = (string)($_POST['payment_method'] ?? 'transferencia');
    $finalChannel = trim((string)($_POST['final_channel'] ?? $defaultChannel));
    $leadId = (int)($_POST['lead_id'] ?? 0) ?: null;

    if ($customerId <= 0) throw new RuntimeException('Seleciona um cliente.');
    if ($salePrice <= 0) throw new RuntimeException('Preço de venda inválido.');

    // days_to_sell uses entry_date
    $daysToSell = null;
    if (!empty($v['entry_date'])) {
      $daysToSell = (int)((new DateTime($saleDate))->diff(new DateTime((string)$v['entry_date']))->format('%r%a'));
      if ($daysToSell < 0) $daysToSell = null;
    }

    $st = $pdo->prepare("INSERT INTO sales (vehicle_id,customer_id,lead_id,sale_date,days_to_sell,sale_price,payment_method,final_channel,finance_company,finance_commission,insurance_company,insurance_commission,invoice_no,notes,created_by)
      VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
    $st->execute([
      $vehicleId,$customerId,$leadId,$saleDate,$daysToSell,$salePrice,$payment,
      ($finalChannel!==''?$finalChannel:'sem_canal'),
      trim((string)($_POST['finance_company'] ?? '')),
      (float)($_POST['finance_commission'] ?? 0),
      trim((string)($_POST['insurance_company'] ?? '')),
      (float)($_POST['insurance_commission'] ?? 0),
      trim((string)($_POST['invoice_no'] ?? '')) ?: null,
      trim((string)($_POST['notes'] ?? '')),
      (int)($_SESSION['user_id'] ?? 0) ?: null
    ]);

    // mark vehicle as sold
    $pdo->prepare("UPDATE vehicles SET status='vendido' WHERE id=?")->execute([$vehicleId]);

    if ($leadId !== null) {
      // lock lead as fechado
      $cur = $pdo->prepare("SELECT stage FROM leads WHERE id=?");
      $cur->execute([$leadId]);
      $curRow = $cur->fetch();
      $fromStage = $curRow ? (string)$curRow['stage'] : null;
      $pdo->prepare("UPDATE leads SET stage='fechado', updated_at=NOW() WHERE id=?")->execute([$leadId]);
      log_lead_stage($pdo, (int)$leadId, $fromStage, 'fechado', (int)($_SESSION['user_id'] ?? 0) ?: null, 'Fecho de venda');
    }

    $msg='Venda registada. Canal final bloqueado: '.($finalChannel!==''?$finalChannel:'sem_canal');
  } catch(Throwable $e){
    $err=$e->getMessage();
  }
}

render_header($config, 'Fechar venda');
?>
<div class="card">
  <h1 style="margin-top:0">Fechar venda · <?= e($v['internal_code']) ?> <?= e(trim($v['brand'].' '.$v['model'])) ?></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"><p class="error"><?= e($err) ?></p></div><?php endif; ?>

  <form method="post" class="row" style="flex-wrap:wrap">
    <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">

    <div style="flex:2;min-width:240px">
      <label>Cliente</label>
      <select name="customer_id" required>
        <option value="">— Selecionar —</option>
        <?php foreach ($customers as $c): ?>
          <option value="<?= (int)$c['id'] ?>"><?= e($c['name']) ?><?= $c['nif']? ' (NIF '.e($c['nif']).')':'' ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div style="flex:1;min-width:140px">
      <label>Data venda</label>
      <input name="sale_date" value="<?= e(date('Y-m-d')) ?>">
    </div>

    <div style="flex:1;min-width:140px">
      <label>Preço venda</label>
      <input name="sale_price" required>
    </div>

    <div style="flex:1;min-width:160px">
      <label>Método</label>
      <select name="payment_method">
        <option value="transferencia">transferencia</option>
        <option value="pronto">pronto</option>
        <option value="financiamento">financiamento</option>
        <option value="misto">misto</option>
      </select>
    </div>

    <div style="flex:1;min-width:180px">
      <label>Canal final (bloqueado)</label>
      <input name="final_channel" value="<?= e($defaultChannel) ?>" placeholder="standvirtual / olx / marketplace / ...">
    </div>

    <div style="flex:1;min-width:200px">
      <label>Lead associada (opcional)</label>
      <select name="lead_id">
        <option value="">— nenhuma —</option>
        <?php foreach ($leads as $l): ?>
          <option value="<?= (int)$l['id'] ?>"><?= e(substr((string)$l['created_at'],0,10)) ?> · <?= e($l['source']) ?> · <?= e($l['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div style="flex:1;min-width:180px">
      <label>Financeira</label>
      <input name="finance_company">
    </div>
    <div style="flex:1;min-width:140px">
      <label>Comissão financiamento</label>
      <input name="finance_commission" value="0">
    </div>

    <div style="flex:1;min-width:180px">
      <label>Seguradora</label>
      <input name="insurance_company">
    </div>
    <div style="flex:1;min-width:140px">
      <label>Comissão seguro</label>
      <input name="insurance_commission" value="0">
    </div>

    <div style="flex:1;min-width:160px">
      <label>Nº fatura</label>
      <input name="invoice_no">
    </div>

    <div style="flex:2;min-width:260px">
      <label>Notas</label>
      <input name="notes">
    </div>

    <div style="align-self:end">
      <button>Registar venda</button>
    </div>
  </form>

  <p style="color:#6b7280;margin-top:10px">Depois de registada, a viatura fica marcada como <b>vendido</b> e o canal final fica guardado em <b>sales.final_channel</b>.</p>
</div>
<?php render_footer(); ?>
