<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, 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;
$action = $_GET['action'] ?? null;

// GET /reservations.php
if ($method === 'GET' && !$id) {
    $sql    = "SELECT * FROM reservations";
    $params = [];
    if (!empty($_GET['status'])) { $sql .= " WHERE status = :s"; $params[':s'] = $_GET['status']; }
    $sql .= " ORDER BY created_at DESC";
    $stmt = $db->prepare($sql);
    foreach ($params as $k => $v) $stmt->bindValue($k, $v);
    $res  = $stmt->execute();
    $rows = [];
    while ($r = $res->fetchArray(SQLITE3_ASSOC)) $rows[] = $r;
    jsonResponse($rows);
}

// GET /reservations.php?id=X
if ($method === 'GET' && $id && !$action) {
    $stmt = $db->prepare("SELECT * FROM reservations WHERE id = :id");
    $stmt->bindValue(':id', $id);
    $row = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
    $row ? jsonResponse($row) : jsonResponse(['error' => 'Bulunamadı'], 404);
}

// GET /reservations.php?id=X&action=iban-status
if ($method === 'GET' && $id && $action === 'iban-status') {
    $stmt = $db->prepare("SELECT iban_sent, iban_requested, iban_sent_at, iban_expired FROM reservations WHERE id = :id");
    $stmt->bindValue(':id', $id);
    $row = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
    if (!$row) jsonResponse(['error' => 'Bulunamadı'], 404);

    // Süre kontrolü: IBAN gönderildiyse ve 15 dk geçtiyse expire et
    if ($row['iban_sent'] && $row['iban_sent_at'] && !$row['iban_expired']) {
        $sentAt  = strtotime($row['iban_sent_at']);
        $elapsed = time() - $sentAt;
        if ($elapsed >= 900) { // 15 dakika = 900 saniye
            $db->exec("UPDATE reservations SET iban_expired=1, iban_sent=NULL WHERE id=$id");
            $row['iban_sent']    = null;
            $row['iban_expired'] = 1;
        }
    }

    $remaining = null;
    if ($row['iban_sent'] && $row['iban_sent_at']) {
        $remaining = max(0, 900 - (time() - strtotime($row['iban_sent_at'])));
    }

    jsonResponse([
        'iban_sent'      => $row['iban_sent'],
        'iban_requested' => $row['iban_requested'],
        'iban_expired'   => $row['iban_expired'],
        'remaining_sec'  => $remaining,
    ]);
}

