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

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

// suppliers for origin (optional)
$suppliers = [];
try {
  $suppliers = $pdo->query("SELECT id, name FROM suppliers WHERE is_active=1 ORDER BY name ASC")->fetchAll();
} catch (Throwable $e) { $suppliers = []; }

$row = [
  'internal_code' => '',
  'entry_date' => now_date(),
  'source' => 'outro',
  'owner_type' => '',
  'owner_name' => '',
  'brand' => '',
  'model' => '',
  'version' => '',
  'vin' => '',
  'plate' => '',
  'status' => 'em_preparacao',
  'supplier_id' => null,
  'supplier_name' => '',
  'buy_date' => null,
  'buy_price' => 0,
  'sell_price_target' => 0,
  'year' => '',
  'km' => '',
  'fuel' => 'outro',
  'color' => '',
  'ready_date' => null
];

if ($editing) {
  $st = $pdo->prepare("SELECT * FROM vehicles WHERE id=?");
  $st->execute([$id]);
  $dbRow = $st->fetch();
  if (!$dbRow) { header('Location: vehicles.php'); exit; }
  $row = array_merge($row, $dbRow);
} else {
  // auto code
  $row['internal_code'] = generate_next_code($pdo, 'vehicles', 'internal_code', 'BS', 4);
}

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

  $internalCode = (string)($row['internal_code'] ?? '');
  $entryDate = (string)($_POST['entry_date'] ?? now_date());
  $source = (string)($_POST['source'] ?? 'outro');
  $ownerType = trim((string)($_POST['owner_type'] ?? ''));
  $ownerName = trim((string)($_POST['owner_name'] ?? ''));
  $brand = trim((string)($_POST['brand'] ?? ''));
  $model = trim((string)($_POST['model'] ?? ''));
  $version = trim((string)($_POST['version'] ?? ''));
  $vin = trim((string)($_POST['vin'] ?? ''));
  $plate = trim((string)($_POST['plate'] ?? ''));
  $status = (string)($_POST['status'] ?? 'em_preparacao');
  $supplierId = (int)($_POST['supplier_id'] ?? 0);
  $supplierIdVal = $supplierId > 0 ? $supplierId : null;

  $supplierName = trim((string)($_POST['supplier_name'] ?? ''));
  if ($supplierIdVal) {
    $st = $pdo->prepare("SELECT name FROM suppliers WHERE id=?");
    $st->execute([$supplierIdVal]);
    $supplierName = (string)($st->fetchColumn() ?? $supplierName);
  }

  $buyDate = (string)($_POST['buy_date'] ?? '');
  $buyDateVal = preg_match('/^\d{4}-\d{2}-\d{2}$/', $buyDate) ? $buyDate : null;

  $buyPrice = (float)($_POST['buy_price'] ?? 0);
  $sellTarget = (float)($_POST['sell_price_target'] ?? 0);

  $year = ($_POST['year'] ?? '');
  $yearVal = ($year === '' ? null : (int)$year);
  $km = ($_POST['km'] ?? '');
  $kmVal = ($km === '' ? null : (int)$km);

  $fuel = (string)($_POST['fuel'] ?? 'outro');
  $color = trim((string)($_POST['color'] ?? ''));

  $readyDate = (string)($_POST['ready_date'] ?? '');
  $readyVal = preg_match('/^\d{4}-\d{2}-\d{2}$/', $readyDate) ? $readyDate : null;

  if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $entryDate)) $err = 'Data entrada inválida.';
  if (!$err && $brand === '') $err = 'Marca é obrigatória.';
  if (!$err && $model === '') $err = 'Modelo é obrigatório.';

  $allowedSource = ['autorola','retoma','particular','importacao','outro'];
  if (!in_array($source, $allowedSource, true)) $source = 'outro';

  $allowedStatus = ['disponivel','em_preparacao','reservado','vendido','anulado'];
  if (!in_array($status, $allowedStatus, true)) $status = 'em_preparacao';

  $allowedFuel = ['gasolina','diesel','hibrido','phev','eletrico','gnv','outro'];
  if (!in_array($fuel, $allowedFuel, true)) $fuel = 'outro';

  if (!$err) {
    if ($editing) {
      $st = $pdo->prepare("UPDATE vehicles SET entry_date=?, source=?, owner_type=?, owner_name=?, brand=?, model=?, version=?, vin=?, plate=?, status=?, supplier_id=?, supplier_name=?, buy_date=?, buy_price=?, sell_price_target=?, year=?, km=?, fuel=?, color=?, ready_date=? WHERE id=?");
      $st->execute([$entryDate,$source,$ownerType,$ownerName,$brand,$model,$version,$vin,$plate,$status,$supplierIdVal,$supplierName,$buyDateVal,$buyPrice,$sellTarget,$yearVal,$kmVal,$fuel,$color,$readyVal,$id]);
    } else {
      $st = $pdo->prepare("INSERT INTO vehicles (internal_code,entry_date,source,owner_type,owner_name,brand,model,version,vin,plate,status,supplier_id,supplier_name,buy_date,buy_price,sell_price_target,year,km,fuel,color,ready_date) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
      $st->execute([$internalCode,$entryDate,$source,$ownerType,$ownerName,$brand,$model,$version,$vin,$plate,$status,$supplierIdVal,$supplierName,$buyDateVal,$buyPrice,$sellTarget,$yearVal,$kmVal,$fuel,$color,$readyVal]);
      $id = (int)$pdo->lastInsertId();
    }
    header('Location: vehicle_view.php?id='.(int)$id);
    exit;
  }

  $row = array_merge($row, [
    'entry_date'=>$entryDate,'source'=>$source,'owner_type'=>$ownerType,'owner_name'=>$ownerName,'brand'=>$brand,'model'=>$model,'version'=>$version,
    'vin'=>$vin,'plate'=>$plate,'status'=>$status,'supplier_id'=>$supplierIdVal,'supplier_name'=>$supplierName,'buy_date'=>$buyDateVal,
    'buy_price'=>$buyPrice,'sell_price_target'=>$sellTarget,'year'=>$year,'km'=>$km,'fuel'=>$fuel,'color'=>$color,'ready_date'=>$readyVal
  ]);
}

