<?php
include_once __DIR__ . "/../db.php";

/**
 * Check if the requesting chat_id is the configured admin
 */
function isAdmin($chat_id) {
    global $config;
    $adminId = $config['admin_chat_id'] ?? null;
    return $adminId && (string)$chat_id === (string)$adminId;
}

/**
 * Route admin sub-commands: /admin stats | broadcast <msg> | user <id>
 */
function handleAdminCommand($chat_id, $text) {
    if (!isAdmin($chat_id)) {
        sendMessage($chat_id, "⛔ You are not authorised to use admin commands.");
        return;
    }

    $parts   = explode(' ', trim($text), 3);
    $sub     = strtolower($parts[1] ?? '');
    $payload = $parts[2] ?? '';

    switch ($sub) {
        case 'stats':
            handleAdminStats($chat_id);
            break;

        case 'broadcast':
            if (empty($payload)) {
                sendMessage($chat_id, "Usage: <code>/admin broadcast Your message here</code>");
                return;
            }
            handleAdminBroadcast($chat_id, $payload);
            break;

        case 'user':
            if (empty($payload) || !is_numeric($payload)) {
                sendMessage($chat_id, "Usage: <code>/admin user 123456789</code>");
                return;
            }
            handleAdminUser($chat_id, (int)$payload);
            break;

        case 'credits':
            // /admin credits <chat_id> <amount>
            $creditParts = explode(' ', trim($payload), 2);
            $targetId    = $creditParts[0] ?? '';
            $amount      = $creditParts[1] ?? '';
            if (!is_numeric($targetId) || !is_numeric($amount) || (int)$amount <= 0) {
                sendMessage($chat_id, "Usage: <code>/admin credits &lt;chat_id&gt; &lt;amount&gt;</code>\nExample: <code>/admin credits 123456789 20</code>");
                return;
            }
            handleAdminGrantCredits($chat_id, (int)$targetId, (int)$amount);
            break;

        case 'setprice':
            // /admin setprice diet|workout <amount>
            $priceParts = explode(' ', trim($payload), 2);
            $planType   = strtolower($priceParts[0] ?? '');
            $newPrice   = $priceParts[1] ?? '';
            if (!in_array($planType, ['diet', 'workout']) || !is_numeric($newPrice) || (int)$newPrice <= 0) {
                sendMessage($chat_id, "Usage: <code>/admin setprice diet|workout &lt;amount&gt;</code>\nExamples:\n<code>/admin setprice diet 10</code>\n<code>/admin setprice workout 20</code>");
                return;
            }
            $settingKey = ($planType === 'diet') ? 'diet_plan_cost' : 'workout_plan_cost';
            setSetting($settingKey, (int)$newPrice);
            sendMessage($chat_id, "✅ <b>" . ucfirst($planType) . " plan price</b> updated to <b>{$newPrice} credits</b>.");
            break;

        case 'setrate':
            // /admin setrate <rupees_per_credit>
            if (!is_numeric($payload) || (int)$payload <= 0) {
                sendMessage($chat_id, "Usage: <code>/admin setrate &lt;rupees_per_credit&gt;</code>\nExample: <code>/admin setrate 1</code>");
                return;
            }
            setSetting('rupee_per_credit', (int)$payload);
            sendMessage($chat_id, "✅ <b>Credit rate</b> updated to <b>₹{$payload} = 1 Credit</b>.");
            break;

        case 'settings':
            handleAdminSettings($chat_id);
            break;

        default:
            sendMessage($chat_id,
                "🛠️ <b>Admin Panel</b>\n\n" .

                "📊 <b>Analytics</b>\n" .
                "<code>/admin stats</code> — Total users, active users, plans generated, credits in circulation\n\n" .

                "👤 <b>User Management</b>\n" .
                "<code>/admin user &lt;chat_id&gt;</code> — View a user's full profile + quick-grant buttons\n" .
                "<code>/admin credits &lt;chat_id&gt; &lt;amount&gt;</code> — Manually grant credits to a user\n" .
                "<code>/admin broadcast &lt;msg&gt;</code> — Send a message to all registered users\n\n" .

                "💰 <b>Pricing &amp; Credits</b>\n" .
                "<code>/admin setprice diet &lt;n&gt;</code> — Set base credit cost for diet plans\n" .
                "<code>/admin setprice workout &lt;n&gt;</code> — Set base credit cost for workout plans\n" .
                "<code>/admin setrate &lt;n&gt;</code> — Set exchange rate (₹ per credit shown to users)\n\n" .

                "⚙️ <b>Settings</b>\n" .
                "<code>/admin settings</code> — View all current runtime settings"
            );
    }
}

