<?php
declare(strict_types=1);

// Force write test for log
@file_put_contents('/home/akgbilis/fi_sf/error.log', date('Y-m-d H:i:s') . " ✅ give_credit started\n", FILE_APPEND);
@file_put_contents(sys_get_temp_dir() . '/give_credit_test.log', date('Y-m-d H:i:s') . " ✅ tempdir test\n", FILE_APPEND);

advancedLog('INFO', '========================= NEW give_credit REQUEST STARTED =========================', __FILE__, __LINE__, '');

ini_set('display_errors', '1');
ini_set('log_errors', '1');
error_reporting(E_ALL);

ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', '/home/akgbilis/fi_sf/error.log');
error_reporting(E_ALL);

advancedLog('DEBUG', 'give_credit.php reached start point', __FILE__, __LINE__, '');

// ============================================
// GELİŞMİŞ LOG SİSTEMİ
// ============================================
function getLogFilePath(): string {
    $paths = [
        '/home/akgbilis/fi_sf/error.log',
        '/home/gorevci/public_html/betsaipanel2/error.log',
        sys_get_temp_dir() . '/give_credit_error.log'
    ];
    foreach ($paths as $path) {
        $dir = dirname($path);
        if (!is_dir($dir)) {
            @mkdir($dir, 0777, true);
        }
        if (!file_exists($path)) {
            @touch($path);
        }
        if (is_writable($path)) {
            return $path;
        }
    }
    $fallback = sys_get_temp_dir() . '/give_credit_error.log';
    @touch($fallback);
    return $fallback;
}

function advancedLog($level, $message, $data = null, $code = null, $trace = null) {
    if (is_array($trace)) {
        $trace = json_encode($trace, JSON_PRETTY_PRINT);
    }

    $log = sprintf("[%s] %s: %s | data=%s | code=%s | trace=%s\n",
        date('Y-m-d H:i:s'),
        strtoupper($level),
        $message,
        json_encode($data, JSON_UNESCAPED_UNICODE),
        $code,
        $trace
    );

    error_log($log, 3, '/home/akgbilis/fi_sf/betsai_debug.log');
}
advancedLog('DEBUG', 'give_credit.php reached start point', __FILE__, __LINE__, '');

// ============================================
// 1. BUFFER VE ERROR YÖNETİMİ
// ============================================
while (ob_get_level()) ob_end_clean();
ob_start();

error_reporting(E_ALL);
ini_set('display_errors', '1');

// ============================================
// 2. YARDIMCI FONKSİYON - JSON GÖNDER VE ÇIK
// ============================================
function sendJson($data, $code = 200) {
    advancedLog('DEBUG', 'Preparing sendJson with data=' . json_encode($data) . ' and code=' . $code, __FILE__, __LINE__, '');
    if ($code >= 400) {
        advancedLog('ERROR', '❌ sendJson HTTP=' . $code . ' payload=' . json_encode($data), __FILE__, __LINE__, json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)));
    }
    while (ob_get_level()) ob_end_clean();
    http_response_code($code);
    header('Content-Type: application/json; charset=utf-8');
    header_remove('X-Powered-By');
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

// ============================================
// 3. FATAL ERROR YAKALAMA
// ============================================
register_shutdown_function(function() {
    $error = error_get_last();
    if ($error !== null && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        // Log fatal error with advanced log
        advancedLog(
            'FATAL',
            $error['message'],
            $error['file'] ?? '',
            $error['line'] ?? 0,
            '' // No trace available here
        );

        while (ob_get_level()) ob_end_clean();
        http_response_code(500);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['error' => 'Fatal error', 'detail' => $error['message']]);
        exit;
    }
});

// ============================================
// 4. BAŞLANGIÇ HEADER'LARI
// ============================================
header('Content-Type: application/json; charset=utf-8');
header_remove('X-Powered-By');

