<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class DailySpinController extends Controller
{
    public function __construct()
    {
        // Only require authentication for the spin action; allow guests to view the page
        $this->middleware('auth', ['only' => ['postSpin']]);
    }

    public function getIndex()
    {
        // Only perform user-specific checks if authenticated
        $user = Auth::user();
        $canSpin = false;
        $nextSpinTime = null;

        if (Auth::check()) {
            // Check if user has already spun today
            $lastSpin = DB::table('daily_spins')
                ->where('user_id', $user->ID)
                ->whereDate('created_at', '=', Carbon::today()->toDateString())
                ->first();

            $canSpin = !$lastSpin;
            $nextSpinTime = $lastSpin ? Carbon::parse($lastSpin->created_at)->addDay() : null;
        }

        // Get spin settings
        $settings = $this->getSpinSettings();

        // Generate preview items for the "already opened" state
        $previewItems = [
            ['reward' => $settings['daily_spin_max_reward'], 'rarity' => 'legendary'],
            ['reward' => intval($settings['daily_spin_max_reward'] * 0.8), 'rarity' => 'epic'],
            ['reward' => intval($settings['daily_spin_max_reward'] * 0.6), 'rarity' => 'rare'],
            ['reward' => intval($settings['daily_spin_max_reward'] * 0.4), 'rarity' => 'uncommon'],
            ['reward' => $settings['daily_spin_min_reward'], 'rarity' => 'common'],
            ['reward' => intval($settings['daily_spin_max_reward'] * 0.7), 'rarity' => 'rare'],
            ['reward' => intval($settings['daily_spin_max_reward'] * 0.5), 'rarity' => 'uncommon'],
            ['reward' => intval($settings['daily_spin_max_reward'] * 0.9), 'rarity' => 'epic']
        ];

        // Generate items for CS:GO case opening animation (100 items)
        $items = [];
        for($i = 0; $i < 100; $i++) {
            $reward = rand($settings['daily_spin_min_reward'], $settings['daily_spin_max_reward']);
            $rarity = 'common';
            if($reward >= $settings['daily_spin_max_reward'] * 0.8) $rarity = 'legendary';
            elseif($reward >= $settings['daily_spin_max_reward'] * 0.6) $rarity = 'epic';
            elseif($reward >= $settings['daily_spin_max_reward'] * 0.4) $rarity = 'rare';
            elseif($reward >= $settings['daily_spin_max_reward'] * 0.2) $rarity = 'uncommon';
            
            $items[] = ['reward' => $reward, 'rarity' => $rarity];
        }

        pagetitle(['Daily Spin', settings('server_name')]);
        
        return view('front.daily-spin.index', compact('canSpin', 'nextSpinTime', 'settings', 'previewItems', 'items'));
    }

    public function postSpin(Request $request)
    {
        $user = Auth::user();
        
        // Check if user has already spun today
        $lastSpin = DB::table('daily_spins')
            ->where('user_id', $user->ID)
            ->whereDate('created_at', '=', Carbon::today()->toDateString())
            ->first();

        if ($lastSpin) {
            return response()->json([
                'success' => false,
                'message' => 'You have already spun today! Come back tomorrow.'
            ]);
        }

        // Get spin settings
        $settings = $this->getSpinSettings();
        
        // Calculate random reward
        $minReward = (int) $settings['daily_spin_min_reward'];
        $maxReward = (int) $settings['daily_spin_max_reward'];
        $reward = rand($minReward, $maxReward);

        // Add currency to user
        DB::table('users')
            ->where('ID', $user->ID)
            ->increment('money', $reward);

        // Record the spin
        DB::table('daily_spins')->insert([
            'user_id' => $user->ID,
            'reward_amount' => $reward,
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now()
        ]);

        return response()->json([
            'success' => true,
            'reward' => $reward,
            'message' => "Congratulations! You won {$reward} " . settings('currency_name', 'coins') . "!"
        ]);
    }

    private function getSpinSettings()
    {
        return [
            'daily_spin_enabled' => settings('daily_spin_enabled', true),
            'daily_spin_min_reward' => settings('daily_spin_min_reward', 100),
            'daily_spin_max_reward' => settings('daily_spin_max_reward', 1000),
            'currency_name' => settings('currency_name', 'coins')
        ];
    }
}