<?php
require_once __DIR__ . '/config.php';

function getDB() {
    $dir = dirname(DB_PATH);
    if (!is_dir($dir)) mkdir($dir, 0755, true);

    $db = new SQLite3(DB_PATH);
    $db->exec("PRAGMA journal_mode=WAL");

    $db->exec("CREATE TABLE IF NOT EXISTS cars (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        model_year INTEGER,
        daily_price INTEGER NOT NULL,
        image_url TEXT DEFAULT '',
        available INTEGER DEFAULT 1,
        seats INTEGER DEFAULT 5,
        luggage INTEGER DEFAULT 2,
        transmission TEXT DEFAULT 'Manuel',
        fuel TEXT DEFAULT 'Benzin',
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");

    $db->exec("CREATE TABLE IF NOT EXISTS reservations (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        car_id INTEGER,
        car_name TEXT,
        customer_name TEXT NOT NULL,
        customer_phone TEXT NOT NULL,
        customer_email TEXT DEFAULT '',
        pickup_airport TEXT NOT NULL,
        dropoff_airport TEXT NOT NULL,
        pickup_date TEXT NOT NULL,
        dropoff_date TEXT NOT NULL,
        total_price INTEGER,
        status TEXT DEFAULT 'beklemede',
        payment_method TEXT DEFAULT 'havale',
        iban_requested INTEGER DEFAULT 0,
        iban_sent TEXT DEFAULT NULL,
        iban_sent_at DATETIME DEFAULT NULL,
        iban_expired INTEGER DEFAULT 0,
        notes TEXT DEFAULT '',
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");

    $db->exec("CREATE TABLE IF NOT EXISTS settings (
        key TEXT PRIMARY KEY,
        value TEXT NOT NULL
    )");

    // Mevcut DB migration
    $cols = [];
    $r = $db->query("PRAGMA table_info(reservations)");
    while ($row = $r->fetchArray(SQLITE3_ASSOC)) $cols[] = $row['name'];
    if (!in_array('iban_sent_at',   $cols)) $db->exec("ALTER TABLE reservations ADD COLUMN iban_sent_at DATETIME DEFAULT NULL");
    if (!in_array('iban_expired',   $cols)) $db->exec("ALTER TABLE reservations ADD COLUMN iban_expired INTEGER DEFAULT 0");
    if (!in_array('iban_requested', $cols)) $db->exec("ALTER TABLE reservations ADD COLUMN iban_requested INTEGER DEFAULT 0");
    if (!in_array('iban_sent',      $cols)) $db->exec("ALTER TABLE reservations ADD COLUMN iban_sent TEXT DEFAULT NULL");
    if (!in_array('payment_method', $cols)) $db->exec("ALTER TABLE reservations ADD COLUMN payment_method TEXT DEFAULT 'havale'");
    if (!in_array('tc_no',          $cols)) $db->exec("ALTER TABLE reservations ADD COLUMN tc_no TEXT DEFAULT ''");
    if (!in_array('rezervasyon_no', $cols)) $db->exec("ALTER TABLE reservations ADD COLUMN rezervasyon_no TEXT DEFAULT ''");
    if (!in_array('dekont_path',    $cols)) $db->exec("ALTER TABLE reservations ADD COLUMN dekont_path TEXT DEFAULT NULL");

    // Varsayılan ayarlar
    $defaults = [
        'whatsapp_number' => '905344250782',
        'hero_title'      => 'Bayram öncesi erken rezervasyon!',
        'hero_subtitle'   => 'Avis Online Araç Kiralama',
    ];
    foreach ($defaults as $k => $v) {
        $db->exec("INSERT OR IGNORE INTO settings (key, value) VALUES ('$k', '$v')");
    }

    // Cars tablosu migration
    $carCols = [];
    $rc = $db->query("PRAGMA table_info(cars)");
    while ($row = $rc->fetchArray(SQLITE3_ASSOC)) $carCols[] = $row['name'];
    if (!in_array('seats',        $carCols)) $db->exec("ALTER TABLE cars ADD COLUMN seats INTEGER DEFAULT 5");
    if (!in_array('luggage',      $carCols)) $db->exec("ALTER TABLE cars ADD COLUMN luggage INTEGER DEFAULT 2");
    if (!in_array('transmission', $carCols)) $db->exec("ALTER TABLE cars ADD COLUMN transmission TEXT DEFAULT 'Manuel'");
    if (!in_array('fuel',         $carCols)) $db->exec("ALTER TABLE cars ADD COLUMN fuel TEXT DEFAULT 'Benzin'");

    // İlk araçları ekle (2026 model, güncel fiyatlar)
    $count = $db->querySingle("SELECT COUNT(*) FROM cars");
    if ($count == 0) {
        $cars = [
            // [isim, yıl, fiyat, görsel, koltuk, bavul, vites, yakıt]
            ['Renault Clio AT',       2026, 1350, 'images/Avis/Cars/f-renault-clio-at.png',     5, 2, 'Otomatik', 'Benzin'],
            ['Citroen C3',            2026, 1400, 'images/Avis/Cars/f-citroen-c3.png',           5, 2, 'Manuel',   'Benzin'],
            ['Fiat Egea',             2026, 1450, 'images/Avis/Cars/n-fiat-egea.png',            5, 2, 'Manuel',   'Benzin'],
            ['Fiat Egea AT',          2026, 1600, 'images/Avis/Cars/ra-fiat-egea-at.png',        5, 2, 'Otomatik', 'Benzin'],
            ['Hyundai i20',           2026, 1500, 'images/Avis/Cars/f-hyundai-i20.png',          5, 2, 'Manuel',   'Benzin'],
            ['Opel Corsa',            2026, 1550, 'images/Avis/Cars/f-opel-corsa.png',           5, 2, 'Manuel',   'Benzin'],
            ['Seat Ibiza',            2026, 1600, 'images/Avis/Cars/f-seat-ibiza.png',           5, 2, 'Manuel',   'Benzin'],
            ['Fiat Egea Cross',       2026, 1700, 'images/Avis/Cars/b-fiat-egea-cross.png',      5, 2, 'Manuel',   'Benzin'],
            ['Citroen C4X',           2026, 2200, 'images/Avis/Cars/ra-citroen-c4x.png',         5, 2, 'Otomatik', 'Benzin'],
            ['Ford Focus',            2026, 2000, 'images/Avis/Cars/o-ford-focus.png',           5, 2, 'Otomatik', 'Benzin'],
            ['Toyota Corolla',        2026, 2100, 'images/Avis/Cars/o-toyota-corolla.png',       5, 2, 'Otomatik', 'Hibrit'],
            ['Peugeot 408',           2026, 2200, 'images/Avis/Cars/o-peugeot-408.png',          5, 2, 'Otomatik', 'Benzin'],
            ['Ford Puma',             2026, 2400, 'images/Avis/Cars/p-ford-puma.png',            5, 2, 'Otomatik', 'Benzin'],
            ['Opel Mokka',            2026, 2400, 'images/Avis/Cars/p-opel-mokka.png',           5, 2, 'Otomatik', 'Benzin'],
            ['Peugeot 2008',          2026, 2500, 'images/Avis/Cars/p-peugeot-2008.png',         5, 2, 'Otomatik', 'Benzin'],
            ['Seat Ateca',            2026, 3000, 'images/Avis/Cars/d-seat-ateca.png',           5, 2, 'Otomatik', 'Benzin'],
            ['Renault Austral',       2026, 3200, 'images/Avis/Cars/d-renault-austral.png',      5, 2, 'Otomatik', 'Hibrit'],
            ['Toyota Corolla Cross',  2026, 3300, 'images/Avis/Cars/d-toyota-corolla-cross.png', 5, 2, 'Otomatik', 'Hibrit'],
            ['Opel Grandland',        2026, 3200, 'images/Avis/Cars/d-opel-grandland.png',       5, 2, 'Otomatik', 'Benzin'],
            ['Peugeot 3008',          2026, 3500, 'images/Avis/Cars/d-peugeot-3008.png',         5, 2, 'Otomatik', 'Benzin'],
            ['Ford Kuga',             2026, 3500, 'images/Avis/Cars/d-ford-kuga.png',            5, 2, 'Otomatik', 'Benzin'],
            ['MG HS',                 2026, 3600, 'images/Avis/Cars/d-mg-hs.png',               5, 2, 'Otomatik', 'Benzin'],
            ['BYD Seal U DM-i',       2026, 3800, 'images/Avis/Cars/d-byd-seal-u-dm-i.png',     5, 2, 'Otomatik', 'Hibrit'],
            ['Audi A3',               2026, 3800, 'images/Avis/Cars/h-audi-a3.png',             5, 2, 'Otomatik', 'Benzin'],
            ['BMW 2 Serisi',          2026, 4000, 'images/Avis/Cars/h-bmw-2-serisi.png',         5, 2, 'Otomatik', 'Benzin'],
            ['Skoda Superb',          2026, 4000, 'images/Avis/Cars/j-skoda-superb.png',         5, 2, 'Otomatik', 'Benzin'],
            ['Volvo S60',             2026, 4200, 'images/Avis/Cars/c-volvo-s60.png',            5, 2, 'Otomatik', 'Benzin'],
            ['BMW 3 Serisi',          2026, 4500, 'images/Avis/Cars/c-bmw-3-serisi.png',         5, 2, 'Otomatik', 'Benzin'],
            ['Volvo XC60',            2026, 4800, 'images/Avis/Cars/m-volvo-xc60.png',           5, 2, 'Otomatik', 'Benzin'],
            ['Peugeot 5008',          2026, 4800, 'images/Avis/Cars/l-peugeot-5008.png',         7, 3, 'Otomatik', 'Benzin'],
            ['Audi A6',               2026, 5500, 'images/Avis/Cars/e-audi-a6.png',             5, 2, 'Otomatik', 'Benzin'],
            ['BMW 5 Serisi',          2026, 6000, 'images/Avis/Cars/e-bmw-5-serisi.png',         5, 2, 'Otomatik', 'Benzin'],
            ['Volvo EX40',            2026, 5000, 'images/Avis/Cars/g-volvo-ex40.png',           5, 2, 'Otomatik', 'Elektrik'],
            ['Volvo XC90',            2026, 7000, 'images/Avis/Cars/k-volvo-xc90.png',           7, 3, 'Otomatik', 'Benzin'],
            ['Fiat Ulysee',           2026, 4500, 'images/Avis/Cars/i-fiat-ulysee.png',          7, 3, 'Otomatik', 'Dizel'],
            ['Ford Ranger',           2026, 5500, 'images/Avis/Cars/i-ford-ranger.png',          5, 3, 'Otomatik', 'Dizel'],
        ];
        $stmt = $db->prepare("INSERT INTO cars (name,model_year,daily_price,image_url,available,seats,luggage,transmission,fuel) VALUES (:n,:y,:p,:i,1,:s,:l,:t,:f)");
        foreach ($cars as $c) {
            $stmt->bindValue(':n', $c[0]); $stmt->bindValue(':y', $c[1]);
            $stmt->bindValue(':p', $c[2]); $stmt->bindValue(':i', $c[3]);
            $stmt->bindValue(':s', $c[4]); $stmt->bindValue(':l', $c[5]);
            $stmt->bindValue(':t', $c[6]); $stmt->bindValue(':f', $c[7]);
            $stmt->execute(); $stmt->reset();
        }
    }

    return $db;
}

function sendTelegram($message) {
    $db     = getDB();
    $token  = $db->querySingle("SELECT value FROM settings WHERE key='telegram_token'")  ?: TELEGRAM_BOT_TOKEN;
    $chatId = $db->querySingle("SELECT value FROM settings WHERE key='telegram_chat_id'") ?: TELEGRAM_CHAT_ID;
    if (empty($token) || empty($chatId)) return;
    $url  = "https://api.telegram.org/bot{$token}/sendMessage";
    $data = http_build_query(['chat_id' => $chatId, 'text' => $message, 'parse_mode' => 'HTML']);
    $ctx  = stream_context_create(['http' => ['method' => 'POST', 'header' => 'Content-Type: application/x-www-form-urlencoded', 'content' => $data, 'timeout' => 5]]);
    @file_get_contents($url, false, $ctx);
}

function jsonResponse($data, $code = 200) {
    http_response_code($code);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function getInput() {
    $raw = file_get_contents('php://input');
    return json_decode($raw, true) ?: [];
}

function isAdminLoggedIn() {
    session_start();
    return !empty($_SESSION['admin_logged_in']);
}
