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

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

$tab = $_GET['tab'] ?? 'dados';
$id  = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$new = isset($_GET['new']) ? 1 : 0;

function get_vehicle(PDO $pdo, int $id): ?array {
  $st = $pdo->prepare("SELECT * FROM vehicles WHERE id=?");
  $st->execute([$id]);
  $v = $st->fetch();
  return $v ?: null;
}

if ($new && $_SERVER['REQUEST_METHOD'] !== 'POST') {
  // create placeholder vehicle
  $code = 'BS' . date('ymdHis');
  $st = $pdo->prepare("INSERT INTO vehicles (internal_code,brand,model,entry_date,buy_price,sell_price_target,status) VALUES (?,?,?,?,?,?,?)");
  $st->execute([$code,'','',date('Y-m-d'),0,0,'em_preparacao']);
  $id = (int)$pdo->lastInsertId();
  header("Location: vehicle_view.php?id={$id}&tab=dados");
  exit;
}

if (!$id) { header('Location: vehicles.php'); exit; }

$vehicle = get_vehicle($pdo, $id);
if (!$vehicle) { http_response_code(404); exit('Not found'); }

$maxBytes = (int)$config['app']['max_upload_mb'] * 1024 * 1024;
$msg = '';
$err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $action = $_POST['action'] ?? '';

  try {
    if ($action === 'save_vehicle') {
      $fields = ['internal_code','brand','model','version','plate','vin','fuel','year','km','color','source','supplier_name','buy_date','entry_date','ready_date','buy_price','sell_price_target','status','notes'];
      $data = [];
      foreach ($fields as $f) $data[$f] = trim((string)($_POST[$f] ?? ''));
      $st = $pdo->prepare("UPDATE vehicles SET internal_code=?,brand=?,model=?,version=?,plate=?,vin=?,fuel=?,year=?,km=?,color=?,source=?,supplier_name=?,buy_date=?,entry_date=?,ready_date=?,buy_price=?,sell_price_target=?,status=?,notes=? WHERE id=?");
      $st->execute([
        $data['internal_code'],$data['brand'],$data['model'],$data['version'],$data['plate'],$data['vin'],$data['fuel'],
        ($data['year']!==''?(int)$data['year']:null),
        ($data['km']!==''?(int)$data['km']:null),
        $data['color'],$data['source'],$data['supplier_name'],
        ($data['buy_date']!==''?$data['buy_date']:null),
        ($data['entry_date']!==''?$data['entry_date']:date('Y-m-d')),
        ($data['ready_date']!==''?$data['ready_date']:null),
        (float)$data['buy_price'],(float)$data['sell_price_target'],
        $data['status'],$data['notes'],
        $id
      ]);
      $msg = 'Viatura guardada.';
      $vehicle = get_vehicle($pdo, $id);
      $tab='dados';
    }

    if ($action === 'add_cost') {
      $st = $pdo->prepare("INSERT INTO vehicle_costs (vehicle_id,cost_type,supplier,invoice_no,invoice_date,amount,vat_amount,notes,created_by) VALUES (?,?,?,?,?,?,?,?,?)");
      $st->execute([
        $id,
        $_POST['cost_type'] ?? 'outros',
        trim((string)($_POST['supplier'] ?? '')),
        trim((string)($_POST['invoice_no'] ?? '')),
        ($_POST['invoice_date'] ?? '') ?: null,
        (float)($_POST['amount'] ?? 0),
        (($_POST['vat_amount'] ?? '') !== '' ? (float)$_POST['vat_amount'] : null),
        trim((string)($_POST['notes'] ?? '')),
        (int)($_SESSION['user_id'] ?? 0) ?: null
      ]);
      $msg = 'Custo registado.';
      $tab='custos';
    }

    if ($action === 'upload_doc' && isset($_FILES['doc'])) {
      $meta = safe_store_upload($_FILES['doc'], vehicle_docs_dir($config,$id), allowed_doc_mimes(), $maxBytes);

      $st = $pdo->prepare("INSERT INTO documents (vehicle_id,doc_type,title,original_filename,stored_filename,mime_type,file_size,sha256,doc_date,invoice_no,supplier,created_by) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)");
      $st->execute([
        $id,
        $_POST['doc_type'] ?? 'outro',
        trim((string)($_POST['title'] ?? $meta['original_filename'])),
        $meta['original_filename'],
        $meta['stored_filename'],
        $meta['mime_type'],
        $meta['file_size'],
        $meta['sha256'],
        ($_POST['doc_date'] ?? '') ?: null,
        trim((string)($_POST['invoice_no'] ?? '')) ?: null,
        trim((string)($_POST['supplier'] ?? '')) ?: null,
        (int)($_SESSION['user_id'] ?? 0) ?: null
      ]);
      $msg = 'Documento carregado.';
      $tab='docs';
    }

    if ($action === 'upload_photo' && isset($_FILES['photo'])) {
      // store upload to temp then optimize into storage
      $tmp = $_FILES['photo']['tmp_name'];
      $finfo = new finfo(FILEINFO_MIME_TYPE);
      $mime = $finfo->file($tmp) ?: '';
      if (!in_array($mime, allowed_photo_mimes(), true)) throw new RuntimeException("Tipo de foto inválido.");

      ensure_dir(vehicle_photos_dir($config,$id));

      $ext = strtolower(pathinfo((string)$_FILES['photo']['name'], PATHINFO_EXTENSION));
      $stored = bin2hex(random_bytes(16)) . ($ext ? ".{$ext}" : ".jpg");
      $dest = rtrim(vehicle_photos_dir($config,$id), '/') . '/' . $stored;

      // optimize
      $opt = optimize_image($tmp, $dest, 1600);
      $outMime = $opt['mime'];

      $sha = hash_file('sha256', $dest);
      $size = filesize($dest);

      $st = $pdo->prepare("INSERT INTO vehicle_photos (vehicle_id,title,original_filename,stored_filename,mime_type,file_size,sha256,is_primary,sort_order,created_by) VALUES (?,?,?,?,?,?,?,?,?,?)");
      $st->execute([
        $id,
        trim((string)($_POST['title'] ?? '')),
        basename((string)$_FILES['photo']['name']),
        $stored,
        $outMime,
        (int)$size,
        $sha,
        0,
        0,
        (int)($_SESSION['user_id'] ?? 0) ?: null
      ]);
      $msg = 'Foto carregada e otimizada.';
      $tab='fotos';
    }

  } catch (Throwable $e) {
    $err = $e->getMessage();
  }
}

