<?php
include 'includes/db.php';

$id = intval($_GET['id']);
$marca = $_POST['marca'];
$model = $_POST['model'];
$an = $_POST['an'];
$nr = $_POST['nr_inmatriculare'];
$pret_euro = $_POST['pret'];
$status = $_POST['status'];
$detalii = $_POST['detalii'];
$vin = $_POST['vin'];

$pret = floatval($pret_euro) * 5;

$stmt = $conn->prepare("UPDATE cars SET marca=?, model=?, an=?, nr_inmatriculare=?, pret=?, status=?, detalii=?, vin=? WHERE id=?");
$stmt->bind_param("ssisdsssi", $marca, $model, $an, $nr, $pret, $status, $detalii, $vin, $id);
$stmt->execute();

// documente noi
if (!empty($_FILES['documente']['name'][0])) {
  foreach ($_FILES['documente']['name'] as $i => $nume) {
    $tmp = $_FILES['documente']['tmp_name'][$i];
    $dest = "uploads/" . basename($nume);
    if (move_uploaded_file($tmp, $dest)) {
      $titlu = pathinfo($nume, PATHINFO_FILENAME);
      $stmt = $conn->prepare("INSERT INTO documents (car_id, titlu, fisier) VALUES (?, ?, ?)");
      $stmt->bind_param("iss", $id, $titlu, $nume);
      $stmt->execute();
    }
  }
}

// poze noi
if (!empty($_FILES['poze']['name'][0])) {
  foreach ($_FILES['poze']['name'] as $i => $nume) {
    $tmp = $_FILES['poze']['tmp_name'][$i];
    $dest = "uploads/" . basename($nume);
    if (move_uploaded_file($tmp, $dest)) {
      $stmt = $conn->prepare("INSERT INTO car_photos (car_id, filename) VALUES (?, ?)");
      $stmt->bind_param("is", $id, $nume);
      $stmt->execute();
    }
  }
}

header("Location: edit_car.php?id=$id");
exit();
?>
