<?php
require_once __DIR__ . '/../auth_middleware.php';
require_once '/home/akgbilis/fi_sf/config.php';

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

// 🧠 Gelişmiş log fonksiyonu
function logRequest($step, $data = []) {
    $logFile = __DIR__ . '/generate_combine_log.txt';
    $entry = "[" . date("Y-m-d H:i:s") . "] STEP: $step\n";
    $entry .= "DATA: " . print_r($data, true) . "\n";
    $entry .= "-----------------------------\n";
    file_put_contents($logFile, $entry, FILE_APPEND);
}

// 1. Gelen raw veriyi logla
$raw = file_get_contents("php://input");
logRequest("RAW INPUT", ['raw' => $raw]);

$data = json_decode($raw, true);
$type = $data['type'] ?? null;

// 2. Auth kullanıcısı ve tür kontrolü
$userId = $decoded->sub ?? null;
logRequest("AUTH + TYPE", ['userId' => $userId, 'type' => $type]);

if (!$userId || !in_array($type, ['low', 'medium', 'high'])) {
    logRequest("FAILED: INVALID USER OR TYPE", []);
    echo json_encode(['success' => false, 'message' => 1]);
    exit;
}

$ranges = [
    'low' => [1.10, 1.30],
    'medium' => [1.31, 1.99],
    'high' => [2.00, 100.00]
];
$creditCosts = [
    'low' => 5,
    'medium' => 10,
    'high' => 15
];

list($min, $max) = $ranges[$type];
$creditToDeduct = $creditCosts[$type];

// 3. Kredi kontrolü
try {
    $creditStmt = $pdo->prepare("SELECT credits FROM users WHERE id = ?");
    $creditStmt->execute([$userId]);
    $userCredits = (int) $creditStmt->fetchColumn();
    logRequest("USER CREDITS", ['credits' => $userCredits]);
} catch (Exception $e) {
    logRequest("DB ERROR: CREDITS", ['error' => $e->getMessage()]);
    echo json_encode(['success' => false, 'message' => 'db_error']);
    exit;
}

if ($userCredits < $creditToDeduct) {
    logRequest("FAILED: INSUFFICIENT CREDITS", []);
    echo json_encode(['success' => false, 'message' => 2]);
    exit;
}

// 4. Maçları çek
try {
    $matchStmt = $pdo->prepare("SELECT * FROM matches WHERE status = 'WAITING' AND can_generate = 1 AND odds BETWEEN ? AND ? ORDER BY RAND()");
    $matchStmt->execute([$min, $max]);
    $allMatches = $matchStmt->fetchAll(PDO::FETCH_ASSOC);
    logRequest("FETCHED MATCHES", ['count' => count($allMatches)]);
} catch (Exception $e) {
    logRequest("DB ERROR: MATCHES", ['error' => $e->getMessage()]);
    echo json_encode(['success' => false, 'message' => 'db_error']);
    exit;
}

$matchCount = ($type === 'high') ? 2 : 3;

// 5. Kombinasyon üret
$validCombine = null;
foreach (combinations($allMatches, $matchCount) as $combo) {
    $matchKeys = array_map(function ($m) {
        return $m['home'] . ' vs ' . $m['away'];
    }, $combo);

    if (count(array_unique($matchKeys)) < $matchCount) {
        continue;
    }

    $total = array_reduce($combo, function ($carry, $m) {
        return $carry * floatval($m['odds']);
    }, 1.0);

    $matchIds = array_map(function ($m) {
        return $m['id'];
    }, $combo);
    sort($matchIds);
    $matchHash = sha1(implode('-', $matchIds));

    $check = $pdo->prepare("SELECT COUNT(*) FROM user_generated_combines WHERE user_id = ? AND match_hash = ?");
    $check->execute([$userId, $matchHash]);
    if ($check->fetchColumn() > 0) {
        continue;
    }

    $validCombine = [$combo, $total, $matchHash];
    logRequest("VALID COMBINE FOUND", ['totalOdds' => $total]);
    break;
}

if (!$validCombine) {
    logRequest("FAILED: NO VALID COMBINE", []);
    echo json_encode(['success' => false, 'message' => 3]);
    exit;
}

list($matches, $totalOdds, $matchHash) = $validCombine;
$combineId = bin2hex(random_bytes(8));

// 6. Kombini kaydet
try {
    $insertCombine = $pdo->prepare("INSERT INTO user_generated_combines (id, user_id, total_odds, category, match_hash) VALUES (?, ?, ?, ?, ?)");
    $insertCombine->execute([$combineId, $userId, $totalOdds, $type, $matchHash]);

    $insertMatch = $pdo->prepare("INSERT INTO user_generated_combine_matches (combine_id, match_id) VALUES (?, ?)");
    foreach ($matches as $match) {
        $insertMatch->execute([$combineId, $match['id']]);
    }

    $updateCredit = $pdo->prepare("UPDATE users SET credits = credits - ? WHERE id = ?");
    $updateCredit->execute([$creditToDeduct, $userId]);

    // ✅ Yeni kredi miktarını tekrar al
    $creditStmt = $pdo->prepare("SELECT credits FROM users WHERE id = ?");
    $creditStmt->execute([$userId]);
    $updatedCredits = (int) $creditStmt->fetchColumn();

    logRequest("COMBINE SAVED", ['combineId' => $combineId, 'newCredits' => $updatedCredits]);
} catch (Exception $e) {
    logRequest("DB ERROR: SAVE COMBINE", ['error' => $e->getMessage()]);
    echo json_encode(['success' => false, 'message' => 'db_error']);
    exit;
}

// 7. Başarılı yanıt
$response = [
    'success' => true,
    'combine_id' => $combineId,
    'total_odds' => round($totalOdds, 2),
    'matches' => $matches,
    'message' => 0,
    'credits' => $updatedCredits // ✅ arayüz için yeni kredi bilgisi
];

logRequest("FINAL RESPONSE", $response);
echo json_encode($response);

// 🔁 Kombinasyon fonksiyonu
function combinations($array, $size) {
    $result = [];

    $recurse = function ($prefix, $remaining, $size) use (&$result, &$recurse) {
        if ($size === 0) {
            $result[] = $prefix;
            return;
        }
        for ($i = 0; $i < count($remaining); $i++) {
            $recurse(array_merge($prefix, [$remaining[$i]]), array_slice($remaining, $i + 1), $size - 1);
        }
    };

    $recurse([], $array, $size);
    return $result;
}