<?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;

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

$row = [
  'vehicle_id' => 0,
  'customer_id' => 0,
  'sale_date' => now_date(),
  'sale_price' => 0,
  'payment_method' => 'transferencia',
  'final_channel' => 'sem_canal',
  'finance_company' => '',
  'finance_commission' => 0,
  'insurance_company' => '',
  'insurance_commission' => 0,
  'invoice_no' => '',
  'notes' => ''
];

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

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

  $vehicleId = (int)($_POST['vehicle_id'] ?? 0);
  $customerId = (int)($_POST['customer_id'] ?? 0);
  $saleDate = (string)($_POST['sale_date'] ?? now_date());
  $salePrice = (float)($_POST['sale_price'] ?? 0);
  $paymentMethod = (string)($_POST['payment_method'] ?? 'transferencia');

  $finalChannel = trim((string)($_POST['final_channel'] ?? 'sem_canal'));
  $financeCompany = trim((string)($_POST['finance_company'] ?? ''));
  $financeCommission = (float)($_POST['finance_commission'] ?? 0);
  $insuranceCompany = trim((string)($_POST['insurance_company'] ?? ''));
  $insuranceCommission = (float)($_POST['insurance_commission'] ?? 0);
  $invoiceNo = trim((string)($_POST['invoice_no'] ?? ''));
  $notes = trim((string)($_POST['notes'] ?? ''));

  if ($vehicleId <= 0) $err = 'Seleciona uma viatura.';
  if (!$err && $customerId <= 0) $err = 'Seleciona um cliente.';
  if (!$err && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $saleDate)) $err = 'Data inválida.';
  if (!$err && $salePrice <= 0) $err = 'Valor de venda inválido.';

  $allowedPM = ['pronto','transferencia','financiamento','misto'];
  if (!in_array($paymentMethod, $allowedPM, true)) $paymentMethod = 'transferencia';

  if ($finalChannel === '') $finalChannel = 'sem_canal';

  // Lock final_channel once set (editing)
  if ($editing) {
    $st = $pdo->prepare("SELECT final_channel, vehicle_id FROM sales WHERE id=?");
    $st->execute([$id]);
    $curr = $st->fetch();
    if ($curr) {
      $locked = (string)$curr['final_channel'];
      if ($locked !== '' && $locked !== 'sem_canal') {
        $finalChannel = $locked;
      }
      // prevent changing vehicle on edit (safer)
      $vehicleId = (int)$curr['vehicle_id'];
    }
  }

  if (!$err) {
    // compute days_to_sell from vehicle entry_date
    $st = $pdo->prepare("SELECT entry_date FROM vehicles WHERE id=?");
    $st->execute([$vehicleId]);
    $entry = (string)($st->fetchColumn() ?? '');
    $daysToSell = $entry ? days_between($entry, $saleDate) : null;

    if ($editing) {
      $st = $pdo->prepare("UPDATE sales SET customer_id=?, sale_date=?, days_to_sell=?, sale_price=?, payment_method=?, final_channel=?, finance_company=?, finance_commission=?, insurance_company=?, insurance_commission=?, invoice_no=?, notes=? WHERE id=?");
      $st->execute([$customerId,$saleDate,$daysToSell,$salePrice,$paymentMethod,$finalChannel,$financeCompany,$financeCommission,$insuranceCompany,$insuranceCommission,$invoiceNo,$notes,$id]);
    } else {
      $createdBy = (int)($_SESSION['user_id'] ?? 0);
      $st = $pdo->prepare("INSERT INTO sales (vehicle_id,customer_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,$saleDate,$daysToSell,$salePrice,$paymentMethod,$finalChannel,$financeCompany,$financeCommission,$insuranceCompany,$insuranceCommission,$invoiceNo,$notes,$createdBy]);
      // mark vehicle as sold
      $up = $pdo->prepare("UPDATE vehicles SET status='vendido' WHERE id=?");
      $up->execute([$vehicleId]);
    }

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

  $row = array_merge($row, [
    'vehicle_id'=>$vehicleId,'customer_id'=>$customerId,'sale_date'=>$saleDate,'sale_price'=>$salePrice,'payment_method'=>$paymentMethod,
    'final_channel'=>$finalChannel,'finance_company'=>$financeCompany,'finance_commission'=>$financeCommission,'insurance_company'=>$insuranceCompany,
    'insurance_commission'=>$insuranceCommission,'invoice_no'=>$invoiceNo,'notes'=>$notes
  ]);
}

render_header($config, $editing ? 'Venda' : 'Nova venda');
?>
<div class="card">
  <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap">
    <h1 style="margin:0"><?= $editing ? 'Venda' : 'Nova venda' ?></h1>
    <a class="btn" href="sales.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 style="grid-column:1 / -1">
      <label>Viatura *</label>
      <select name="vehicle_id" <?= $editing ? 'disabled' : '' ?>>
        <option value="0">— selecionar —</option>
        <?php foreach ($vehicles as $v): ?>
          <?php $label = trim($v['internal_code'].' '.$v['brand'].' '.$v['model'].' ('.$v['plate'].')'); ?>
          <option value="<?= (int)$v['id'] ?>" <?= ((int)$row['vehicle_id']===(int)$v['id'])?'selected':'' ?>>
            <?= e($label) ?>
          </option>
        <?php endforeach; ?>
      </select>
      <?php if ($editing): ?><input type="hidden" name="vehicle_id" value="<?= (int)$row['vehicle_id'] ?>"><?php endif; ?>
    </div>

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

    <div>
      <label>Data venda *</label>
      <input name="sale_date" value="<?= e((string)$row['sale_date']) ?>">
    </div>

    <div>
      <label>Valor venda (€) *</label>
      <input name="sale_price" value="<?= e((string)$row['sale_price']) ?>">
    </div>

    <div>
      <label>Método pagamento</label>
      <select name="payment_method">
        <?php foreach (['pronto'=>'Pronto','transferencia'=>'Transferência','financiamento'=>'Financiamento','misto'=>'Misto'] as $k=>$lbl): ?>
          <option value="<?= e($k) ?>" <?= ((string)$row['payment_method']===$k)?'selected':'' ?>><?= e($lbl) ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div>
      <label>Canal final (bloqueia no fecho)</label>
      <?php $locked = $editing && ((string)$row['final_channel'] !== '' && (string)$row['final_channel'] !== 'sem_canal'); ?>
      <input name="final_channel" value="<?= e((string)$row['final_channel']) ?>" <?= $locked ? 'disabled' : '' ?>>
      <?php if ($locked): ?><input type="hidden" name="final_channel" value="<?= e((string)$row['final_channel']) ?>"><?php endif; ?>
      <div style="color:#6b7280;font-size:12px;margin-top:6px">Ex: StandVirtual, OLX, Marketplace, Direto.</div>
    </div>

    <div>
      <label>Financeira</label>
      <input name="finance_company" value="<?= e((string)$row['finance_company']) ?>">
    </div>
    <div>
      <label>Comissão financiamento (€)</label>
      <input name="finance_commission" value="<?= e((string)$row['finance_commission']) ?>">
    </div>

    <div>
      <label>Seguradora</label>
      <input name="insurance_company" value="<?= e((string)$row['insurance_company']) ?>">
    </div>
    <div>
      <label>Comissão seguro (€)</label>
      <input name="insurance_commission" value="<?= e((string)$row['insurance_commission']) ?>">
    </div>

    <div>
      <label>Nº Fatura</label>
      <input name="invoice_no" value="<?= e((string)$row['invoice_no']) ?>">
    </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 render_footer(); ?>
