<?php

namespace App\Http\Controllers\Game;

use App\Http\Controllers\Controller;
use App\Services\SuperballActivityService;
use Illuminate\Http\Request;

/**
 * Superball Activity API: recharge + turnover task, balls, lucky number, prize.
 * File encoding: UTF-8.
 */
class SuperballActivityController extends Controller
{
    protected SuperballActivityService $service;

    public function __construct(SuperballActivityService $service)
    {
        $this->service = $service;
    }

    /**
     * Get full activity info: yesterday data, today data, tiers, user task, multiplier.
     */
    public function info(Request $request)
    {
        $user = $request->user();
        $userId = $user ? (int) $user->UserID : 0;

        if ($userId <= 0) {
            return apiReturnFail(['web.activity.login_required', 'Please login first']);
        }

        try {
            $data = $this->service->getInfo($userId);
            return apiReturnSuc($data);
        } catch (\Throwable $e) {
            \Log::error('Superball info error', ['user_id' => $userId, 'error' => $e->getMessage()]);
            return apiReturnFail(['web.activity.error', $e->getMessage()]);
        }
    }

    /**
     * Select task tier for today (A-E). Requires confirm on front.
     */
    public function selectTier(Request $request)
    {
        $user = $request->user();
        if (!$user) {
            return apiReturnFail(['web.activity.login_required', 'Please login first']);
        }
        $userId = (int) $user->UserID;
        $tier = strtoupper(trim((string) $request->input('tier', '')));
        if (!in_array($tier, ['A', 'B', 'C', 'D', 'E'], true)) {
            return apiReturnFail(['web.superball.invalid_tier', 'Invalid tier']);
        }

        $result = $this->service->selectTier($userId, $tier);
        if (isset($result['success']) && $result['success'] === false) {
            return apiReturnFail($result['message']);
        }
        return apiReturnSuc(['message' => 'Tier selected']);
    }

    /**
     * Upgrade to higher tier (keep progress). Only when task completed and not A.
     */
    public function upgradeTier(Request $request)
    {
        $user = $request->user();
        if (!$user) {
            return apiReturnFail(['web.activity.login_required', 'Please login first']);
        }
        $userId = (int) $user->UserID;
        $newTier = strtoupper(trim((string) $request->input('tier', '')));
        if (!in_array($newTier, ['A', 'B', 'C', 'D', 'E'], true)) {
            return apiReturnFail(['web.superball.invalid_tier', 'Invalid tier']);
        }

        $result = $this->service->upgradeTier($userId, $newTier);
        //dd($result,isset($result['success']) && $result['success'] === false,$result['success'] === false);
        if (isset($result['success']) && $result['success'] === false) {
            return apiReturnFail($result['message']);
        }
        return apiReturnSuc(['message' => 'Tier upgraded']);
    }

    /**
     * Claim reward: grant balls, update daily, multiplier, mark task claimed.
     */
    public function claimReward(Request $request)
    {
        $user = $request->user();
        if (!$user) {
            return apiReturnFail(['web.activity.login_required', 'Please login first']);
        }
        $userId = (int) $user->UserID;

        $result = $this->service->claimReward($userId);
        if (isset($result['success']) && $result['success'] === false) {
            return apiReturnFail($result['message']);
        }
        return apiReturnSuc($result);
    }

    /**
     * Submit numbers for all balls (0-9 per ball). Array of numbers.
     */
    public function submitNumbers(Request $request)
    {
        $user = $request->user();
        if (!$user) {
            return apiReturnFail(['web.activity.login_required', 'Please login first']);
        }
        $userId = (int) $user->UserID;
        $numbers = $request->input('numbers', []);
        if (!is_array($numbers)) {
            $numbers = [];
        }

        $result = $this->service->submitNumbers($userId, $numbers);
        if (isset($result['success']) && $result['success'] === false) {
            return apiReturnFail($result['message']);
        }
        return apiReturnSuc(['message' => 'Numbers submitted']);
    }

    /**
     * Get my balls for a date (for number selection page or display). Default today.
     */
    public function getMyBalls(Request $request)
    {
        $user = $request->user();
        if (!$user) {
            return apiReturnFail(['web.activity.login_required', 'Please login first']);
        }
        $userId = (int) $user->UserID;
        $date = $request->input('date', date('Y-m-d'));

        try {
            $balls = $this->service->getMyBalls($userId, $date);
            return apiReturnSuc(['balls' => $balls]);
        } catch (\Throwable $e) {
            \Log::error('Superball getMyBalls error', ['user_id' => $userId, 'error' => $e->getMessage()]);
            return apiReturnFail(['web.superball.error', $e->getMessage()]);
        }
    }

    /**
     * Get last 7 days lucky numbers (for display).
     */
    public function luckyNumbers(Request $request)
    {
        try {
            $list = $this->service->getLast7DaysLuckyNumbers();
            return apiReturnSuc(['lucky_numbers' => $list]);
        } catch (\Throwable $e) {
            \Log::error('Superball luckyNumbers error', ['error' => $e->getMessage()]);
            return apiReturnFail(['web.superball.error', $e->getMessage()]);
        }
    }

    /**
     * Claim yesterday's reward (user claims next day, no auto distribution).
     */
    public function claimYesterdayReward(Request $request)
    {
        $user = $request->user();
        if (!$user) {
            return apiReturnFail(['web.activity.login_required', 'Please login first']);
        }
        $userId = (int) $user->UserID;

        $result = $this->service->claimYesterdayReward($userId);
        if (isset($result['success']) && $result['success'] === false) {
            return apiReturnFail($result['message']);
        }
        return apiReturnSuc($result);
    }
}