/**
 * Show platform-wide statistics
 */
function handleAdminStats($chat_id) {
    global $pdo;

    $totalUsers  = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
    $totalDiets  = $pdo->query("SELECT COUNT(*) FROM diet_plans")->fetchColumn();
    $totalWorkouts = $pdo->query("SELECT COUNT(*) FROM workout_plans")->fetchColumn();
    $totalLogs   = $pdo->query("SELECT COUNT(*) FROM progress")->fetchColumn();

    $activeWeek  = $pdo->query("
        SELECT COUNT(DISTINCT chat_id) FROM (
            SELECT chat_id FROM diet_plans    WHERE created_at >= NOW() - INTERVAL 7 DAY
            UNION ALL
            SELECT chat_id FROM workout_plans WHERE created_at >= NOW() - INTERVAL 7 DAY
            UNION ALL
            SELECT chat_id FROM progress      WHERE logged_at  >= NOW() - INTERVAL 7 DAY
        ) t
    ")->fetchColumn();

    $newThisWeek = $pdo->query("
        SELECT COUNT(*) FROM users WHERE created_at >= NOW() - INTERVAL 7 DAY
    ")->fetchColumn();

    $totalCredits = $pdo->query("SELECT COALESCE(SUM(credits),0) FROM users")->fetchColumn();
    $creditsSpent = $pdo->query("SELECT COALESCE(ABS(SUM(amount)),0) FROM credit_transactions WHERE amount < 0")->fetchColumn();

    $msg  = "📊 <b>Platform Stats</b>\n\n";
    $msg .= "👥 Total Users: <b>{$totalUsers}</b> (+{$newThisWeek} this week)\n";
    $msg .= "🟢 Active (last 7 days): <b>{$activeWeek}</b>\n\n";
    $msg .= "🍽️ Diet Plans Generated: <b>{$totalDiets}</b>\n";
    $msg .= "💪 Workout Plans Generated: <b>{$totalWorkouts}</b>\n";
    $msg .= "📈 Weight Logs: <b>{$totalLogs}</b>\n\n";
    $msg .= "💳 Credits in circulation: <b>{$totalCredits}</b>\n";
    $msg .= "💸 Credits spent (all time): <b>{$creditsSpent}</b>\n";

    sendMessage($chat_id, $msg);
}

/**
 * Broadcast a message to all users
 */
function handleAdminBroadcast($admin_chat_id, $message) {
    global $pdo, $config;

    $stmt  = $pdo->query("SELECT chat_id FROM users");
    $users = $stmt->fetchAll(PDO::FETCH_COLUMN);
    $count = 0;
    $failed = 0;

    sendMessage($admin_chat_id, "📡 Broadcasting to " . count($users) . " users...");

    foreach ($users as $uid) {
        $url  = "https://api.telegram.org/bot{$config['telegram_token']}/sendMessage";
        $data = [
            "chat_id"    => $uid,
            "text"       => "📢 <b>Message from Admin:</b>\n\n" . $message,
            "parse_mode" => "HTML"
        ];
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS     => $data,
        ]);
        $resp   = curl_exec($ch);
        $result = json_decode($resp, true);
        if ($result['ok'] ?? false) {
            $count++;
        } else {
            $failed++;
        }
        usleep(50000); // 50ms between sends to respect rate limits
    }

    sendMessage($admin_chat_id, "✅ Broadcast complete.\n✔️ Sent: <b>{$count}</b> | ❌ Failed: <b>{$failed}</b>");
}

/**
 * Show a specific user's profile
 */
