<?php
require_once '../config.php';
require_once '../middleware.php';

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

// Get request method
$method = $_SERVER['REQUEST_METHOD'];

// Get admin token from headers
$admin_token = isset($_SERVER['HTTP_ADMIN_TOKEN']) ? $_SERVER['HTTP_ADMIN_TOKEN'] : '';

// Authenticate admin
authenticateAdmin($admin_token);

$conn = getDbConnection();

if ($method === 'GET') {
    // Get dashboard statistics
    $stats = [];
    
    // 1. User Statistics
    $stmt = $conn->prepare("SELECT 
        COUNT(*) as total_users,
        SUM(CASE WHEN is_blocked = 0 THEN 1 ELSE 0 END) as active_users,
        SUM(CASE WHEN is_blocked = 1 THEN 1 ELSE 0 END) as banned_users,
        SUM(coins) as total_coins_in_circulation
        FROM users");
    $stmt->execute();
    $result = $stmt->get_result();
    $user_stats = $result->fetch_assoc();
    $stats['users'] = [
        'total' => (int)$user_stats['total_users'],
        'active' => (int)$user_stats['active_users'],
        'banned' => (int)$user_stats['banned_users'],
        'total_coins_in_circulation' => (int)$user_stats['total_coins_in_circulation']
    ];
    
    // 2. Total coins disbursed (from promo codes and tasks)
    $stmt = $conn->prepare("SELECT 
        COALESCE(SUM(pc.coins * pcu.usage_count), 0) as promo_coins_disbursed
        FROM promo_codes pc
        LEFT JOIN (
            SELECT promo_code_id, COUNT(*) as usage_count 
            FROM promo_code_usage 
            GROUP BY promo_code_id
        ) pcu ON pc.id = pcu.promo_code_id");
    $stmt->execute();
    $result = $stmt->get_result();
    $promo_stats = $result->fetch_assoc();
    
    // Get coins from completed tasks
    $stmt = $conn->prepare("SELECT 
        COALESCE(SUM(earned_coins), 0) as task_coins_disbursed
        FROM task_completions");
    $stmt->execute();
    $result = $stmt->get_result();
    $task_stats = $result->fetch_assoc();
    
    $stats['coins'] = [
        'total_disbursed' => (int)($promo_stats['promo_coins_disbursed'] + $task_stats['task_coins_disbursed']),
        'promo_codes_disbursed' => (int)$promo_stats['promo_coins_disbursed'],
        'tasks_disbursed' => (int)$task_stats['task_coins_disbursed']
    ];
    
    // 3. Redeem Statistics
    $stmt = $conn->prepare("SELECT 
        COUNT(*) as total_requests,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_requests,
        SUM(CASE WHEN status = 'approved' THEN 1 ELSE 0 END) as approved_requests,
        SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected_requests
        FROM redeem_history");
    $stmt->execute();
    $result = $stmt->get_result();
    $redeem_stats = $result->fetch_assoc();
    $stats['redeem'] = [
        'total_requests' => (int)$redeem_stats['total_requests'],
        'pending' => (int)$redeem_stats['pending_requests'],
        'approved' => (int)$redeem_stats['approved_requests'],
        'rejected' => (int)$redeem_stats['rejected_requests']
    ];
    
    // 4. Task Statistics
    $stmt = $conn->prepare("SELECT 
        COUNT(*) as total_completions,
        COUNT(DISTINCT user_id) as unique_users_completed_tasks
        FROM task_completions");
    $stmt->execute();
    $result = $stmt->get_result();
    $task_completion_stats = $result->fetch_assoc();
    
    $stmt = $conn->prepare("SELECT 
        COUNT(*) as total_tasks
        FROM tasks");
    $stmt->execute();
    $result = $stmt->get_result();
    $task_stats = $result->fetch_assoc();
    
    $stmt = $conn->prepare("SELECT 
        COUNT(*) as total_questions
        FROM task_questions");
    $stmt->execute();
    $result = $stmt->get_result();
    $question_stats = $result->fetch_assoc();
    
    $stats['tasks'] = [
        'total_tasks' => (int)$task_stats['total_tasks'],
        'total_questions' => (int)$question_stats['total_questions'],
        'total_completions' => (int)$task_completion_stats['total_completions'],
        'unique_users_completed' => (int)$task_completion_stats['unique_users_completed_tasks']
    ];
    
    // 5. App Settings
    $stmt = $conn->prepare("SELECT 
        maintenance_mode,
        website_task_enabled,
        vpn_allowed,
        claim_timer,
        referrer_coins,
        referred_coins,
        earning_mode,
        gamezop_card_status,
        ad_app_size,
        gamezop_timer,
        ad_index
        FROM app_settings 
        ORDER BY id DESC 
        LIMIT 1");
    $stmt->execute();
    $result = $stmt->get_result();
    $settings = $result->fetch_assoc();
    
    if ($settings) {
        $stats['settings'] = [
            'maintenance_mode' => (bool)$settings['maintenance_mode'],
            'website_task_enabled' => (bool)$settings['website_task_enabled'],
            'vpn_allowed' => (bool)$settings['vpn_allowed'],
            'claim_timer' => (int)$settings['claim_timer'],
            'referrer_coins' => (int)$settings['referrer_coins'],
            'referred_coins' => (int)$settings['referred_coins'],
            'earning_mode' => (int)$settings['earning_mode'],
            'gamezop_card_status' => (int)$settings['gamezop_card_status'],
            'ad_app_size' => (int)$settings['ad_app_size'],
            'gamezop_timer' => (int)$settings['gamezop_timer'],
            'ad_index' => (int)$settings['ad_index'],
            'last_updated' => date('Y-m-d H:i:s')
        ];
    } else {
        // Default settings if none exist
        $stats['settings'] = [
            'maintenance_mode' => false,
            'website_task_enabled' => true,
            'vpn_allowed' => true,
            'claim_timer' => 3600,
            'referrer_coins' => 100,
            'referred_coins' => 50,
            'earning_mode' => 1,
            'gamezop_card_status' => 1,
            'ad_app_size' => 12,
            'gamezop_timer' => 10,
            'ad_index' => 0,
            'last_updated' => date('Y-m-d H:i:s')
        ];
    }
    // Remove these fields as top-level fields if present
    unset($stats['gamezop_card_status'], $stats['ad_app_size'], $stats['gamezop_timer'], $stats['ad_index'], $stats['earning_mode']);
    
    // Fetch ad_controls
    $stmt_adctrl = $conn->prepare("SELECT * FROM ad_controls");
    $stmt_adctrl->execute();
    $result_adctrl = $stmt_adctrl->get_result();
    $ad_controls = [];
    while ($row = $result_adctrl->fetch_assoc()) {
        $ad_controls[] = $row;
    }
    $stmt_adctrl->close();
    $stats['ad_controls'] = $ad_controls;
    
    // 6. Recent Activity (last 7 days)
    $stmt = $conn->prepare("SELECT 
        COUNT(*) as new_users_7_days
        FROM users 
        WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)");
    $stmt->execute();
    $result = $stmt->get_result();
    $recent_users = $result->fetch_assoc();
    
    $stmt = $conn->prepare("SELECT 
        COUNT(*) as new_redeem_requests_7_days
        FROM redeem_history 
        WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)");
    $stmt->execute();
    $result = $stmt->get_result();
    $recent_redeem = $result->fetch_assoc();
    
    $stats['recent_activity'] = [
        'new_users_7_days' => (int)$recent_users['new_users_7_days'],
        'new_redeem_requests_7_days' => (int)$recent_redeem['new_redeem_requests_7_days']
    ];
    
    // 7. System Info
    $stats['system'] = [
        'server_time' => date('Y-m-d H:i:s'),
        'php_version' => PHP_VERSION,
        'database_name' => DB_NAME
    ];
    
    $stmt->close();
    $conn->close();
    
    sendResponse(200, 'Dashboard data fetched', $stats);
    
} elseif ($method === 'POST') {
    // Handle toggle actions
    $encrypted_payload = file_get_contents('php://input');
    if (empty($encrypted_payload)) {
        sendResponse(400, 'Empty request body');
    }

    $data = decryptRequestPayload($encrypted_payload);
    if (!$data) {
        sendResponse(400, 'Invalid request body');
    }

    $action = $data['action'] ?? '';
    
    switch ($action) {
        case 'toggle_maintenance':
            $stmt = $conn->prepare("UPDATE app_settings SET 
                maintenance_mode = NOT maintenance_mode
                WHERE id = (SELECT id FROM (SELECT id FROM app_settings ORDER BY id DESC LIMIT 1) as temp)");
            $stmt->execute();
            
            if ($stmt->affected_rows === 0) {
                // Create new settings if none exist
                $stmt = $conn->prepare("INSERT INTO app_settings (maintenance_mode) VALUES (1)");
                $stmt->execute();
            }
            
            $stmt->close();
            sendResponse(200, 'Maintenance mode toggled');
            break;
            
        case 'set_maintenance':
            $maintenance_mode = isset($data['maintenance_mode']) ? (int)$data['maintenance_mode'] : null;
            if ($maintenance_mode === null) {
                sendResponse(400, 'maintenance_mode parameter is required (0 for off, 1 for on)');
            }
            
            $stmt = $conn->prepare("UPDATE app_settings SET 
                maintenance_mode = ?
                WHERE id = (SELECT id FROM (SELECT id FROM app_settings ORDER BY id DESC LIMIT 1) as temp)");
            $stmt->bind_param("i", $maintenance_mode);
            $stmt->execute();
            
            if ($stmt->affected_rows === 0) {
                // Create new settings if none exist
                $stmt = $conn->prepare("INSERT INTO app_settings (maintenance_mode) VALUES (?)");
                $stmt->bind_param("i", $maintenance_mode);
                $stmt->execute();
            }
            
            $stmt->close();
            $status = $maintenance_mode ? 'enabled' : 'disabled';
            sendResponse(200, "Maintenance mode {$status}");
            break;
            
        case 'set_maintenance_on':
            $on = isset($data['On']) ? (int)$data['On'] : null;
            if ($on === null) {
                sendResponse(400, 'On parameter is required (0 for off, 1 for on)');
            }
            
            $stmt = $conn->prepare("UPDATE app_settings SET 
                maintenance_mode = ?
                WHERE id = (SELECT id FROM (SELECT id FROM app_settings ORDER BY id DESC LIMIT 1) as temp)");
            $stmt->bind_param("i", $on);
            $stmt->execute();
            
            if ($stmt->affected_rows === 0) {
                // Create new settings if none exist
                $stmt = $conn->prepare("INSERT INTO app_settings (maintenance_mode) VALUES (?)");
                $stmt->bind_param("i", $on);
                $stmt->execute();
            }
            
            $stmt->close();
            $status = $on ? 'enabled' : 'disabled';
            sendResponse(200, "Maintenance mode {$status}");
            break;
            
        case 'toggle_website_task':
            $stmt = $conn->prepare("UPDATE app_settings SET 
                website_task_enabled = NOT website_task_enabled
                WHERE id = (SELECT id FROM (SELECT id FROM app_settings ORDER BY id DESC LIMIT 1) as temp)");
            $stmt->execute();
            
            if ($stmt->affected_rows === 0) {
                // Create new settings if none exist
                $stmt = $conn->prepare("INSERT INTO app_settings (website_task_enabled) VALUES (1)");
                $stmt->execute();
            }
            
            $stmt->close();
            sendResponse(200, 'Website task enabled toggled');
            break;
            
        case 'set_website_task':
            $website_task_enabled = isset($data['website_task_enabled']) ? (int)$data['website_task_enabled'] : null;
            if ($website_task_enabled === null) {
                sendResponse(400, 'website_task_enabled parameter is required (0 for off, 1 for on)');
            }
            
            $stmt = $conn->prepare("UPDATE app_settings SET 
                website_task_enabled = ?
                WHERE id = (SELECT id FROM (SELECT id FROM app_settings ORDER BY id DESC LIMIT 1) as temp)");
            $stmt->bind_param("i", $website_task_enabled);
            $stmt->execute();
            
            if ($stmt->affected_rows === 0) {
                // Create new settings if none exist
                $stmt = $conn->prepare("INSERT INTO app_settings (website_task_enabled) VALUES (?)");
                $stmt->bind_param("i", $website_task_enabled);
                $stmt->execute();
            }
            
            $stmt->close();
            $status = $website_task_enabled ? 'enabled' : 'disabled';
            sendResponse(200, "Website task {$status}");
            break;
            
        case 'set_website_task_on':
            $on = isset($data['On']) ? (int)$data['On'] : null;
            if ($on === null) {
                sendResponse(400, 'On parameter is required (0 for off, 1 for on)');
            }
            
            $stmt = $conn->prepare("UPDATE app_settings SET 
                website_task_enabled = ?
                WHERE id = (SELECT id FROM (SELECT id FROM app_settings ORDER BY id DESC LIMIT 1) as temp)");
            $stmt->bind_param("i", $on);
            $stmt->execute();
            
            if ($stmt->affected_rows === 0) {
                // Create new settings if none exist
                $stmt = $conn->prepare("INSERT INTO app_settings (website_task_enabled) VALUES (?)");
                $stmt->bind_param("i", $on);
                $stmt->execute();
            }
            
            $stmt->close();
            $status = $on ? 'enabled' : 'disabled';
            sendResponse(200, "Website task {$status}");
            break;
            
        case 'toggle_vpn_allowed':
            $stmt = $conn->prepare("UPDATE app_settings SET 
                vpn_allowed = NOT vpn_allowed
                WHERE id = (SELECT id FROM (SELECT id FROM app_settings ORDER BY id DESC LIMIT 1) as temp)");
            $stmt->execute();
            
            if ($stmt->affected_rows === 0) {
                // Create new settings if none exist
                $stmt = $conn->prepare("INSERT INTO app_settings (vpn_allowed) VALUES (1)");
                $stmt->execute();
            }
            
            $stmt->close();
            sendResponse(200, 'VPN allowed toggled');
            break;
            
        case 'set_vpn_allowed':
            $vpn_allowed = isset($data['vpn_allowed']) ? (int)$data['vpn_allowed'] : null;
            if ($vpn_allowed === null) {
                sendResponse(400, 'vpn_allowed parameter is required (0 for off, 1 for on)');
            }
            
            $stmt = $conn->prepare("UPDATE app_settings SET 
                vpn_allowed = ?
                WHERE id = (SELECT id FROM (SELECT id FROM app_settings ORDER BY id DESC LIMIT 1) as temp)");
            $stmt->bind_param("i", $vpn_allowed);
            $stmt->execute();
            
            if ($stmt->affected_rows === 0) {
                // Create new settings if none exist
                $stmt = $conn->prepare("INSERT INTO app_settings (vpn_allowed) VALUES (?)");
                $stmt->bind_param("i", $vpn_allowed);
                $stmt->execute();
            }
            
            $stmt->close();
            $status = $vpn_allowed ? 'enabled' : 'disabled';
            sendResponse(200, "VPN access {$status}");
            break;
            
        case 'set_vpn_allowed_on':
            $on = isset($data['On']) ? (int)$data['On'] : null;
            if ($on === null) {
                sendResponse(400, 'On parameter is required (0 for off, 1 for on)');
            }
            
            $stmt = $conn->prepare("UPDATE app_settings SET 
                vpn_allowed = ?
                WHERE id = (SELECT id FROM (SELECT id FROM app_settings ORDER BY id DESC LIMIT 1) as temp)");
            $stmt->bind_param("i", $on);
            $stmt->execute();
            
            if ($stmt->affected_rows === 0) {
                // Create new settings if none exist
                $stmt = $conn->prepare("INSERT INTO app_settings (vpn_allowed) VALUES (?)");
                $stmt->bind_param("i", $on);
                $stmt->execute();
            }
            
            $stmt->close();
            $status = $on ? 'enabled' : 'disabled';
            sendResponse(200, "VPN access {$status}");
            break;
            
        case 'update_settings':
            // Update multiple settings at once
            $maintenance_mode = isset($data['maintenance_mode']) ? (int)$data['maintenance_mode'] : null;
            $website_task_enabled = isset($data['website_task_enabled']) ? (int)$data['website_task_enabled'] : null;
            $vpn_allowed = isset($data['vpn_allowed']) ? (int)$data['vpn_allowed'] : null;
            $claim_timer = isset($data['claim_timer']) ? (int)$data['claim_timer'] : null;
            $referrer_coins = isset($data['referrer_coins']) ? (int)$data['referrer_coins'] : null;
            $referred_coins = isset($data['referred_coins']) ? (int)$data['referred_coins'] : null;
            
            $updates = [];
            $params = [];
            $types = '';
            
            if ($maintenance_mode !== null) {
                $updates[] = "maintenance_mode = ?";
                $params[] = $maintenance_mode;
                $types .= 'i';
            }
            if ($website_task_enabled !== null) {
                $updates[] = "website_task_enabled = ?";
                $params[] = $website_task_enabled;
                $types .= 'i';
            }
            if ($vpn_allowed !== null) {
                $updates[] = "vpn_allowed = ?";
                $params[] = $vpn_allowed;
                $types .= 'i';
            }
            if ($claim_timer !== null) {
                $updates[] = "claim_timer = ?";
                $params[] = $claim_timer;
                $types .= 'i';
            }
            if ($referrer_coins !== null) {
                $updates[] = "referrer_coins = ?";
                $params[] = $referrer_coins;
                $types .= 'i';
            }
            if ($referred_coins !== null) {
                $updates[] = "referred_coins = ?";
                $params[] = $referred_coins;
                $types .= 'i';
            }
            
            if (empty($updates)) {
                sendResponse(400, 'No settings to update');
            }
            
            $sql = "UPDATE app_settings SET " . implode(', ', $updates) . " WHERE id = (SELECT id FROM (SELECT id FROM app_settings ORDER BY id DESC LIMIT 1) as temp)";
            
            $stmt = $conn->prepare($sql);
            if ($types) {
                $stmt->bind_param($types, ...$params);
            }
            $stmt->execute();
            
            if ($stmt->affected_rows === 0) {
                // Create new settings if none exist
                $stmt = $conn->prepare("INSERT INTO app_settings (maintenance_mode, website_task_enabled, vpn_allowed, claim_timer, referrer_coins, referred_coins) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->bind_param("iiiiii", 
                    $maintenance_mode ?? 0,
                    $website_task_enabled ?? 1,
                    $vpn_allowed ?? 1,
                    $claim_timer ?? 3600,
                    $referrer_coins ?? 100,
                    $referred_coins ?? 50
                );
                $stmt->execute();
            }
            
            $stmt->close();
            sendResponse(200, 'Settings updated successfully');
            break;
            
        default:
            sendResponse(400, 'Invalid action');
            break;
    }
    
} else {
    sendResponse(405, 'Method not allowed');
}

$conn->close();
?> 