<?php
// ============================================================
// points.php — JSON-based Points System (No MySQL)
// ============================================================
require_once __DIR__ . '/config.php';

$root_data = (basename(__DIR__) === 'php') ? dirname(__DIR__) . '/data' : __DIR__ . '/data';
$php_data  = (basename(__DIR__) === 'php') ? __DIR__ . '/data' : __DIR__ . '/php/data';

define('DATA_DIR', $root_data);
if (!is_dir(DATA_DIR)) @mkdir(DATA_DIR, 0755, true);

if (!file_exists($root_data . '/users.json') && file_exists($php_data . '/users.json')) {
    @copy($php_data . '/users.json', $root_data . '/users.json');
}
if (!file_exists($root_data . '/jobs.json') && file_exists($php_data . '/jobs.json')) {
    @copy($php_data . '/jobs.json', $root_data . '/jobs.json');
}

$USERS_FILE = DATA_DIR . '/users.json';
$JOBS_FILE  = DATA_DIR . '/jobs.json';

// ── JSON Helpers ─────────────────────────────────────────────

function readJSON(string $file): array {
    if (!file_exists($file)) return [];
    $raw = @file_get_contents($file);
    $d = @json_decode($raw, true);
    return is_array($d) ? $d : [];
}

function writeJSON(string $file, array $data): void {
    file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), LOCK_EX);
}

function nextJobId(): int {
    global $JOBS_FILE;
    $jobs = readJSON($JOBS_FILE);
    if (empty($jobs)) return 1;
    return max(array_keys($jobs)) + 1;
}

// ── DB stub (returns a dummy truthy value for compatibility) ──
function getDB() { return true; } // No-op — JSON is used instead

// ── User Management ───────────────────────────────────────────

function getUser(int $telegramId, string $username = '', string $fullName = ''): ?array {
    global $USERS_FILE;
    $users = readJSON($USERS_FILE);
    $tid   = (string)$telegramId;

    // Auto-register owner
    if ($telegramId == OWNER_ID && !isset($users[$tid])) {
        $users[$tid] = [
            'telegram_id' => $telegramId,
            'username'    => $username,
            'full_name'   => $fullName,
            'role'        => 'owner',
            'points'      => 999999,
            'hold_points' => 0,
            'is_active'   => true,
            'created_at'  => date('Y-m-d H:i:s'),
        ];
        writeJSON($USERS_FILE, $users);
    } elseif (isset($users[$tid]) && ($username || $fullName)) {
        // Update name if changed
        if ($username) $users[$tid]['username'] = $username;
        if ($fullName) $users[$tid]['full_name'] = $fullName;
        writeJSON($USERS_FILE, $users);
    }

    return $users[$tid] ?? null;
}

function registerAdmin(int $telegramId, string $username = '', string $fullName = ''): bool {
    global $USERS_FILE;
    $users = readJSON($USERS_FILE);
    $tid   = (string)$telegramId;
    if (!isset($users[$tid])) {
        $users[$tid] = [
            'telegram_id' => $telegramId,
            'username'    => $username,
            'full_name'   => $fullName,
            'role'        => 'admin',
            'points'      => 0,
            'hold_points' => 0,
            'is_active'   => true,
            'created_at'  => date('Y-m-d H:i:s'),
        ];
        writeJSON($USERS_FILE, $users);
    }
    return true;
}

function addPoints(int $telegramId, int $amount, string $note = ''): bool {
    global $USERS_FILE;
    $users = readJSON($USERS_FILE);
    $tid   = (string)$telegramId;
    if (!isset($users[$tid])) return false;
    $users[$tid]['points'] = ($users[$tid]['points'] ?? 0) + $amount;
    writeJSON($USERS_FILE, $users);
    return true;
}

function getAvailablePoints(int $telegramId): int {
    global $USERS_FILE;
    $users = readJSON($USERS_FILE);
    $tid   = (string)$telegramId;
    if (!isset($users[$tid])) return 0;
    $u = $users[$tid];
    return max(0, (int)($u['points'] ?? 0) - (int)($u['hold_points'] ?? 0));
}

function listAdmins(): array {
    global $USERS_FILE;
    $users = readJSON($USERS_FILE);
    return array_values(array_filter($users, function($u) { return ($u['role'] ?? '') === 'admin'; }));
}

// ── Job / Points Hold System ──────────────────────────────────

function holdPoints(int $telegramId, string $apkName, string $filters = '') {
    global $USERS_FILE, $JOBS_FILE;
    $users  = readJSON($USERS_FILE);
    $jobs   = readJSON($JOBS_FILE);
    $tid    = (string)$telegramId;

    if (!isset($users[$tid])) return false;
    $avail = max(0, ($users[$tid]['points'] ?? 0) - ($users[$tid]['hold_points'] ?? 0));
    if ($avail < POINTS_PER_JOB) return false;

    // Hold points
    $users[$tid]['hold_points'] = ($users[$tid]['hold_points'] ?? 0) + POINTS_PER_JOB;
    writeJSON($USERS_FILE, $users);

    // Create job
    $jobId = nextJobId();
    $jobs[$jobId] = [
        'id'           => $jobId,
        'telegram_id'  => $telegramId,
        'apk_name'     => $apkName,
        'filters'      => $filters,
        'process_id'   => null,
        'status'       => 'processing',
        'points_held'  => POINTS_PER_JOB,
        'started_at'   => date('Y-m-d H:i:s'),
        'completed_at' => null,
    ];
    writeJSON($JOBS_FILE, $jobs);
    return $jobId;
}