function handleAdminUser($chat_id, $target_id) {
    global $pdo;

    $stmt = $pdo->prepare("SELECT * FROM users WHERE chat_id = ?");
    $stmt->execute([$target_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        sendMessage($chat_id, "⚠️ No user found with chat_id <code>{$target_id}</code>.");
        return;
    }

    $dietCount = $pdo->prepare("SELECT COUNT(*) FROM diet_plans WHERE chat_id = ?");
    $dietCount->execute([$target_id]);

    $workoutCount = $pdo->prepare("SELECT COUNT(*) FROM workout_plans WHERE chat_id = ?");
    $workoutCount->execute([$target_id]);

    $lastLog = $pdo->prepare("SELECT weight, logged_at FROM progress WHERE chat_id = ? ORDER BY logged_at DESC LIMIT 1");
    $lastLog->execute([$target_id]);
    $log = $lastLog->fetch(PDO::FETCH_ASSOC);

    $msg  = "👤 <b>User Profile</b>\n";
    $msg .= "ID: <code>{$target_id}</code>\n";
    $msg .= "Name: <b>" . htmlspecialchars($user['first_name'] ?? 'N/A') . "</b>\n";
    $msg .= "Weight: {$user['weight']} kg | Height: {$user['height']} cm | Age: {$user['age']}\n";
    $msg .= "Gender: {$user['gender']} | Goal: {$user['goal']} | Diet: {$user['diet']}\n";
    $msg .= "BMI: {$user['bmi']} | BMR: {$user['bmr']} | TDEE: {$user['maintenance_calories']}\n";
    $msg .= "💳 Credits: <b>" . ($user['credits'] ?? 0) . "</b>\n\n";
    $msg .= "🍽️ Diet plans: <b>" . $dietCount->fetchColumn() . "</b>\n";
    $msg .= "💪 Workout plans: <b>" . $workoutCount->fetchColumn() . "</b>\n";
    if ($log) {
        $msg .= "📈 Last log: <b>{$log['weight']} kg</b> on {$log['logged_at']}\n";
    }

    $keyboard = [
        "inline_keyboard" => [[
            ["text" => "➕ Grant 10 Credits", "callback_data" => "admin_grant_{$target_id}_10"],
            ["text" => "➕ Grant 20 Credits", "callback_data" => "admin_grant_{$target_id}_20"],
        ]]
    ];

    sendMessage($chat_id, $msg, $keyboard);
}

/**
 * Display all current runtime settings.
 */
function handleAdminSettings($chat_id) {
    $keys = [
        'diet_plan_cost'    => 'Diet plan base price',
        'workout_plan_cost' => 'Workout plan base price',
        'rupee_per_credit'  => '₹ per credit',
        'signup_credits'    => 'Signup bonus credits',
    ];

    $msg = "⚙️ <b>Current Settings</b>\n\n";
    foreach ($keys as $key => $label) {
        $val  = getSetting($key, '(not set)');
        $msg .= "<b>{$label}:</b> <code>{$val}</code>\n";
    }
    $msg .= "\nUse <code>/admin setprice</code> or <code>/admin setrate</code> to update.";
    sendMessage($chat_id, $msg);
}

/**
 * Grant credits to a user (called from /admin credits command or quick-grant buttons).
 */
function handleAdminGrantCredits($admin_chat_id, $target_id, $amount) {
    global $pdo;

    $check = $pdo->prepare("SELECT first_name, credits FROM users WHERE chat_id = ?");
    $check->execute([$target_id]);
    $user = $check->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        sendMessage($admin_chat_id, "⚠️ No user found with chat_id <code>{$target_id}</code>.");
        return;
    }

    addCredits($target_id, $amount, 'admin_grant', "Granted by admin");
    $newBalance = $user['credits'] + $amount;

    $name = htmlspecialchars($user['first_name'] ?? "User #{$target_id}");
    sendMessage($admin_chat_id, "✅ Granted <b>{$amount} credits</b> to <b>{$name}</b>.\nNew balance: <b>{$newBalance} credits</b>");

    // Notify the user
    sendMessage($target_id,
        "🎉 <b>{$amount} credits</b> have been added to your account!\n" .
        "💳 New balance: <b>{$newBalance} credits</b>\n\n" .
        "Use /diet or /workout to generate your next plan."
    );
}
