<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use App\Models\Contest;
use App\Models\User;
use App\Models\Ptc;
use App\Models\Link;
use App\Models\ContestHistory;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class CronController extends Controller
{
    public function updateCryptoPrices()
    {
        Artisan::call('crypto:update');

        $output = Artisan::output();
        
        return response()->json([
            'status' => 'success',
            'message' => 'Crypto prices update command executed.',
            'output' => $output
        ]);
    }
    public function daily()
    {
        $today = Carbon::today();
    
        User::where('today_earned', '>', 0)
            ->whereDate('updated_at', '<>', $today)
            ->update(['today_earned' => 0]);
    
        Ptc::where('today_views', '>', 0)
            ->whereDate('updated_at', '<>', $today)
            ->update(['today_views' => 0]);
    
        Link::where('today_views', '>', 0)
            ->whereDate('updated_at', '<>', $today)
            ->update(['today_views' => 0]);
    
        $this->processContest(1);
        sleep(2);
        $this->processContest(2);
    }
    private function processContest($contestId) {
        $contest = Contest::findOrFail($contestId);
    
        if (!$contest || !$contest->is_active || now()->lessThan($contest->end_date)) {
            return response()->json([
                'message' => 'Contest is still ongoing or already ended'
            ], 400);
        }
    
        $winners = User::where($contest->user_row, '>', 0)
            ->orderBy($contest->user_row, 'desc')
            ->limit(count(explode(',', $contest->rewards)))
            ->get();
    
        $rewards = explode(',', $contest->rewards);
    
        foreach ($winners as $index => $user) {
            if (isset($rewards[$index])) {
                $rank = $index + 1;
                $user->increment('balance', $rewards[$index]);
                $user->increment('total_earned', $rewards[$index]);
                create_notification(
                    "You ranked #{$rank} in the {$contest->name}!",
                    "You won: " . balanceAndSymbol($rewards[$index]) . ".",
                    'success',
                    $user->id
                );

                ContestHistory::create([
                    'user_id' => $user->id,
                    'username' => $user->name,
                    'contest_name' => $contest->name,
                    'rank' => $rank,
                    'reward' => $rewards[$index]
                ]);
            }
        }
    
        User::where($contest->user_row, '>', 0)->update([$contest->user_row => 0]);
    
        $newStartDate = now();
        switch ($contest->type) {
            case 'daily':
                $newEndDate = now()->addDay()->endOfDay();
                break;
            case 'weekly':
                $newEndDate = now()->next('Sunday')->endOfDay();
                break;
            case 'monthly':
                $newEndDate = now()->endOfMonth()->endOfDay();
                break;
            default:
                return response()->json(['message' => 'Invalid contest type'], 400);
        }
    
        $contest->update([
            'start_date' => $newStartDate,
            'end_date' => $newEndDate,
        ]);
    }
}