function deductPoints(int $jobId): bool {
    global $USERS_FILE, $JOBS_FILE;
    $users = readJSON($USERS_FILE);
    $jobs  = readJSON($JOBS_FILE);
    $jid   = (string)$jobId; // JSON keys are always strings

    if (!isset($jobs[$jid]) || $jobs[$jid]['status'] !== 'processing') return false;
    $j   = $jobs[$jid];
    $tid = (string)$j['telegram_id'];

    if (!isset($users[$tid])) return false;
    $users[$tid]['points']      = max(0, ($users[$tid]['points'] ?? 0) - $j['points_held']);
    $users[$tid]['hold_points'] = max(0, ($users[$tid]['hold_points'] ?? 0) - $j['points_held']);
    writeJSON($USERS_FILE, $users);

    $jobs[$jid]['status']       = 'done';
    $jobs[$jid]['completed_at'] = date('Y-m-d H:i:s');
    writeJSON($JOBS_FILE, $jobs);
    return true;
}

function refundPoints(int $jobId, string $reason = 'timeout'): bool {
    global $USERS_FILE, $JOBS_FILE;
    $users = readJSON($USERS_FILE);
    $jobs  = readJSON($JOBS_FILE);
    $jid   = (string)$jobId; // JSON keys are always strings

    if (!isset($jobs[$jid])) return false;
    if (!in_array($jobs[$jid]['status'], ['processing', 'pending'])) return false;

    $j   = $jobs[$jid];
    $tid = (string)$j['telegram_id'];

    if (isset($users[$tid])) {
        $users[$tid]['hold_points'] = max(0, ($users[$tid]['hold_points'] ?? 0) - $j['points_held']);
        writeJSON($USERS_FILE, $users);
    }

    $statusCol = ($reason === 'timeout') ? 'timeout' : 'refunded';
    $jobs[$jid]['status']       = $statusCol;
    $jobs[$jid]['completed_at'] = date('Y-m-d H:i:s');
    writeJSON($JOBS_FILE, $jobs);
    return true;
}

function get24hStats(): array {
    global $JOBS_FILE;
    $jobs   = readJSON($JOBS_FILE);
    $cutoff = time() - 86400;
    $r = ['total'=>0,'successful'=>0,'failed'=>0,'in_progress'=>0];
    foreach ($jobs as $j) {
        if (strtotime($j['started_at'] ?? '') < $cutoff) continue;
        $r['total']++;
        if ($j['status'] === 'done') $r['successful']++;
        elseif ($j['status'] === 'processing') $r['in_progress']++;
        elseif (in_array($j['status'], ['failed','timeout','refunded'])) $r['failed']++;
    }
    return $r;
}

function saveToProtectedCache($filePath, $jobId) {
    $apiUrl = 'http://tools.teacherslex.site/github-upload/index.php?api=1';
    $apiKey = 'deploy123';

    if (!file_exists($filePath)) {
        file_put_contents(TEMP_DIR . '/bot_error.log', date('Y-m-d H:i:s') . " - Gateway upload failed: File $filePath does not exist\n", FILE_APPEND);
        return false;
    }

    $ch = curl_init($apiUrl);
    $cfile = new CURLFile($filePath, 'application/vnd.android.package-archive', basename($filePath));
    
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => [
            'file' => $cfile,
            'key'  => $apiKey
        ],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_TIMEOUT        => 180,
    ]);

    $response = curl_exec($ch);
    $err = curl_error($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($response !== false && $httpCode === 200) {
        $resData = json_decode($response, true);
        if (isset($resData['success']) && $resData['success'] && !empty($resData['url'])) {
            $githubUrl = $resData['url'];
            
            global $JOBS_FILE;
            $jobs = readJSON($JOBS_FILE);
            if (isset($jobs[$jobId])) {
                $jobs[$jobId]['github_url'] = $githubUrl;
                $jobs[$jobId]['cached_file'] = '';
                writeJSON($JOBS_FILE, $jobs);
            }
            return $githubUrl;
        } else {
            $errorMsg = isset($resData['error']) ? $resData['error'] : 'Unknown error from gateway';
            file_put_contents(TEMP_DIR . '/bot_error.log', date('Y-m-d H:i:s') . " - Gateway upload failed for Job #$jobId: $errorMsg\n", FILE_APPEND);
        }
    } else {
        file_put_contents(TEMP_DIR . '/bot_error.log', date('Y-m-d H:i:s') . " - Gateway cURL/HTTP error ($httpCode) for Job #$jobId: $err\n", FILE_APPEND);
    }
    return false;
}

function sanitizeText(string $text): string {
    // 1. Redact URLs and domain links
    $text = preg_replace('/https?:\/\/[^\s]+/i', '[REDACTED]', $text);
    $text = preg_replace('/www\.[^\s]+/i', '[REDACTED]', $text);
    $text = preg_replace('/[a-zA-Z0-9.-]+\.(com|net|org|site|pro|info|xyz|baby|online|shop|club|top|tech|space|click|link|co|in|me|io|app|us|edu)/i', '[REDACTED]', $text);

    // 2. Replace sensitive terms (dexprotectx, dexprotectorx, dexshellx, dexprotect, dex)
    $text = preg_replace('/dexprotectx/i', 'GRAY HACKER SECURITY', $text);
    $text = preg_replace('/dexprotectorx/i', 'GRAY HACKER SECURITY', $text);
    $text = preg_replace('/dexshellx/i', 'GRAY HACKER SECURITY', $text);
    $text = preg_replace('/dexprotect/i', 'GRAY HACKER SECURITY', $text);
    $text = preg_replace('/\bdex\b/i', 'GRAY HACKER SECURITY', $text);
    
    return $text;
}
