<?php
header('Content-Type: application/json');

$servername = "localhost";
$username = "blacrhdy_bet1";
$password = "blacrhdy_bet1";
$dbname = "blacrhdy_bet1";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die(json_encode(['success' => false, 'message' => 'Database connection failed: ' . $conn->connect_error]));
}

session_start();
if (!isset($_SESSION['username'])) {
    echo json_encode(['success' => false, 'message' => 'User not logged in.']);
    exit;
}

$aktif_kullanici_username = $_SESSION['username'];

$kullanici_id_sql = "SELECT id, ana_bakiye FROM kullanicilar WHERE username = ?";
$stmt = $conn->prepare($kullanici_id_sql);
$stmt->bind_param("s", $aktif_kullanici_username);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    $kullanici = $result->fetch_assoc();
    $aktif_kullanici_id = $kullanici['id'];
    $ana_bakiye = $kullanici['ana_bakiye'];
} else {
    echo json_encode(['success' => false, 'message' => 'User not found.']);
    exit;
}

if ($ana_bakiye > 5) {
    echo json_encode(['success' => false, 'message' => 'Bakiyenizin 5 TL den fazla olması durumunda bonus verilmemektedir.']);
    exit;
}

$request = json_decode(file_get_contents('php://input'), true);

if ($request['action'] === 'ver_bonusu') {
    $bonusTuru = $request['bonusTuru'];
    $bugun = date('Y-m-d');
    $saat = date('H:i');

    $gunluk_kontrol_sql = "SELECT * FROM bonus_talepleri WHERE uye_id = ? AND tarih = ? AND bonus_turu = ?";
    $stmt = $conn->prepare($gunluk_kontrol_sql);
    $stmt->bind_param("iss", $aktif_kullanici_id, $bugun, $bonusTuru);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        echo json_encode(['success' => false, 'message' => 'Bu bonusu bugün zaten talep etmiştiniz.']);
        exit;
    }

    $bonus_miktari = 0;
    switch ($bonusTuru) {
        case '%30 GECE KAYIP BONUSU':
            if ($saat < '00:00' || $saat > '08:00') {
                echo json_encode(['success' => false, 'message' => 'Gece Kayıp Bonusu yalnızca 00:00 ile 08:00 saatleri arasında talep edilebilir.']);
                exit;
            }
            $bonus_miktari = $ana_bakiye * 0.30;
            break;
        case '%20 KAYIP BONUSU':
            $bonus_miktari = $ana_bakiye * 0.20;
            break;
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid bonus type.']);
            exit;
    }

    $conn->begin_transaction();
    $wr = 0.0;
    $wrq = $conn->prepare("SELECT wagering_requirement, no_wagering FROM bonus_types WHERE name = ? LIMIT 1");
    $wrq->bind_param("s", $bonusTuru);
    $wrq->execute();
    $wrres = $wrq->get_result();
    $no_wr = 0;
    if ($wrrow = $wrres->fetch_assoc()) { $wr = floatval($wrrow['wagering_requirement']); $no_wr = intval($wrrow['no_wagering']) ? 1 : 0; }
    $wrq->close();
    $insert_sql = "INSERT INTO bonus_talepleri (uye_id, bonus_turu, miktar, tarih, durum, wagering_requirement, no_wagering) VALUES (?, ?, ?, ?, 1, ?, ?)";
    $insert_stmt = $conn->prepare($insert_sql);
    $insert_stmt->bind_param("isdsii", $aktif_kullanici_id, $bonusTuru, $bonus_miktari, $bugun, $wr, $no_wr);

    if ($insert_stmt->execute()) {
        $update_sql = "UPDATE kullanicilar SET ana_bakiye = ana_bakiye + ? WHERE id = ?";
        $upd = $conn->prepare($update_sql);
        $upd->bind_param("di", $bonus_miktari, $aktif_kullanici_id);
        if ($upd->execute()) {
            $conn->commit();
            echo json_encode(['success' => true, 'message' => 'Bonus başarıyla hesabınıza eklendi.']);
        } else {
            $conn->rollback();
            echo json_encode(['success' => false, 'message' => 'Bonus bakiye güncellemesi başarısız.']);
        }
        $upd->close();
    } else {
        $conn->rollback();
        echo json_encode(['success' => false, 'message' => 'Bonus talebi oluşturulamadı.']);
    }

    $insert_stmt->close();
}

$conn->close();
?>