// POST /reservations.php  → yeni rezervasyon
if ($method === 'POST' && !$id) {
    $d = getInput();
    $required = ['customer_name','customer_phone','pickup_airport','dropoff_airport','pickup_date','dropoff_date'];
    foreach ($required as $f) {
        if (empty($d[$f])) jsonResponse(['error' => "Zorunlu alan eksik: $f"], 400);
    }

    $car_name    = 'Belirtilmedi';
    $total_price = null;
    $car_id      = $d['car_id'] ?? null;

    if ($car_id) {
        $stmt = $db->prepare("SELECT * FROM cars WHERE id = :id");
        $stmt->bindValue(':id', (int)$car_id);
        $car = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
        if ($car) {
            $car_name = trim($car['name'] . ' ' . ($car['model_year'] ?? ''));
            $days     = (int)ceil((strtotime($d['dropoff_date']) - strtotime($d['pickup_date'])) / 86400);
            $total_price = $days > 0 ? $days * $car['daily_price'] : $car['daily_price'];
        }
    }

    $pmethod = $d['payment_method'] ?? 'havale';
    // Rezervasyon numarası oluştur: RES-YYYYMMDD-XXXX
    $rezNo = 'RES-' . date('Ymd') . '-' . strtoupper(substr(md5(uniqid()), 0, 4));

    $stmt = $db->prepare("INSERT INTO reservations
        (car_id, car_name, customer_name, customer_phone, customer_email,
         pickup_airport, dropoff_airport, pickup_date, dropoff_date,
         total_price, payment_method, tc_no, rezervasyon_no, notes)
        VALUES (:cid,:cn,:name,:phone,:email,:pa,:da,:pd,:dd,:tp,:pm,:tc,:rno,:notes)");
    $stmt->bindValue(':cid',   $car_id);
    $stmt->bindValue(':cn',    $car_name);
    $stmt->bindValue(':name',  $d['customer_name']);
    $stmt->bindValue(':phone', $d['customer_phone']);
    $stmt->bindValue(':email', $d['customer_email'] ?? '');
    $stmt->bindValue(':pa',    $d['pickup_airport']);
    $stmt->bindValue(':da',    $d['dropoff_airport']);
    $stmt->bindValue(':pd',    $d['pickup_date']);
    $stmt->bindValue(':dd',    $d['dropoff_date']);
    $stmt->bindValue(':tp',    $total_price);
    $stmt->bindValue(':pm',    $pmethod);
    $stmt->bindValue(':tc',    $d['tc_no'] ?? '');
    $stmt->bindValue(':rno',   $rezNo);
    $stmt->bindValue(':notes', $d['notes'] ?? '');
    $stmt->execute();
    $new_id = $db->lastInsertRowID();

    $payLabel = $pmethod === 'havale' ? '🏦 Havale/EFT' : '💳 Kredi Kartı';
    $msg = "🚗 <b>Yeni Rezervasyon #{$new_id}</b>\n\n"
         . "👤 <b>Müşteri:</b> {$d['customer_name']}\n"
         . "📞 <b>Telefon:</b> {$d['customer_phone']}\n"
         . "🚘 <b>Araç:</b> {$car_name}\n"
         . "✈️ <b>Alış:</b> {$d['pickup_airport']}\n"
         . "✈️ <b>İade:</b> {$d['dropoff_airport']}\n"
         . "📅 <b>Tarih:</b> {$d['pickup_date']} → {$d['dropoff_date']}\n"
         . "💰 <b>Toplam:</b> " . ($total_price ? "{$total_price} TL" : "Hesaplanmadı") . "\n"
         . "{$payLabel}\n"
         . "📝 <b>Not:</b> " . ($d['notes'] ?? '-');
    sendTelegram($msg);

    jsonResponse(['id' => $new_id, 'message' => 'Rezervasyon oluşturuldu', 'total_price' => $total_price]);
}

// POST /reservations.php?id=X&action=request-iban
if ($method === 'POST' && $id && $action === 'request-iban') {
    $stmt = $db->prepare("SELECT * FROM reservations WHERE id = :id");
    $stmt->bindValue(':id', $id);
    $r = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
    if (!$r) jsonResponse(['error' => 'Bulunamadı'], 404);

    $db->exec("UPDATE reservations SET iban_requested=1 WHERE id=$id");

    $msg = "🏦 <b>IBAN Talebi!</b>\n\n"
         . "👤 <b>Müşteri:</b> {$r['customer_name']}\n"
         . "📞 <b>Telefon:</b> {$r['customer_phone']}\n"
         . "🚘 <b>Araç:</b> {$r['car_name']}\n"
         . "💰 <b>Tutar:</b> " . ($r['total_price'] ? "{$r['total_price']} TL" : '-') . "\n\n"
         . "⚠️ Muhasebe panelden IBAN gönderin: Rezervasyon #{$id}";
    sendTelegram($msg);

    jsonResponse(['message' => 'IBAN talebi alındı']);
}

// POST /reservations.php?id=X&action=send-iban
if ($method === 'POST' && $id && $action === 'send-iban') {
    $d     = getInput();
    $iban  = trim($d['iban']  ?? '');
    $alici = trim($d['alici'] ?? '');
    $banka = trim($d['banka'] ?? '');
    if (!$iban) jsonResponse(['error' => 'IBAN boş olamaz'], 400);

    // Alıcı ve banka bilgisini IBAN ile birlikte JSON olarak sakla
    $ibanData = json_encode(['iban' => $iban, 'alici' => $alici, 'banka' => $banka], JSON_UNESCAPED_UNICODE);

    $stmt = $db->prepare("UPDATE reservations SET iban_sent=:iban, iban_sent_at=datetime('now'), iban_expired=0 WHERE id=:id");
    $stmt->bindValue(':iban', $ibanData);
    $stmt->bindValue(':id',   $id);
    $stmt->execute();
    jsonResponse(['message' => 'IBAN gönderildi']);
}

// PATCH /reservations.php?id=X&action=status
if ($method === 'PATCH' && $id && $action === 'status') {
    $d      = getInput();
    $status = $d['status'] ?? '';
    $valid  = ['beklemede','onaylandi','iptal','tamamlandi'];
    if (!in_array($status, $valid)) jsonResponse(['error' => 'Geçersiz durum'], 400);
    $stmt = $db->prepare("UPDATE reservations SET status=:s WHERE id=:id");
    $stmt->bindValue(':s',  $status);
    $stmt->bindValue(':id', $id);
    $stmt->execute();
    jsonResponse(['message' => 'Durum güncellendi']);
}

// DELETE /reservations.php?id=X
if ($method === 'DELETE' && $id) {
    $db->exec("DELETE FROM reservations WHERE id=$id");
    jsonResponse(['message' => 'Silindi']);
}
