<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

require_once __DIR__ . '/db.php';
$db     = getDB();
$method = $_SERVER['REQUEST_METHOD'];
$id     = isset($_GET['id']) ? (int)$_GET['id'] : null;

if ($method === 'GET') {
    if ($id) {
        $stmt = $db->prepare("SELECT * FROM cars WHERE id = :id");
        $stmt->bindValue(':id', $id);
        $row = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
        $row ? jsonResponse($row) : jsonResponse(['error' => 'Bulunamadı'], 404);
    } else {
        $only_available = isset($_GET['available']);
        $sql = $only_available
            ? "SELECT * FROM cars WHERE available=1 ORDER BY daily_price ASC"
            : "SELECT * FROM cars ORDER BY daily_price ASC";
        $res  = $db->query($sql);
        $rows = [];
        while ($r = $res->fetchArray(SQLITE3_ASSOC)) $rows[] = $r;
        jsonResponse($rows);
    }
}

if ($method === 'POST') {
    $d = getInput();
    if (empty($d['name']) || empty($d['daily_price'])) jsonResponse(['error' => 'İsim ve fiyat zorunlu'], 400);
    $stmt = $db->prepare("INSERT INTO cars (name, model_year, daily_price, image_url, available) VALUES (:n,:y,:p,:i,:a)");
    $stmt->bindValue(':n', $d['name']);
    $stmt->bindValue(':y', $d['model_year'] ?? null);
    $stmt->bindValue(':p', (int)$d['daily_price']);
    $stmt->bindValue(':i', $d['image_url'] ?? '');
    $stmt->bindValue(':a', isset($d['available']) ? (int)$d['available'] : 1);
    $stmt->execute();
    jsonResponse(['id' => $db->lastInsertRowID(), 'message' => 'Araç eklendi']);
}

if ($method === 'PUT' && $id) {
    $d = getInput();
    $stmt = $db->prepare("UPDATE cars SET name=:n, model_year=:y, daily_price=:p, image_url=:i, available=:a WHERE id=:id");
    $stmt->bindValue(':n',  $d['name']);
    $stmt->bindValue(':y',  $d['model_year'] ?? null);
    $stmt->bindValue(':p',  (int)$d['daily_price']);
    $stmt->bindValue(':i',  $d['image_url'] ?? '');
    $stmt->bindValue(':a',  (int)$d['available']);
    $stmt->bindValue(':id', $id);
    $stmt->execute();
    jsonResponse(['message' => 'Güncellendi']);
}

if ($method === 'DELETE' && $id) {
    $db->exec("DELETE FROM cars WHERE id = $id");
    jsonResponse(['message' => 'Silindi']);
}
