<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\GameDetail;
use App\Models\WinningNumber;
use Illuminate\Http\Request;

class WinningController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:admin');
    }

    public function list($id)  {
        $game = GameDetail::findOrfail($id);
        $winningNumberList = WinningNumber::where('game_id', $game->id)->get();
        return view('admin.winnigs_management.list', compact('game','winningNumberList'));
    }

    public function store(Request $request)
    {
        // Validate the form data
        $validatedData = $request->validate([
            'game_id' => 'required|exists:game_details,id',
            'winning_number' => 'required|array',
            'winning_number.*' => 'required',
            'winning_sequence' => 'required|array',
            'winning_sequence.*' => 'required',
        ]);

        // Store the winning numbers in the database
        foreach ($validatedData['winning_number'] as $index => $winningNumber) {
            WinningNumber::create([
                'game_id' => $validatedData['game_id'],
                'number' => $winningNumber,
                'sequence' => $validatedData['winning_sequence'][$index],
            ]);
        }

       // Redirect to the edit page with the game ID
       return redirect()->route('admin.winning.list', $validatedData['game_id'])
    ->with('success', 'Winning numbers have been stored successfully.');

    }

    public function edit($id)
    {
        // Retrieve the game and its associated winning numbers
        $game = GameDetail::findOrFail($id);
        $winningNumbers = WinningNumber::findOrFail($game->id);

        return view('admin.winnigs_management.edit_list', compact('game', 'winningNumbers'));
    }

    public function deleteRecord(Request $request)
    {

        // return response()->json(
        //     ['success' => true, 
        //     'message' => $request->all()
        // ]);
// die;
        $recordId = $request->input('id');

        // Perform validation or any other checks here if needed

        // Find the record
        $record = WinningNumber::find($recordId);
        // dd($record);

        if (!$record) {
            return response()->json(['success' => false, 'message' => 'Record not found.']);
        }

        // Perform the deletion
        $record->delete();

        return response()->json(['success' => true, 'message' => 'Record deleted successfully.']);
    }
}