render_header($config, $editing ? 'Viatura' : 'Nova viatura');
?>
<div class="card">
  <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap">
    <h1 style="margin:0"><?= $editing ? 'Viatura' : 'Nova viatura' ?></h1>
    <a class="btn" href="vehicles.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(3,1fr);gap:12px;margin-top:10px">
    <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">

    <div>
      <label>Código</label>
      <input value="<?= e((string)$row['internal_code']) ?>" disabled>
    </div>
    <div>
      <label>Data Entrada *</label>
      <input name="entry_date" value="<?= e((string)$row['entry_date']) ?>">
    </div>
    <div>
      <label>Origem</label>
      <select name="source">
        <?php foreach (['autorola','retoma','particular','importacao','outro'] as $s): ?>
          <option value="<?= e($s) ?>" <?= ((string)$row['source']===$s)?'selected':'' ?>><?= e($s) ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div>
      <label>Proprietário (tipo)</label>
      <input name="owner_type" value="<?= e((string)$row['owner_type']) ?>" placeholder="ex: BlockSpark / TRKW / Consignação">
    </div>
    <div style="grid-column:span 2">
      <label>Proprietário (nome)</label>
      <input name="owner_name" value="<?= e((string)$row['owner_name']) ?>" placeholder="ex: João / Empresa XYZ">
    </div>

    <div>
      <label>Marca *</label>
      <input name="brand" value="<?= e((string)$row['brand']) ?>" required>
    </div>
    <div>
      <label>Modelo *</label>
      <input name="model" value="<?= e((string)$row['model']) ?>" required>
    </div>
    <div>
      <label>Versão</label>
      <input name="version" value="<?= e((string)$row['version']) ?>">
    </div>

    <div>
      <label>Chassis (VIN)</label>
      <input name="vin" value="<?= e((string)$row['vin']) ?>">
    </div>
    <div>
      <label>Matrícula</label>
      <input name="plate" value="<?= e((string)$row['plate']) ?>">
    </div>
    <div>
      <label>Estado</label>
      <select name="status">
        <?php foreach (['disponivel','em_preparacao','reservado','vendido','anulado'] as $st): ?>
          <option value="<?= e($st) ?>" <?= ((string)$row['status']===$st)?'selected':'' ?>><?= e($st) ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div>
      <label>Fornecedor (origem)</label>
      <select name="supplier_id">
        <option value="0">—</option>
        <?php foreach ($suppliers as $s): ?>
          <option value="<?= (int)$s['id'] ?>" <?= ((int)($row['supplier_id'] ?? 0)===(int)$s['id'])?'selected':'' ?>><?= e($s['name']) ?></option>
        <?php endforeach; ?>
      </select>
      <div style="color:#6b7280;font-size:12px;margin-top:6px">Opcional. Guarda também o nome em texto.</div>
    </div>
    <div style="grid-column:span 2">
      <label>Fornecedor (texto)</label>
      <input name="supplier_name" value="<?= e((string)$row['supplier_name']) ?>" placeholder="se não existir na lista">
    </div>

    <div>
      <label>Data compra</label>
      <input name="buy_date" value="<?= e((string)$row['buy_date']) ?>">
    </div>
    <div>
      <label>Preço compra (€)</label>
      <input name="buy_price" value="<?= e((string)$row['buy_price']) ?>">
    </div>
    <div>
      <label>Preço alvo (€)</label>
      <input name="sell_price_target" value="<?= e((string)$row['sell_price_target']) ?>">
    </div>

    <div>
      <label>Ano</label>
      <input name="year" value="<?= e((string)$row['year']) ?>">
    </div>
    <div>
      <label>KM</label>
      <input name="km" value="<?= e((string)$row['km']) ?>">
    </div>
    <div>
      <label>Combustível</label>
      <select name="fuel">
        <?php foreach (['gasolina','diesel','hibrido','phev','eletrico','gnv','outro'] as $f): ?>
          <option value="<?= e($f) ?>" <?= ((string)$row['fuel']===$f)?'selected':'' ?>><?= e($f) ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div>
      <label>Cor</label>
      <input name="color" value="<?= e((string)$row['color']) ?>">
    </div>
    <div>
      <label>Data disponível</label>
      <input name="ready_date" value="<?= e((string)$row['ready_date']) ?>">
    </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(); ?>