$costs = $pdo->prepare("SELECT * FROM vehicle_costs WHERE vehicle_id=? ORDER BY invoice_date DESC, id DESC");
$costs->execute([$id]);
$costRows = $costs->fetchAll();

$docs = $pdo->prepare("SELECT * FROM documents WHERE vehicle_id=? ORDER BY created_at DESC");
$docs->execute([$id]);
$docRows = $docs->fetchAll();

$photos = $pdo->prepare("SELECT * FROM vehicle_photos WHERE vehicle_id=? ORDER BY is_primary DESC, sort_order ASC, id DESC");
$photos->execute([$id]);
$photoRows = $photos->fetchAll();

$totalCosts = 0.0;
foreach ($costRows as $c) $totalCosts += (float)$c['amount'];

?>

  </div>

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

  <div class="tabs">
    <a href="sale_close.php?vehicle_id=<?= (int)$id ?>" style="margin-left:auto">Fechar venda</a>
    <a class="<?= $tab==='dados'?'active':'' ?>" href="vehicle_view.php?id=<?= (int)$id ?>&tab=dados">Dados</a>
    <a class="<?= $tab==='custos'?'active':'' ?>" href="vehicle_view.php?id=<?= (int)$id ?>&tab=custos">Custos</a>
    <a class="<?= $tab==='docs'?'active':'' ?>" href="vehicle_view.php?id=<?= (int)$id ?>&tab=docs">Documentos</a>
    <a class="<?= $tab==='fotos'?'active':'' ?>" href="vehicle_view.php?id=<?= (int)$id ?>&tab=fotos">Fotos</a>
  </div>

  <?php if ($tab === 'dados'): ?>
    <form method="post" class="card">
      <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
      <input type="hidden" name="action" value="save_vehicle">
      <div class="row">
        <div style="flex:1"><label>Código interno</label><input name="internal_code" value="<?= e($vehicle['internal_code']) ?>"></div>
        <div style="flex:1"><label>Estado</label>
          <select name="status">
            <?php foreach (['disponivel','em_preparacao','reservado','vendido','anulado'] as $s): ?>
              <option value="<?= e($s) ?>" <?= $vehicle['status']===$s?'selected':'' ?>><?= e($s) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>
      <div class="row">
        <div style="flex:1"><label>Marca</label><input name="brand" value="<?= e($vehicle['brand']) ?>"></div>
        <div style="flex:1"><label>Modelo</label><input name="model" value="<?= e($vehicle['model']) ?>"></div>
        <div style="flex:1"><label>Versão</label><input name="version" value="<?= e($vehicle['version']) ?>"></div>
      </div>
      <div class="row">
        <div style="flex:1"><label>Matrícula</label><input name="plate" value="<?= e($vehicle['plate']) ?>"></div>
        <div style="flex:1"><label>VIN</label><input name="vin" value="<?= e($vehicle['vin']) ?>"></div>
        <div style="flex:1"><label>Combustível</label>
          <select name="fuel">
            <?php foreach (['gasolina','diesel','hibrido','phev','eletrico','gnv','outro'] as $f): ?>
              <option value="<?= e($f) ?>" <?= $vehicle['fuel']===$f?'selected':'' ?>><?= e($f) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>
      <div class="row">
        <div style="flex:1"><label>Ano</label><input name="year" value="<?= e((string)$vehicle['year']) ?>"></div>
        <div style="flex:1"><label>KM</label><input name="km" value="<?= e((string)$vehicle['km']) ?>"></div>
        <div style="flex:1"><label>Cor</label><input name="color" value="<?= e((string)$vehicle['color']) ?>"></div>
      </div>
      <div class="row">
        <div style="flex:1"><label>Origem</label>
          <select name="source">
            <?php foreach (['autorola','retoma','particular','importacao','outro'] as $s): ?>
              <option value="<?= e($s) ?>" <?= $vehicle['source']===$s?'selected':'' ?>><?= e($s) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div style="flex:2"><label>Fornecedor</label><input name="supplier_name" value="<?= e((string)$vehicle['supplier_name']) ?>"></div>
      </div>
      <div class="row">
        <div style="flex:1"><label>Data compra</label><input name="buy_date" value="<?= e((string)$vehicle['buy_date']) ?>"></div>
        <div style="flex:1"><label>Data entrada</label><input name="entry_date" value="<?= e((string)$vehicle['entry_date']) ?>"></div>
        <div style="flex:1"><label>Data disponível</label><input name="ready_date" value="<?= e((string)($vehicle['ready_date'] ?? '')) ?>" placeholder="YYYY-MM-DD"></div>
      </div>
      <div class="row">
        <div style="flex:1"><label>Preço compra</label><input name="buy_price" value="<?= e((string)$vehicle['buy_price']) ?>"></div>
        <div style="flex:1"><label>Preço venda alvo</label><input name="sell_price_target" value="<?= e((string)$vehicle['sell_price_target']) ?>"></div>
        <div style="flex:1"><label>Total custos (registos)</label><input disabled value="<?= e(money($totalCosts)) ?>"></div>
      </div>
      <label>Notas</label>
      <textarea name="notes" rows="4"><?= e((string)$vehicle['notes']) ?></textarea>
      <button type="submit">Guardar</button>
    </form>
  <?php endif; ?>

  <?php if ($tab === 'custos'): ?>
    <div class="card">
      <h3>Adicionar custo</h3>
      <form method="post" class="row" style="flex-wrap:wrap">
        <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="action" value="add_cost">
        <div style="flex:1;min-width:160px">
          <label>Tipo</label>
          <select name="cost_type">
            <?php foreach (['compra','transporte','recondicionamento','pecas','pintura','limpeza','garantia','publicidade','outsourcing','outros'] as $t): ?>
              <option value="<?= e($t) ?>"><?= e($t) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div style="flex:1;min-width:160px"><label>Fornecedor</label><input name="supplier"></div>
        <div style="flex:1;min-width:140px"><label>Nº fatura</label><input name="invoice_no"></div>
        <div style="flex:1;min-width:140px"><label>Data</label><input name="invoice_date" placeholder="YYYY-MM-DD"></div>
        <div style="flex:1;min-width:120px"><label>Valor</label><input name="amount"></div>
        <div style="flex:1;min-width:120px"><label>IVA</label><input name="vat_amount"></div>
        <div style="flex:2;min-width:200px"><label>Notas</label><input name="notes"></div>
        <div style="align-self:end"><button>Adicionar</button></div>
      </form>
    </div>

    <div class="card" style="margin-top:12px">
      <h3>Custos registados · Total: <?= e(money($totalCosts)) ?></h3>
      <table>
        <thead><tr><th>Tipo</th><th>Fornecedor</th><th>Fatura</th><th>Data</th><th>Valor</th></tr></thead>
        <tbody>
          <?php foreach ($costRows as $c): ?>
          <tr>
            <td><?= e($c['cost_type']) ?></td>
            <td><?= e((string)$c['supplier']) ?></td>
            <td><?= e((string)$c['invoice_no']) ?></td>
            <td><?= e((string)$c['invoice_date']) ?></td>
            <td><?= e(money($c['amount'])) ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  <?php endif; ?>

  <?php if ($tab === 'docs'): ?>
    <div class="card">
      <h3>Carregar documento</h3>
      <form method="post" enctype="multipart/form-data" class="row" style="flex-wrap:wrap">
        <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="action" value="upload_doc">
        <div style="flex:1;min-width:180px">
          <label>Tipo</label>
          <select name="doc_type">
            <?php foreach (['fatura_compra','fatura_transporte','fatura_recondicionamento','fatura_pecas','fatura_pintura','fatura_limpeza','fatura_venda','garantia','inspecao','financiamento','seguro','comprovativo_pagamento','livrete','manual','outro'] as $t): ?>
              <option value="<?= e($t) ?>"><?= e($t) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div style="flex:2;min-width:220px"><label>Título</label><input name="title" placeholder="Ex: Fatura pintura"></div>
        <div style="flex:1;min-width:140px"><label>Data doc</label><input name="doc_date" placeholder="YYYY-MM-DD"></div>
        <div style="flex:1;min-width:140px"><label>Nº fatura</label><input name="invoice_no"></div>
        <div style="flex:1;min-width:180px"><label>Fornecedor</label><input name="supplier"></div>
        <div style="flex:2;min-width:260px"><label>Ficheiro (PDF/JPG/PNG)</label><input type="file" name="doc" required></div>
        <div style="align-self:end"><button>Upload</button></div>
      </form>
    </div>

    <div class="card" style="margin-top:12px">
      <h3>Arquivo documental</h3>
      <table>
        <thead><tr><th>Tipo</th><th>Título</th><th>Fornecedor</th><th>Fatura</th><th>Data</th><th>Download</th></tr></thead>
        <tbody>
          <?php foreach ($docRows as $d): ?>
          <tr>
            <td><?= e($d['doc_type']) ?></td>
            <td><?= e($d['title']) ?></td>
            <td><?= e((string)$d['supplier']) ?></td>
            <td><?= e((string)$d['invoice_no']) ?></td>
            <td><?= e((string)$d['doc_date']) ?></td>
            <td><a href="download.php?doc_id=<?= (int)$d['id'] ?>">Download</a></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  <?php endif; ?>

  <?php if ($tab === 'fotos'): ?>
    <div class="card">
      <h3>Carregar foto (otimiza automaticamente)</h3>
      <form method="post" enctype="multipart/form-data" class="row" style="flex-wrap:wrap">
        <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="action" value="upload_photo">
        <div style="flex:2;min-width:260px"><label>Foto (JPG/PNG)</label><input type="file" name="photo" required></div>
        <div style="flex:2;min-width:220px"><label>Título</label><input name="title" placeholder="Ex: Frente"></div>
        <div style="align-self:end"><button>Upload</button></div>
      </form>
    </div>

    <div class="card" style="margin-top:12px">
      <h3>Galeria</h3>
      <table>
        <thead><tr><th>Ficheiro</th><th>Título</th><th>Mime</th><th>Tamanho</th></tr></thead>
        <tbody>
          <?php foreach ($photoRows as $p): ?>
          <tr>
            <td><?= e($p['stored_filename']) ?></td>
            <td><?= e((string)$p['title']) ?></td>
            <td><?= e($p['mime_type']) ?></td>
            <td><?= e((string)$p['file_size']) ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
      <p style="color:#666;margin-top:8px">As fotos ficam guardadas fora do public_html em /blockspark_storage/vehicles/{id}/photos.</p>
    </div>
  <?php endif; ?>

<?php render_footer(); ?>