// ============================================
// 5. REQUIRE FILES
// ============================================
try {
    require_once '/home/akgbilis/fi_sf/config.php';

    if (isset($pdo)) {
        $GLOBALS['pdo'] = $pdo;
        advancedLog('DEBUG', 'PDO found and stored globally', __FILE__, __LINE__, '');
    } elseif (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
        $pdo = $GLOBALS['pdo'];
        advancedLog('DEBUG', 'Using global PDO fallback', __FILE__, __LINE__, '');
    } else {
        advancedLog('FATAL', 'PDO not found even after config include', __FILE__, __LINE__, '');
        sendJson(["error" => "Database connection missing"], 500);
    }

    // vendor klasörünü mutlak path ile yükle
    $vendorPath = '/home/akgbilis/fi_sf/vendor/autoload.php';
    if (!file_exists($vendorPath)) {
        $vendorPath = '/home/gorevci/public_html/betsaipanel2/vendor/autoload.php';
    }
    if (!file_exists($vendorPath)) {
        advancedLog('FATAL', "Vendor autoload.php not found at $vendorPath", __FILE__, __LINE__, '');
        sendJson(["error" => "Vendor autoload.php missing", "path" => $vendorPath], 500);
    }
    require_once $vendorPath;
    advancedLog('DEBUG', "Vendor autoload loaded from $vendorPath", __FILE__, __LINE__, '');
} catch (Exception $e) {
    advancedLog('EXCEPTION', $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
    sendJson(["error" => "Failed to load dependencies", "detail" => $e->getMessage()], 500);
}

if (!isset($pdo) || !$pdo instanceof PDO) {
    advancedLog('FATAL', 'PDO not initialized after config.php include', __FILE__, __LINE__, '');
    sendJson(["error" => "Database connection missing"], 500);
}

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

// ============================================
// 6. ENV YÜKLEME
// ============================================
$envPath = '/home/akgbilis/fi_sf/.env.php';
if (!file_exists($envPath)) {
    $envPath = __DIR__ . '/../../.env.php';
}
if (!file_exists($envPath)) {
    sendJson(["error" => "Env file missing"], 500);
}
$env = require $envPath;

// ============================================
// 7. HEADER KONTROLÜ
// ============================================
// --- Enhanced header fetch for environments without getallheaders ---
function getRequestHeaders(): array {
    $headers = [];
    foreach ($_SERVER as $name => $value) {
        if (str_starts_with($name, 'HTTP_')) {
            $formatted = str_replace('_', '-', substr($name, 5));
            $headers[$formatted] = $value;
        }
    }
    return $headers;
}

$headers = function_exists('getallheaders') ? getallheaders() : getRequestHeaders();
advancedLog('DEBUG', 'Incoming headers: ' . json_encode($headers), __FILE__, __LINE__, '');
advancedLog('DEBUG', 'All request headers: ' . json_encode($headers), __FILE__, __LINE__, '');

// AppAuth kontrolü
$appAuth = $headers['X-App-Auth'] ?? $headers['X-APP-AUTH'] ?? '';

// JWT kontrolü
$authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
if (!preg_match('/Bearer\s+(\S+)/', $authHeader, $matches)) {
    sendJson(["error" => "Missing token"], 401);
}

$jwt = $matches[1];

// ============================================
// 8. JWT DECODE
// ============================================
advancedLog('DEBUG', 'Decoding JWT token...', __FILE__, __LINE__, '');
try {
    $decoded = JWT::decode($jwt, new Key($env['jwt_secret'], 'HS256'));
    $userId = $decoded->sub;
    advancedLog('DEBUG', 'JWT decoded successfully for userId=' . $decoded->sub, __FILE__, __LINE__, '');
} catch (Exception $e) {
    advancedLog('EXCEPTION', $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
    sendJson(["error" => "Invalid token", "detail" => $e->getMessage()], 401);
}

// ============================================
// 9. KULLANICI KONTROLÜ
// ============================================
try {
    $stmt = $pdo->prepare("SELECT id, credits FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    advancedLog('DEBUG', 'User fetched: ' . json_encode($user), __FILE__, __LINE__, '');
    
    if (!$user) {
        sendJson(["error" => "User not found"], 404);
    }
} catch (PDOException $e) {
    advancedLog('EXCEPTION', $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
    sendJson(["error" => "Database error", "detail" => $e->getMessage()], 500);
}

// ============================================
// 10. INPUT PARSING
// ============================================
$raw = file_get_contents("php://input");
advancedLog('DEBUG', 'Raw input: ' . $raw, __FILE__, __LINE__, '');
advancedLog('DEBUG', 'Received raw POST input: ' . $raw, __FILE__, __LINE__, '');
$data = json_decode($raw, true);
advancedLog('DEBUG', 'Decoded JSON: ' . json_encode($data), __FILE__, __LINE__, '');

if (json_last_error() !== JSON_ERROR_NONE) {
    advancedLog('WARN', '400 FAIL: reason=' . json_encode($data ?? []), __FILE__, __LINE__, '');
    sendJson(["error" => "Invalid JSON input", "detail" => json_last_error_msg()], 400);
}

$productId = $data['productId'] ?? '';
$purchaseToken = $data['purchaseToken'] ?? '';

if (!$productId || !$purchaseToken) {
    advancedLog('WARN', '400 FAIL: reason=' . json_encode($data ?? []), __FILE__, __LINE__, '');
    sendJson(["error" => "Missing productId or purchaseToken"], 400);
}

// ============================================
// 11. REPLAY KONTROLÜ
// ============================================
try {
    $stmt = $pdo->prepare("SELECT id FROM purchase_tokens WHERE token = ?");
    $stmt->execute([$purchaseToken]);
    
    if ($stmt->fetch()) {
        advancedLog('WARN', '400 FAIL: reason=' . json_encode($data ?? []), __FILE__, __LINE__, '');
        sendJson(["error" => "Token already used"], 400);
    }
} catch (PDOException $e) {
    advancedLog('EXCEPTION', $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
    sendJson(["error" => "Database error", "detail" => $e->getMessage()], 500);
}

// ============================================
// 12. GOOGLE PLAY DOĞRULAMASI
// ============================================
$verifyPayload = json_encode([
    "productId" => $productId,
    "purchaseToken" => $purchaseToken
]);

advancedLog('DEBUG', 'Sending verify payload: ' . $verifyPayload, __FILE__, __LINE__, '');

$ch = curl_init($env['vp_url'] ?? '');
if ($ch === false) {
    sendJson(["error" => "Failed to initialize verification request"], 500);
}

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $verifyPayload,
    CURLOPT_TIMEOUT => 10,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false
]);

$verifyResponse = curl_exec($ch);
$curlError = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

advancedLog('DEBUG', 'verify_purchase raw response: ' . ($verifyResponse ?: 'FALSE') . ', HTTP=' . $httpCode . ', CURL error=' . ($curlError ?: 'none'), __FILE__, __LINE__, '');

if ($verifyResponse === false) {
    sendJson(["error" => "Verification request failed", "detail" => $curlError], 500);
}

advancedLog('DEBUG', 'verify_purchase response: ' . $verifyResponse . ' (HTTP ' . $httpCode . ')', __FILE__, __LINE__, '');

$verification = json_decode($verifyResponse, true);

advancedLog('DEBUG', 'Decoded verify_purchase JSON: ' . json_encode($verification), __FILE__, __LINE__, '');

// Verification kontrolü
if (!$verification || 
    empty($verification['ok']) || 
    ($verification['purchaseState'] ?? '') !== 'PURCHASED') {
    
    advancedLog('WARN', '400 FAIL: reason=' . json_encode($verification ?? []), __FILE__, __LINE__, '');
    sendJson([
        "error" => "Purchase verification failed", 
        "raw" => $verifyResponse,
        "httpCode" => $httpCode
    ], 400);
}

// ============================================
// 13. ÜRÜN EŞLEMESİ
// ============================================
$creditMap = [
    "credits_50" => 50,
    "credits_100" => 100,
    "credits_250" => 250,
    "credits_500" => 500,
    "credits_1000" => 1250,
];

$amount = $creditMap[$productId] ?? 0;

if ($amount <= 0) {
    advancedLog('WARN', '400 FAIL: reason=' . json_encode(['productId' => $productId]) , __FILE__, __LINE__, '');
    sendJson(["error" => "Unknown product", "productId" => $productId], 400);
}

// ============================================
// 14. DATABASE İŞLEMLERİ
// ============================================
try {
    advancedLog('DEBUG', 'Starting DB transaction for userId=' . $userId . ', product=' . $productId . ', amount=' . $amount, __FILE__, __LINE__, '');
    $pdo->beginTransaction();

    // Token kaydet
    $stmt = $pdo->prepare("INSERT INTO purchase_tokens (token, product_id, user_id) VALUES (?, ?, ?)");
    $stmt->execute([$purchaseToken, $productId, $userId]);

    // Kredileri güncelle
    $stmt = $pdo->prepare("UPDATE users SET credits = credits + ? WHERE id = ?");
    $stmt->execute([$amount, $userId]);

    // Yeni bakiyeyi al
    $stmt = $pdo->prepare("SELECT credits FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $newBalance = $stmt->fetchColumn();

    $pdo->commit();

    advancedLog('DEBUG', 'Transaction committed successfully. New balance=' . $newBalance, __FILE__, __LINE__, '');

    // Başarılı yanıt
    sendJson([
        "success" => true,
        "message" => "$amount credits added successfully",
        "credits" => (int)$newBalance,
        "productId" => $productId,
        "userId" => $userId
    ], 200);

    advancedLog('INFO', '✅ give_credit SUCCESS for userId=' . $userId . ', amount=' . $amount . ', product=' . $productId, __FILE__, __LINE__, '');
} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
        advancedLog('ERROR', 'Transaction failed and rolled back: ' . $e->getMessage(), __FILE__, __LINE__, $e->getTraceAsString());
    }
    
    // Log error with advanced log
    advancedLog('EXCEPTION', $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
    
    sendJson([
        "error" => "Transaction failed", 
        "detail" => $e->getMessage()
    ], 500);
}

// Custom error handler
set_error_handler(function ($errno, $errstr, $errfile, $errline) {
    $msg = "$errstr";
    advancedLog('PHP ERROR', $msg, $errfile, $errline, '');
    return false; // Let default handler continue
});

// Exception handler
set_exception_handler(function ($e) {
    advancedLog('UNCAUGHT EXCEPTION', $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode(["error" => "Internal Server Error", "detail" => $e->getMessage()]);
    exit;
});

// ================= FINAL DEBUG SNAPSHOT =================
advancedLog('DEBUG', '================= FINAL DEBUG SNAPSHOT =================', __FILE__, __LINE__, '');
$snapshot = [
    'SERVER' => $_SERVER,
    'HEADERS' => $headers ?? [],
    'DATA' => $data ?? [],
    'VERIFICATION' => $verification ?? [],
    'USER' => $user ?? [],
    'productId' => $productId ?? null,
    'purchaseToken' => $purchaseToken ?? null,
    'amount' => $amount ?? null,
    'userId' => $userId ?? null,
    'httpCode' => $httpCode ?? null
];
advancedLog('DEBUG', 'Snapshot: ' . json_encode($snapshot, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), __FILE__, __LINE__, '');