<?php
  
namespace App\Http\Controllers\Admin;
  
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreBoardPatternRequest;
use App\Http\Requests\Admin\StoreCompetitionAssignmentRequest;
use App\Http\Requests\Admin\StoreContestRequest;
use App\Http\Requests\Admin\StoreMathChapterRequest;
use App\Http\Requests\Admin\StoreQuestionRequest;
use App\Http\Requests\Admin\StoreQuestionSetRequest;
use App\Http\Requests\Admin\StoreStudentGroupRequest;
use App\Http\Requests\Admin\StoreStudentSubjectRequest;
use App\Http\Requests\Admin\UpdateBoardPatternRequest;
use App\Http\Requests\Admin\UpdateCompetitionAssignmentRequest;
use App\Http\Requests\Admin\UpdateContestRequest;
use App\Http\Requests\Admin\UpdateMathChapterRequest;
use App\Http\Requests\Admin\UpdateQuestionRequest;
use App\Http\Requests\Admin\UpdateQuestionSetRequest;
use App\Http\Requests\Admin\UpdateSiteDetailRequest;
use App\Http\Requests\Admin\UpdateStudentGroupRequest;
use App\Http\Requests\Admin\UpdateStudentSubjectRequest;
use App\Models\Attachment;
use App\Models\BoardPattern;
use App\Models\CompetitionAssignment;
use App\Models\GameplayHistory;
use App\Models\MatchContest;
use App\Models\MathChapter;
use App\Models\QuestionManagement;
use App\Models\QuestionSetup;
use App\Models\SiteDetail;
use App\Models\StudentGroup;
use App\Models\StudentSubject;
use App\Support\LegacyJson;
use App\Models\UserAnswerDetail;
use App\Models\WalletUser;
use App\Models\WinningHistory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Session;
use Illuminate\Support\Facades\Redirect;
use App\Models\User;

use Hash;
use DB; 
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Str;
  
class TournamentController extends Controller
{
    private const MATH_SUBJECT_ID = 5;

    private function guestRedirect(): RedirectResponse
    {
        return redirect()->route('admin.logindata')
            ->with('message', 'Please login to continue.');
    }

    private function resolveAttachmentUrl(?int $attachmentId, string $fallbackUrl): string
    {
        if ((int) $attachmentId <= 0) {
            return $fallbackUrl;
        }

        $attachment = Attachment::query()->find($attachmentId);

        return $attachment ? ASSETURL.'files/'.$attachment->att_url : $fallbackUrl;
    }

    private function defaultPortalImageUrl(): string
    {
        return asset('public/frontend/images/logo.png');
    }

    private function defaultSiteLogoUrl(): string
    {
        return asset('public/newlogo.jpg');
    }

    private function buildLegacySlug(string $value): string
    {
        return Str::slug($value);
    }

    private function normalizeRechargeAmountConfig(string $value): string
    {
        return collect(explode(',', $value))
            ->map(fn ($amount) => trim((string) $amount))
            ->filter(fn ($amount) => $amount !== '' && is_numeric($amount) && (float) $amount > 0)
            ->map(function ($amount) {
                $normalized = number_format((float) $amount, 2, '.', '');

                return rtrim(rtrim($normalized, '0'), '.');
            })
            ->unique()
            ->values()
            ->implode(',');
    }

    private function parseCompoundValue(?string $value): array
    {
        if (! $value || ! str_contains($value, '<=>')) {
            return ['id' => null, 'name' => ''];
        }

        [$id, $name] = explode('<=>', $value, 2);

        return [
            'id' => $id !== '' ? (int) $id : null,
            'name' => $name ?? '',
        ];
    }

    private function normalizeContestType(?string $contestType): string
    {
        return $contestType === MatchContest::TYPE_FREE
            ? MatchContest::TYPE_FREE
            : MatchContest::TYPE_PAID;
    }

    private function contestModuleConfig(string $contestType): array
    {
        if ($contestType === MatchContest::TYPE_FREE) {
            return [
                'contest_type' => MatchContest::TYPE_FREE,
                'contest_type_label' => 'Free Exam',
                'module_title' => 'Manage Free Exams',
                'module_note' => 'Free exams stay separate from paid competitions. Scholarship rule: daily class-wise top 3, then final top 10 overall.',
                'add_route_name' => 'admin.addfreecontest',
                'manage_route_name' => 'admin.managefreecontest',
                'save_route_name' => 'admin.savefreecontest',
                'edit_route_name' => 'admin.editfreecontest',
                'update_route_name' => 'admin.updatefreecontest',
                'assign_route_name' => 'admin.freeassigncompetition',
                'assign_add_route_name' => 'admin.addfreeassigncompetition',
                'assign_edit_route_name' => 'admin.editfreeassigncompetition',
                'assign_save_route_name' => 'admin.savefreeassigncompetition',
                'assign_update_route_name' => 'admin.updatefreeassigncompetition',
                'create_title' => 'Add Free Exam',
                'edit_title' => 'Edit Free Exam',
                'hero_create_title' => 'Create Free Exam',
                'hero_edit_title' => 'Update Free Exam',
                'hero_create_description' => 'Create zero-fee scholarship exams separately from paid competitions. Final scholarships will follow the daily class-wise top 3 rule.',
                'hero_edit_description' => 'Update free exam settings without mixing them with paid competition rewards.',
                'assignment_title' => 'Manage Free Exam Assignments',
                'assignment_note' => 'Assign free exams class-wise and date-wise. Daily scholarship logic will use the assigned class/date combination.',
                'assignment_add_title' => 'Add Free Exam Assignment',
                'assignment_edit_title' => 'Edit Free Exam Assignment',
                'assignment_hero_create' => 'Map a free exam to class group, board pattern and question sets for the selected date.',
                'assignment_hero_edit' => 'Update a free exam assignment while keeping scholarship grouping ready by date and class.',
            ];
        }

        return [
            'contest_type' => MatchContest::TYPE_PAID,
            'contest_type_label' => 'Paid Competition',
            'module_title' => 'Manage Competition',
            'module_note' => 'From here you can create paid contests, update reward slabs, remove unused contests and inspect joined students.',
            'add_route_name' => 'admin.addcontest',
            'manage_route_name' => 'admin.managecontest',
            'save_route_name' => 'admin.savecontest',
            'edit_route_name' => 'admin.editcontest',
            'update_route_name' => 'admin.updatecontest',
            'assign_route_name' => 'admin.assigncompetition',
            'assign_add_route_name' => 'admin.addassigncompetition',
            'assign_edit_route_name' => 'admin.editassigncompetition',
            'assign_save_route_name' => 'admin.saveassigncompetition',
            'assign_update_route_name' => 'admin.updateassigncompetition',
            'create_title' => 'Add Competition',
            'edit_title' => 'Edit Competition',
            'hero_create_title' => 'Create New Competition',
            'hero_edit_title' => 'Update Competition',
            'hero_create_description' => 'Set up a fresh competition with prize pool, seat limit, join amount and rank-based rewards.',
            'hero_edit_description' => 'Edit competition rules, seat allocation and reward ranges without changing the existing route flow.',
            'assignment_title' => 'Manage Assign Competitions',
            'assignment_note' => 'Use filter to quickly inspect assignments for one class group.',
            'assignment_add_title' => 'Add Assignment',
            'assignment_edit_title' => 'Edit Assignment',
            'assignment_hero_create' => 'Map competition, class group, board pattern and question sets into one scheduled exam assignment.',
            'assignment_hero_edit' => 'Edit the linked class group, question sets, competition and full assignment schedule from one screen.',
        ];
    }

    private function contestQueryByType(string $contestType)
    {
        return MatchContest::query()->ofType($this->normalizeContestType($contestType));
    }

    private function assignmentQueryByContestType(string $contestType)
    {
        return CompetitionAssignment::query()->whereHas(
            'contest',
            fn ($query) => $query->ofType($this->normalizeContestType($contestType))
        );
    }

    private function buildContestPayload(array $validated, bool $isUpdate = false): array
    {
        $contestType = $this->normalizeContestType($validated['contest_type'] ?? null);
        $payload = [
            'contest_type' => $contestType,
            'contesttitile' => $validated['matchesname'],
            'totalamount' => $validated['prizetottalamount'],
            'contestseat' => $validated['totalseat'],
            'winpertange' => $validated['winpertantage'],
            'userentery' => $validated['userenrery'],
            'contestprizeamt' => implode(',', $validated['prizedetail']),
            'conteststartseat' => implode(',', $validated['prizestratseat']),
            'contestendseat' => implode(',', $validated['prizeendseat']),
        ];

        if ($contestType === MatchContest::TYPE_FREE) {
            $payload['joinamt'] = 0;
        } else {
            $payload['joinamt'] = $validated['joinprice'];
        }

        if ($isUpdate) {
            $payload['updatetime'] = now();
        } else {
            $payload['createdby'] = Auth::id();
            $payload['createdtime'] = now();
        }

        return $payload;
    }

    private function parseContestCsv(?string $value): array
    {
        if (! $value) {
            return [];
        }

        return array_values(array_filter(explode(',', $value), static fn ($item) => $item !== ''));
    }

    private function buildContestPrizeRows(array $amounts, array $starts, array $ends): array
    {
        $rowCount = max(count($amounts), count($starts), count($ends), 1);
        $rows = [];

        for ($index = 0; $index < $rowCount; $index++) {
            $rows[] = [
                'amount' => $amounts[$index] ?? '',
                'start' => $starts[$index] ?? '',
                'end' => $ends[$index] ?? '',
            ];
        }

        return $rows;
    }

    private function buildQuestionPayload(array $validated): array
    {
        $subject = $this->parseCompoundValue($validated['questionsubject']);
        $group = $this->parseCompoundValue($validated['questiongoupsclass']);
        $chapterName = $this->normalizeQuestionChapterName($validated['questionchapter'] ?? null);

        return [
            'questionstitle' => $validated['questiontitle'],
            'questiongroupname' => $group['name'],
            'questiongroupid' => $group['id'],
            'questionsubjectname' => $subject['name'],
            'questionsubjectid' => $subject['id'],
            'questionchaptername' => $chapterName,
            'questionlist' => array_values($validated['questionsection']),
            'questionhindi' => array_values($validated['questionsectionhndi']),
            'questionobjectfirst' => array_values($validated['questionsectionobjectfirst']),
            'questionobjectsecond' => array_values($validated['questionsectionseond']),
            'questionobjectthird' => array_values($validated['questionsectionthird']),
            'questionobjectfourth' => array_values($validated['questionsectionfouth']),
            'questionobjectfirsthindi' => array_values($validated['questionsectionobjectfirsthindi']),
            'questionobjectsecondhindi' => array_values($validated['questionsectionseondhindi']),
            'questionobjectthirdhindi' => array_values($validated['questionsectionthirdhindi']),
            'questionobjectfourthhindi' => array_values($validated['questionsectionfouthhindi']),
            'questionobjectanswer' => array_values($validated['questionobjectanswer']),
        ];
    }

    private function questionFormOptions(): array
    {
        return [
            'studentsgroup' => StudentGroup::query()->orderByDesc('id')->get(),
            'sudentsubject' => StudentSubject::query()->orderByDesc('id')->get(),
            'mathSubjectId' => self::MATH_SUBJECT_ID,
            'mathchapters' => MathChapter::query()
                ->orderBy('classgroupname')
                ->orderBy('subjectname')
                ->orderBy('chapterorder')
                ->orderBy('chaptername')
                ->get(),
        ];
    }

    private function questionSetSubjectDefinitions(): array
    {
        return [
            'gk' => [
                'subject_id' => 1,
                'title' => 'Questions Set G.K.',
                'search_placeholder' => 'Search Questions Set G.K.',
                'input_name' => 'questionsetgk',
                'route' => route('admin.loadquestions'),
            ],
            'science' => [
                'subject_id' => 2,
                'title' => 'Questions Set Science',
                'search_placeholder' => 'Search Questions Set Science.',
                'input_name' => 'questionsetnscince',
                'route' => route('admin.loadquestionscince'),
            ],
            'hindi' => [
                'subject_id' => 4,
                'title' => 'Questions Set Hindi',
                'search_placeholder' => 'Search Questions Set Hindi.',
                'input_name' => 'questionsetnhindi',
                'route' => route('admin.loadquestionhindi'),
            ],
            'english' => [
                'subject_id' => 3,
                'title' => 'Questions Set English',
                'search_placeholder' => 'Search Questions Set English.',
                'input_name' => 'questionsetenglish',
                'route' => route('admin.loadquestionenglish'),
            ],
            'maths' => [
                'subject_id' => 5,
                'title' => 'Questions Set Mathematics',
                'search_placeholder' => 'Search Questions Set Mathematics.',
                'input_name' => 'questionsetmath',
                'route' => route('admin.loadquestionmaths'),
            ],
        ];
    }

    private function questionOptionsBySubjectAndClass(int $subjectId, int $classId)
    {
        $query = QuestionManagement::query()
            ->where('questionsubjectid', $subjectId)
            ->where('questiongroupid', $classId);

        $query
            ->orderByRaw("CASE WHEN questionchaptername IS NULL OR questionchaptername = '' THEN 1 ELSE 0 END")
            ->orderBy('questionchaptername');

        return $query
            ->orderByDesc('id')
            ->get();
    }

    private function isMathSubjectId(?int $subjectId): bool
    {
        return (int) $subjectId === self::MATH_SUBJECT_ID;
    }

    private function normalizeQuestionChapterName(?string $value): ?string
    {
        $chapterName = trim((string) $value);

        return $chapterName !== '' ? $chapterName : null;
    }

    private function questionSetPanelData(int $classId = 0): array
    {
        $panels = [];

        foreach ($this->questionSetSubjectDefinitions() as $panelKey => $definition) {
            $panels[$panelKey] = array_merge(
                $definition,
                [
                    'questions' => $classId > 0
                        ? $this->questionOptionsBySubjectAndClass($definition['subject_id'], $classId)
                        : collect(),
                ]
            );
        }

        return $panels;
    }

    private function buildQuestionSetPayload(array $validated, ?QuestionSetup $existing = null): array
    {
        $group = isset($validated['questiongoupsclass'])
            ? $this->parseCompoundValue($validated['questiongoupsclass'])
            : ['id' => $existing?->questionsetclassid, 'name' => $existing?->questionsetclassname ?? ''];
        $gk = $this->parseCompoundValue($validated['questionsetgk']);
        $science = $this->parseCompoundValue($validated['questionsetnscince']);
        $hindi = $this->parseCompoundValue($validated['questionsetnhindi']);
        $english = $this->parseCompoundValue($validated['questionsetenglish']);
        $maths = $this->parseCompoundValue($validated['questionsetmath']);

        return [
            'questionsettitle' => $validated['questiontitle'],
            'questionsetclassname' => $group['name'],
            'questionsetclassid' => $group['id'],
            'questionsetgkid' => $gk['id'],
            'questionsetgktitle' => $gk['name'],
            'questionsetscienceid' => $science['id'],
            'questionsetsciencetittle' => $science['name'],
            'questionsethindiid' => $hindi['id'],
            'questionsethindititle' => $hindi['name'],
            'questionsetenglishid' => $english['id'],
            'questionsetenglishtitle' => $english['name'],
            'questionsetmathsid' => $maths['id'],
            'questionsetmathstitle' => $maths['name'],
        ];
    }

    private function buildCompetitionAssignmentPayload(array $validated): array
    {
        $group = $this->parseCompoundValue($validated['questiongoupsclass']);
        $competition = $this->parseCompoundValue($validated['questioncompetition']);
        $board = $this->parseCompoundValue($validated['questionboard']);

        $questionSetIds = [];
        $questionSetNames = [];
        foreach ($validated['questionset'] as $questionSet) {
            $parsedSet = $this->parseCompoundValue($questionSet);
            if ($parsedSet['id']) {
                $questionSetIds[] = $parsedSet['id'];
                $questionSetNames[] = $parsedSet['name'];
            }
        }

        return [
            'compitetiontitle' => $validated['questiontitle'],
            'groupclassname' => $group['name'],
            'groupclassid' => $group['id'],
            'compitetionid' => $competition['id'],
            'compitetionname' => $competition['name'],
            'questionsetid' => implode(',', $questionSetIds),
            'questiomnsetname' => implode(',', $questionSetNames),
            'startdate' => $validated['startdate'],
            'enddate' => $validated['enddate'],
            'examdate' => $validated['examdate'],
            'resultdate' => $validated['resultdate'],
            'examendtime' => $validated['examtimeing'],
            'boardpatternid' => $board['id'],
            'boardpatternname' => $board['name'],
            'answersheetdate' => $validated['answersheetdate'],
        ];
    }

    private function assignmentFormOptions(string $contestType = MatchContest::TYPE_PAID): array
    {
        return [
            'studentsgroup' => StudentGroup::query()->orderByDesc('id')->get(),
            'questionsetup' => QuestionSetup::query()->orderByDesc('id')->get(),
            'boardpattern' => BoardPattern::query()->orderByDesc('id')->get(),
            'matchcobntests' => $this->contestQueryByType($contestType)->orderByDesc('id')->get(),
        ];
    }

    private function buildStudentGroupPayload(array $validated, bool $isUpdate = false): array
    {
        $payload = [
            'studentsgroupname' => $validated['pagename'],
            'groupslug' => $this->buildLegacySlug($validated['pagename']),
            'grouporder' => $validated['pageorder'] ?? null,
            'groupimg' => $validated['photoid'] ?? null,
        ];

        if (! $isUpdate) {
            $payload['createdby'] = Auth::id();
            $payload['createdtime'] = now();
        }

        return $payload;
    }

    private function buildStudentSubjectPayload(array $validated, bool $isUpdate = false): array
    {
        $payload = [
            'subjectname' => $validated['pagename'],
            'subjectslug' => $this->buildLegacySlug($validated['pagename']),
            'subjectorder' => $validated['pageorder'] ?? null,
            'subjectimg' => $validated['photoid'] ?? null,
        ];

        if (! $isUpdate) {
            $payload['createdby'] = Auth::id();
            $payload['createdtime'] = now();
        }

        return $payload;
    }

    private function buildBoardPatternPayload(array $validated, bool $isUpdate = false): array
    {
        $payload = [
            'boardname' => $validated['pagename'],
            'showname' => $validated['pageorder'] ?? null,
            'boardimg' => $validated['photoid'] ?? null,
        ];

        if (! $isUpdate) {
            $payload['createdby'] = Auth::id();
            $payload['createdtime'] = now();
        }

        return $payload;
    }

    private function buildMathChapterPayload(array $validated, bool $isUpdate = false): array
    {
        $group = $this->parseCompoundValue($validated['classgroup']);
        $subject = $this->parseCompoundValue($validated['subject']);

        $payload = [
            'chaptername' => $validated['chaptername'],
            'chapterslug' => $this->buildLegacySlug($validated['chaptername']),
            'chapterorder' => $validated['chapterorder'] ?? null,
            'classgroupid' => $group['id'],
            'classgroupname' => $group['name'],
            'subjectid' => $subject['id'],
            'subjectname' => $subject['name'],
            'status' => 1,
        ];

        if (! $isUpdate) {
            $payload['createdby'] = Auth::id();
            $payload['createdtime'] = now();
        }

        return $payload;
    }

 

         //////////////////
        //// Competition Management
        ////////////////


        public function managecontest(): View|RedirectResponse
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }           

            $moduleConfig = $this->contestModuleConfig(MatchContest::TYPE_PAID);
            $matchcobntests = $this->contestQueryByType(MatchContest::TYPE_PAID)
                ->withCount(['gameplayEntries as joined_count'])
                ->orderByDesc('id')
                ->get();

            return view('admin.contest.managecontest', array_merge($moduleConfig, [
                'matchcobntests' => $matchcobntests,
            ]));
        } 

        public function managefreecontest(): View|RedirectResponse
        {
            if (!Auth::check()) {
                return $this->guestRedirect();
            }

            $moduleConfig = $this->contestModuleConfig(MatchContest::TYPE_FREE);
            $matchcobntests = $this->contestQueryByType(MatchContest::TYPE_FREE)
                ->withCount(['gameplayEntries as joined_count'])
                ->orderByDesc('id')
                ->get();

            return view('admin.contest.managecontest', array_merge($moduleConfig, [
                'matchcobntests' => $matchcobntests,
            ]));
        }
    
        public function addcontest(): View|RedirectResponse
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }           

            return view('admin.contest.addcontest', $this->contestModuleConfig(MatchContest::TYPE_PAID));
        } 

        public function addfreecontest(): View|RedirectResponse
        {
            if (!Auth::check()) {
                return $this->guestRedirect();
            }

            return view('admin.contest.addcontest', $this->contestModuleConfig(MatchContest::TYPE_FREE));
        }

        

        public function savecontest(StoreContestRequest $request): RedirectResponse
        {
            if (!Auth::check()) {
                return $this->guestRedirect();
            }

            MatchContest::query()->create($this->buildContestPayload($request->validated()));
     
            
            Session::flash('sucmessage', "Successful, Match Contest  has Added"); 
             
            return Redirect::back(); 
        } 

        public function savefreecontest(StoreContestRequest $request): RedirectResponse
        {
            if (!Auth::check()) {
                return $this->guestRedirect();
            }

            MatchContest::query()->create($this->buildContestPayload($request->validated()));

            Session::flash('sucmessage', "Successful, Free Exam has Added");

            return Redirect::back();
        }

        public function editcontest(int $id): View|RedirectResponse
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }   
     
              $matchcobntests = $this->contestQueryByType(MatchContest::TYPE_PAID)
                  ->withCount(['gameplayEntries as joined_count'])
                  ->findOrFail($id);
              $contestPrizeAmounts = $this->parseContestCsv($matchcobntests->contestprizeamt);
              $contestStartSeats = $this->parseContestCsv($matchcobntests->conteststartseat);
              $contestEndSeats = $this->parseContestCsv($matchcobntests->contestendseat);
              $prizeRows = $this->buildContestPrizeRows($contestPrizeAmounts, $contestStartSeats, $contestEndSeats);
 
            

            return view(
                'admin.contest.editcontest',
                array_merge(
                    $this->contestModuleConfig(MatchContest::TYPE_PAID),
                    [
                        'matchcobntests' => $matchcobntests,
                        'prizeRows' => $prizeRows,
                    ]
                )
            );
        } 

        public function editfreecontest(int $id): View|RedirectResponse
        {
            if (!Auth::check()) {
                return $this->guestRedirect();
            }

            $matchcobntests = $this->contestQueryByType(MatchContest::TYPE_FREE)
                ->withCount(['gameplayEntries as joined_count'])
                ->findOrFail($id);

            return view(
                'admin.contest.editcontest',
                array_merge(
                    $this->contestModuleConfig(MatchContest::TYPE_FREE),
                    [
                        'matchcobntests' => $matchcobntests,
                        'prizeRows' => [['amount' => 0, 'start' => 1, 'end' => 1]],
                    ]
                )
            );
        }
        
      

        public function updatecontest(UpdateContestRequest $request): RedirectResponse
        {
            if (!Auth::check()) {
                return $this->guestRedirect();
            }

            $validated = $request->validated();

            MatchContest::query()
                ->findOrFail($validated['editid'])
                ->update($this->buildContestPayload($validated, true));
            
            Session::flash('sucmessage', "Successful, Match Contest  has Updated"); 
             
            return Redirect::back(); 
        } 

        public function updatefreecontest(UpdateContestRequest $request): RedirectResponse
        {
            if (!Auth::check()) {
                return $this->guestRedirect();
            }

            $validated = $request->validated();

            $this->contestQueryByType(MatchContest::TYPE_FREE)
                ->findOrFail($validated['editid'])
                ->update($this->buildContestPayload($validated, true));

            Session::flash('sucmessage', "Successful, Free Exam has Updated");

            return Redirect::back();
        }


        public function deletecontest(int $id): RedirectResponse {

            if (!Auth::check()) { 
                return $this->guestRedirect();
              }    
              
               MatchContest::query()->findOrFail($id)->delete();  
              
            Session::flash('sucmessage', "Successful,  Contest has Deleted"); 
             
            return Redirect::back(); 
            
        } 

        public function applieddetails(int $id): View|RedirectResponse
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }   
            
              $contest = MatchContest::query()
                  ->withCount(['gameplayEntries as joined_count'])
                  ->findOrFail($id);

              $gameplayhistory = GameplayHistory::query()
                  ->with('user')
                  ->where('contestid', $id)
                  ->orderByDesc('id')
                  ->get();
 
            

            return view('admin.contest.applieddetails')
                ->with('contest', $contest)
                ->with('gameplayhistory',$gameplayhistory);
        } 
        


        /////////////////
        //// Assignment of All type Contest
        ////////////////
        
        
        
        public function leaguecontest()
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }           
    
    
              $leagues = DB::table('leagues')->orderBy('id', 'DESC')->get();
    
            return view('admin.contest.league.leaguecontest')->with('leagues',$leagues);
        } 
        

        public function addleaguecontest()
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }           
    
    
              $leagues = DB::table('leagues')->orderBy('id', 'DESC')->get();
    
              $matchcobntests = DB::table('matchcobntests')->orderBy('id', 'ASC')->get(); 

            return view('admin.contest.league.addleaguecontest')->with('leagues',$leagues)->with('matchcobntests',$matchcobntests);
        } 

        public function loadallmatch($id)
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }   

              $currentda6te = date('Y-m-d');
     
              $matchesdetails = DB::table('matchesdetails')->where('matchstartdate', '>=',  $currentda6te)->where('matchleagueid',  $id)->orderBy('id', 'ASC')->get(); 

             

            return view('admin.load.loadallmatch')->with('matchesdetails',$matchesdetails);
        } 


         

        public function saveleaguecontest(Request $request)
        {
    
            date_default_timezone_set("Asia/Calcutta"); 
            
             $savedata =  $request->all(); 
    
             /// echo '<pre>'; print_r($savedata); echo '</pre>'; exit; 
              
            $leagueid = ''; $leaguename = '';   $matchid = ''; $matchname = '';   $firstteamid = ''; $firstteamname = '';   $secondteamid = ''; $secondteamname = ''; 
    
            $leaguenamearray = explode('<=>',$savedata['leaguename']);
    
            $leagueid =  $leaguenamearray[0];
    
            $leaguename =  $leaguenamearray[1];

            /////// Match Details 

             $leaguematcharray = explode('<=>',$savedata['leaguematch']);
    
            $matchid =  $leaguematcharray[0];
    
            $matchname =  $leaguematcharray[1]; 
            
            $firstteamid =  $leaguematcharray[2];

            $firstteamname =  $leaguematcharray[3];

            $secondteamid =  $leaguematcharray[4];

            $secondteamname =  $leaguematcharray[5];
    
           
    
        
    
            foreach($savedata['contestlist'] as $contestlist) {
    
                $conrestarray = explode('<=>',$contestlist);

                $contestid = '';  $contestname = '';  $contesttotalamt= 0;  $contestjoinamt= 0; 

                $contestid =  $conrestarray[0];

                $contestname =  $conrestarray[1];

                $contesttotalamt =  $conrestarray[2];

                $contestjoinamt =  $conrestarray[3];

                $allradydata = DB::table('leaguecontestlist')->where('contestid',  $contestid)->where('leaguematchid',  $matchid)->where('leagueid',  $leagueid)->first();

               ///  echo '<pre>'; print_r($allradydata); echo '</pre>'; exit; 

                if(!$allradydata) {

                        $insertdata = array( 
                                'leaguename'=>$leaguename,
                                'leagueid'=>$leagueid,              
                                'leaguematchname'=>$matchname,
                                'leaguematchid'=>$matchid,
                                'matchfirstteamid'=>$firstteamid,
                                'matchfirstteamname'=>$firstteamname,
                                'matchsecondid'=>$secondteamid, 
                                'matchsecondname'=>$secondteamname, 
                                'contestid'=>$contestid, 
                                'contestname'=>$contestname,  
                                'contresttotalamount'=>$contesttotalamt,  
                                'contestjoinamt'=>$contestjoinamt,  
                                'conteststratdate'=>$savedata['stratdate'],  
                                'contestenddate'=>$savedata['enddate'],   
                                'contestendtime'=>$savedata['joinprice'],  
                                'status'=>1,  
                            
                                'createdby'=>$savedata['userid'],                      
                                'createdtime'=>date("Y-m-d H:i:s"),
                            
                        );
                        
                        DB::table('leaguecontestlist')->insert($insertdata);  

                    }

            }
     
            
            Session::flash('sucmessage', "Successful, Match Contest  has Added"); 
             
            return Redirect::back(); 
        } 

        
        public function editleaguecontest($id)
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }           
    
    
              $leagues = DB::table('leagues')->orderBy('id', 'DESC')->get();
    
              $matchcobntests = DB::table('matchcobntests')->orderBy('id', 'ASC')->get(); 

              $leaguecontestlist = DB::table('leaguecontestlist')->where('id',  $id)->orderBy('id', 'ASC')->first(); 

            return view('admin.contest.league.editleaguecontest')->with('leagues',$leagues)->with('matchcobntests',$matchcobntests)->with('leaguecontestlist',$leaguecontestlist);
        } 


        
        public function updateleaguecontest(Request $request)
        {
    
            date_default_timezone_set("Asia/Calcutta"); 
            
             $savedata =  $request->all(); 
    
             /// echo '<pre>'; print_r($savedata); echo '</pre>'; exit;  

                        $insertdata = array(  
                                'conteststratdate'=>$savedata['stratdate'],  
                                'contestenddate'=>$savedata['enddate'],   
                                'contestendtime'=>$savedata['joinprice'],   
                        );
                        
                        DB::table('leaguecontestlist')->where('id',  $savedata['editid'])->update($insertdata);  

                     

     
     
            
            Session::flash('sucmessage', "Successful, League Contest  has Updated"); 
             
            return Redirect::back(); 
        } 


        public function deleteleaguecontest($id) {

            if (!Auth::check()) { 
                return $this->guestRedirect();
              }    
              
               DB::table('leaguecontestlist')->where('id', $id)->delete();  
              
            Session::flash('sucmessage', "Successful, League Contest has Deleted"); 
             
            return Redirect::back(); 
            
        } 
        


        public function appmanagement()
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }           
    
              $sitedetails = SiteDetail::query()->findOrFail(1); 

            return view('admin.sitedetails.appmanagement')
                ->with('sitedetails',$sitedetails)
                ->with('siteLogoUrl', $this->resolveAttachmentUrl((int) $sitedetails->applogo, $this->defaultSiteLogoUrl()));
        } 


         

          public function savemanagement(UpdateSiteDetailRequest $request)
          {
              $validated = $request->validated();
              $normalizedRechargeAmounts = $this->normalizeRechargeAmountConfig($validated['rechargeamt']);

              SiteDetail::query()->findOrFail($validated['editid'])->update([
                  'appname' => $validated['pagename'],
                  'appamount' => $normalizedRechargeAmounts,
                  'applogo' => $validated['photoid'] ?? null,
              ]);

            Session::flash('sucmessage', "Successful,  Site Details  has Updated"); 
             
            return Redirect::back(); 
        } 


        

        ////////////
        /// League Questions  
        ///////////////


        public function leaguequestioncontest($leagueid,$matchid,$contestid)
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }           
    
    
              /// echo $leagueid.''.$matchid.' '.$contestid; exit; 

              $leaguecontestlist = DB::table('leaguecontestlist')->where('leagueid',  $leagueid)->where('leaguematchid',  $matchid)->where('contestid',  $contestid)->orderBy('id', 'ASC')->first(); 

              $contestquestions = DB::table('contestquestions')->where('leagueid',  $leagueid)->where('matchid',  $matchid)->where('contestid',  $contestid)->orderBy('id', 'ASC')->first(); 

              /// echo '<pre>'; print_r($contestquestions); echo '</pre>'; exit; 

              $questionsdetails = DB::table('questionsdetails')->orderBy('id', 'ASC')->get(); 
              
    
            return view('admin.contest.questions.manaagequestions')->with('questionsdetails',$questionsdetails)->with('contestquestions',$contestquestions)->with('leaguecontestlist',$leaguecontestlist);
        } 
        

          /////////////////
        //// Assignment of All type Contest
        ////////////////
        
        
        
        public function leaguequestions()
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }           
    
    
              $questionsdetails = DB::table('questionsdetails')->orderBy('id', 'ASC')->get(); 
    
            return view('admin.questions.leaguequestions')->with('questionsdetails',$questionsdetails);
        } 
        

        public function addleaguequestions()
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }           
     

            return view('admin.questions.addleaguequestions');
        } 


        public function saveleaguequestions(Request $request)
        {
    
            date_default_timezone_set("Asia/Calcutta"); 
            
             $savedata =  $request->all(); 
    
             ////   echo '<pre>'; print_r($savedata); echo '</pre>'; exit; 
              
            
    
                $insertdata = array( 
                        'questiontitle'=>$savedata['questiontitle'], 
                        'questionhindi'=>$savedata['questionhindi'],               
                        'questiontype'=>$savedata['questiontype'],
                        'status'=>1, 
                        'playercount'=>$savedata['playerselect'],
                        'createdby'=>$savedata['userid'],                      
                        'createdtime'=>date("Y-m-d H:i:s"),
                    
                );
                
                DB::table('questionsdetails')->insert($insertdata);  
     
            
            Session::flash('sucmessage', "Successful, Questions  has Added"); 
             
            return Redirect::back(); 
        } 

        

        public function editleaguequestions($id)
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }           
  
              $questionsdetails = DB::table('questionsdetails')->where('id',  $id)->orderBy('id', 'ASC')->first(); 

            return view('admin.questions.editleaguequestions')->with('questionsdetails',$questionsdetails);
        } 


        public function updateleaguequestions(Request $request)
        {
    
            date_default_timezone_set("Asia/Calcutta"); 
            
             $savedata =  $request->all(); 
    
             ////   echo '<pre>'; print_r($savedata); echo '</pre>'; exit; 
              
            
    
                $insertdata = array( 
                        'questiontitle'=>$savedata['questiontitle'], 
                        'questionhindi'=>$savedata['questionhindi'],               
                        'questiontype'=>$savedata['questiontype'],
                        'playercount'=>$savedata['playerselect'],
                         
                    
                );
                
                DB::table('questionsdetails')->where('id',  $savedata['editid'])->update($insertdata);  
     
            
            Session::flash('sucmessage', "Successful, Questions  has Updated"); 
            
                $urldirect = url('admin/leaguequestions');

            return redirect()->to($urldirect);

          //  return Redirect::back(); 
        } 


        

        public function deleteleaguequestions($id) {

            if (!Auth::check()) { 
                return $this->guestRedirect();
              }    
              
               DB::table('questionsdetails')->where('id', $id)->delete();  
              
            Session::flash('sucmessage', "Successful, Question has Deleted"); 
             
            return Redirect::back(); 
            
        } 


        

        public function saveleaguequestioncontest(Request $request)
        {
    
            date_default_timezone_set("Asia/Calcutta"); 
            
             $savedata =  $request->all(); 
    
              /// echo '<pre>'; print_r($savedata); echo '</pre>'; exit; 


              if($savedata['editid'] > 0 ) {

                $insertdata = array( 
   
                    'quesitonsid'=>implode(',',$savedata['questionid']),
                         'firstteamid'=>$savedata['firstteamid'],
                        'secondteamid'=>$savedata['secondteamid'],
 
                
            );
            
            DB::table('contestquestions')->where('id',  $savedata['editid'])->update($insertdata); 

              }
              else {
            
    
                $insertdata = array( 
                        'leagueid'=>$savedata['leaguid'], 
                        'leaguename'=>$savedata['leaguename'],               
                        'matchid'=>$savedata['matchid'],
                        'matchname'=>$savedata['matchname'],
                        'contestid'=>$savedata['contestid'],
                        'contestname'=>$savedata['contestname'],
                        'firstteamname'=>$savedata['firstteamname'],
                        'secondteamname'=>$savedata['secondteamname'],
                        'quesitonsid'=>implode(',',$savedata['questionid']),
                        'firstteamid'=>$savedata['firstteamid'],
                        'secondteamid'=>$savedata['secondteamid'],

                        'createdby'=>$savedata['userid'],                      
                        'createdtime'=>date("Y-m-d H:i:s"),
                    
                );
                
                DB::table('contestquestions')->insert($insertdata); 
                
            }
     
            
            Session::flash('sucmessage', "Successful, Questions  has Updated"); 
             
            return Redirect::back(); 
        } 
        

       ////////////////////
       //// Class Management
       /////////////////// 
        
        
        public function managestudentsgroup()
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }           
    
              $studentsgroup = StudentGroup::query()->orderByDesc('id')->get();
    
            return view('admin.group.managestudentsgroup')->with('studentsgroup',$studentsgroup);
        } 
        

        public function addstudentsgroup()
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }   
              
            return view('admin.group.addstudentsgroup');
        } 

        public function savestudentsgroup(StoreStudentGroupRequest $request)
        {
            StudentGroup::query()->create($this->buildStudentGroupPayload($request->validated()));
            
            Session::flash('sucmessage', "Successful, Class Group  has Added"); 
             
            return Redirect::back(); 
        } 

       public function editstudentsgroup($id)
       {
           if (!Auth::check()) { 
               return $this->guestRedirect();
             }           
 
             $studentsgroup = StudentGroup::query()->findOrFail($id);
             $studentsgroup->image_url = $this->resolveAttachmentUrl(
                 (int) ($studentsgroup->groupimg ?? 0),
                 $this->defaultPortalImageUrl()
             );

           return view('admin.group.editstudentsgroup')->with('studentsgroup',$studentsgroup);
       } 


        public function updatestudentsgroup(UpdateStudentGroupRequest $request)
        {
            $validated = $request->validated();

            StudentGroup::query()
                ->findOrFail($validated['editid'])
                ->update($this->buildStudentGroupPayload($validated, true));  
            
            Session::flash('sucmessage', "Successful, Class Group  has Updated"); 
             
            return Redirect::back(); 
        } 


        public function deletestudentsgroup($id) {

            if (!Auth::check()) { 
                return $this->guestRedirect();
              }    
              
               StudentGroup::query()->findOrFail($id)->delete();  
              
            Session::flash('sucmessage', "Successful, Class Group has Deleted"); 
             
            return Redirect::back(); 
            
        } 


        ////////////////////
       //// Subject Management
       /////////////////// 
        
        
       public function manageclasssubject()
       {
           if (!Auth::check()) { 
               return $this->guestRedirect();
             }           
   
   
             $studentsgroup = StudentSubject::query()->orderByDesc('id')->get();
   
           return view('admin.subject.manageclasssubject')->with('studentsgroup',$studentsgroup);
       } 
       

       public function addclasssubject()
       {
           if (!Auth::check()) { 
               return $this->guestRedirect();
             }   
             
           return view('admin.subject.addclasssubject');
       } 

       public function saveclasssubject(StoreStudentSubjectRequest $request)
       {
           StudentSubject::query()->create($this->buildStudentSubjectPayload($request->validated()));
           
           Session::flash('sucmessage', "Successful, Student Subject  has Added"); 
            
           return Redirect::back(); 
       } 


       public function editclasssubject($id)
       {
           if (!Auth::check()) { 
               return $this->guestRedirect();
             }           
 
             $studentsgroup = StudentSubject::query()->findOrFail($id);
             $studentsgroup->image_url = $this->resolveAttachmentUrl(
                 (int) ($studentsgroup->subjectimg ?? 0),
                 $this->defaultPortalImageUrl()
             );

           return view('admin.subject.editclasssubject')->with('studentsgroup',$studentsgroup);
       } 


       public function updateclasssubject(UpdateStudentSubjectRequest $request)
       {
           $validated = $request->validated();

           StudentSubject::query()
               ->findOrFail($validated['editid'])
               ->update($this->buildStudentSubjectPayload($validated, true));  
           
           Session::flash('sucmessage', "Successful, Class Subject  has Updated"); 
            
           return Redirect::back(); 
       } 


       public function deleteclasssubject($id) {

        if (!Auth::check()) { 
            return $this->guestRedirect();
          }    
          
           StudentSubject::query()->findOrFail($id)->delete();  
          
        Session::flash('sucmessage', "Successful, Class Subject has Deleted"); 
         
        return Redirect::back(); 
        
    } 
    
    
    ////////////////////
    //// Subject Chapter Management
    /////////////////// 
     
    public function managemathchapter(Request $request): View|RedirectResponse
    {
        if (!Auth::check()) {
            return $this->guestRedirect();
        }

        $selectedGroupId = (int) $request->query('group', 0);
        $selectedSubjectId = (int) $request->query('subject', 0);
        $studentsgroup = StudentGroup::query()->orderByDesc('id')->get();
        $sudentsubject = StudentSubject::query()->orderByDesc('id')->get();
        $mathchapters = MathChapter::query()
            ->when($selectedGroupId > 0, fn ($query) => $query->where('classgroupid', $selectedGroupId))
            ->when($selectedSubjectId > 0, fn ($query) => $query->where('subjectid', $selectedSubjectId))
            ->orderBy('classgroupname')
            ->orderBy('subjectname')
            ->orderBy('chapterorder')
            ->orderBy('chaptername')
            ->orderByDesc('id')
            ->get();

        $chapterStats = QuestionManagement::query()
            ->when($selectedGroupId > 0, fn ($query) => $query->where('questiongroupid', $selectedGroupId))
            ->when($selectedSubjectId > 0, fn ($query) => $query->where('questionsubjectid', $selectedSubjectId))
            ->whereNotNull('questionchaptername')
            ->where('questionchaptername', '!=', '')
            ->get(['questionsubjectid', 'questiongroupid', 'questionchaptername', 'questionlist'])
            ->groupBy(function ($question) {
                return (int) $question->questionsubjectid
                    .'|'.(int) $question->questiongroupid
                    .'|'.strtolower(trim((string) $question->questionchaptername));
            })
            ->map(function ($questions) {
                return [
                    'module_count' => $questions->count(),
                    'slot_count' => $questions->sum(function ($question) {
                        return collect(LegacyJson::toArray($question->questionlist))
                            ->filter(fn ($value) => filled($value))
                            ->count();
                    }),
                ];
            });

        $mathchapters = $mathchapters->map(function ($chapter) use ($chapterStats) {
            $key = (int) $chapter->subjectid
                .'|'.(int) $chapter->classgroupid
                .'|'.strtolower(trim((string) $chapter->chaptername));
            $stats = $chapterStats->get($key, [
                'module_count' => 0,
                'slot_count' => 0,
            ]);

            $chapter->question_module_count = (int) ($stats['module_count'] ?? 0);
            $chapter->question_slot_count = (int) ($stats['slot_count'] ?? 0);

            return $chapter;
        });

        $totalQuestionModules = $mathchapters->sum('question_module_count');
        $totalQuestionSlots = $mathchapters->sum('question_slot_count');

        return view('admin.mathchapters.managemathchapter', [
            'mathchapters' => $mathchapters,
            'studentsgroup' => $studentsgroup,
            'sudentsubject' => $sudentsubject,
            'selectedGroupId' => $selectedGroupId,
            'selectedSubjectId' => $selectedSubjectId,
            'totalQuestionModules' => $totalQuestionModules,
            'totalQuestionSlots' => $totalQuestionSlots,
        ]);
    }

    public function addmathchapter(): View|RedirectResponse
    {
        if (!Auth::check()) {
            return $this->guestRedirect();
        }

        return view('admin.mathchapters.addmathchapter', [
            'studentsgroup' => StudentGroup::query()->orderByDesc('id')->get(),
            'sudentsubject' => StudentSubject::query()->orderByDesc('id')->get(),
        ]);
    }

    public function savemathchapter(StoreMathChapterRequest $request): RedirectResponse
    {
        MathChapter::query()->create($this->buildMathChapterPayload($request->validated()));

        Session::flash('sucmessage', "Successful, Subject Chapter has Added");

        return Redirect::back();
    }

    public function editmathchapter(int $id): View|RedirectResponse
    {
        if (!Auth::check()) {
            return $this->guestRedirect();
        }

        return view('admin.mathchapters.editmathchapter', [
            'chapterRecord' => MathChapter::query()->findOrFail($id),
            'studentsgroup' => StudentGroup::query()->orderByDesc('id')->get(),
            'sudentsubject' => StudentSubject::query()->orderByDesc('id')->get(),
        ]);
    }

    public function updatemathchapter(UpdateMathChapterRequest $request): RedirectResponse
    {
        $validated = $request->validated();

        MathChapter::query()
            ->findOrFail($validated['editid'])
            ->update($this->buildMathChapterPayload($validated, true));

        Session::flash('sucmessage', "Successful, Subject Chapter has Updated");

        return redirect()->route('admin.managemathchapter');
    }

    public function deletemathchapter(int $id): RedirectResponse
    {
        if (!Auth::check()) {
            return $this->guestRedirect();
        }

        MathChapter::query()->findOrFail($id)->delete();

        Session::flash('sucmessage', "Successful, Subject Chapter has Deleted");

        return Redirect::back();
    }

    
    /////////////////
    //// Pattern
    /////////////////
  
        
        
        public function managestudentspattern()
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }           
    
    
              $boardpattern = BoardPattern::query()->orderByDesc('id')->get();
    
            return view('admin.pattern.managestudentspattern')->with('boardpattern',$boardpattern);
        } 
        

        public function addstudentspattern()
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }   
              
            return view('admin.pattern.addstudentspattern');
        } 

         public function savestudentspattern(StoreBoardPatternRequest $request)
       {
           BoardPattern::query()->create($this->buildBoardPatternPayload($request->validated()));
           
           Session::flash('sucmessage', "Successful,  Board Pattern  has Added"); 
            
           return Redirect::back(); 
       } 



    public function editstudentspattern($id)
       {
           if (!Auth::check()) { 
               return $this->guestRedirect();
             }           
 
             $boardpattern = BoardPattern::query()->findOrFail($id);
             $boardpattern->image_url = $this->resolveAttachmentUrl(
                 (int) ($boardpattern->boardimg ?? 0),
                 $this->defaultPortalImageUrl()
             );

           return view('admin.pattern.editstudentspattern')->with('boardpattern',$boardpattern);
       } 


       public function updatestudentspattern(UpdateBoardPatternRequest $request)
       {
           $validated = $request->validated();

           BoardPattern::query()
               ->findOrFail($validated['editid'])
               ->update($this->buildBoardPatternPayload($validated, true));  
           
           Session::flash('sucmessage', "Successful, Board Pattern  has Updated"); 
            
           return Redirect::back(); 
       } 


         public function deletestudentspattern($id) {

              if (!Auth::check()) { 
                  return $this->guestRedirect();
                }    
                
                BoardPattern::query()->findOrFail($id)->delete();  
                
              Session::flash('sucmessage', "Successful,  Board Pattern has Deleted"); 
              
              return Redirect::back(); 
              
          } 

      ////////////////////
       //// Questions Management
       /////////////////// 
        
        
       public function managequestions(Request $request): View|RedirectResponse
       {
           if (!Auth::check()) { 
               return $this->guestRedirect();
             }           
             $selectedSubjectId = (int) $request->query('subject', 0);
             $selectedGroupId = (int) $request->query('goupsclass', 0);
             $selectedChapter = trim((string) $request->query('chapter', ''));
             $questionOptions = $this->questionFormOptions();
   
             $questionsmanagemnet = QuestionManagement::query()
                 ->when($selectedSubjectId > 0, fn ($query) => $query->where('questionsubjectid', $selectedSubjectId))
                 ->when($selectedGroupId > 0, fn ($query) => $query->where('questiongroupid', $selectedGroupId))
                 ->when($selectedChapter !== '', fn ($query) => $query->whereRaw('LOWER(TRIM(questionchaptername)) = ?', [Str::lower($selectedChapter)]))
                 ->orderByDesc('id')
                 ->get();
   
           return view(
               'admin.questions.managequestions',
               array_merge(
                   $questionOptions,
                   [
                       'questionsmanagemnet' => $questionsmanagemnet,
                       'selectedSubjectId' => $selectedSubjectId,
                       'selectedGroupId' => $selectedGroupId,
                       'selectedChapter' => $selectedChapter,
                   ]
               )
           );
       } 
       

       public function addquestions(): View|RedirectResponse
       {
           if (!Auth::check()) { 
               return $this->guestRedirect();
             }   

           return view('admin.questions.addquestions', $this->questionFormOptions());
       } 

       public function savequestions(StoreQuestionRequest $request): RedirectResponse
       {
           $payload = $this->buildQuestionPayload($request->validated());
           $payload['status'] = 1;
           $payload['createdby'] = Auth::id();
           $payload['createrdtime'] = now();

           QuestionManagement::query()->create($payload);
           
           Session::flash('sucmessage', "Successful, Student Question  has Added"); 
            
           return Redirect::back(); 
       } 


       public function editquestions(int $id): View|RedirectResponse
       {
           if (!Auth::check()) { 
               return $this->guestRedirect();
             }           
            $questionsmanagemnet = QuestionManagement::query()->findOrFail($id); 

           return view(
               'admin.questions.editquestions',
               array_merge(
                   $this->questionFormOptions(),
                   ['questionsmanagemnet' => $questionsmanagemnet]
               )
           );
       } 


       public function updatequestions(UpdateQuestionRequest $request): RedirectResponse
       {
           $validated = $request->validated();
           $payload = $this->buildQuestionPayload($validated);

           QuestionManagement::query()
               ->findOrFail($validated['editid'])
               ->update($payload);  
           
           Session::flash('sucmessage', "Successful, Student Question  has Updated"); 

           return redirect()->route('admin.managequestions');
            
          //  return Redirect::back();  
       } 

       public function deletequestions($id) {

        if (!Auth::check()) { 
            return $this->guestRedirect();
          }    
          
           QuestionManagement::query()->findOrFail($id)->delete();  
          
        Session::flash('sucmessage', "Successful, Questions has Deleted"); 
         
        return Redirect::back(); 
        
    } 


        ////////////////////
       //// Questions Management
       /////////////////// 
        
        
       public function managequestionssets(): View|RedirectResponse
       {
           if (!Auth::check()) { 
               return $this->guestRedirect();
             }     
            $questionsetupmanage = QuestionSetup::query()->orderByDesc('id')->get();
   
           return view('admin.questions.managequestionssets')->with('questionsetupmanage',$questionsetupmanage);
       } 
    

       
       public function addquestionsset(): View|RedirectResponse
       {
           if (!Auth::check()) { 
               return $this->guestRedirect();
             }   

           $oldGroupValue = (string) session()->getOldInput('questiongoupsclass', '');
           $oldGroupParts = $oldGroupValue !== '' ? explode('<=>', $oldGroupValue, 2) : [];
           $selectedGroupId = isset($oldGroupParts[0]) && is_numeric($oldGroupParts[0]) ? (int) $oldGroupParts[0] : 0;

           return view(
               'admin.questions.addquestionsset',
               [
                   'studentsgroup' => StudentGroup::query()->orderByDesc('id')->get(),
                   'questionSetPanels' => $this->questionSetPanelData($selectedGroupId),
               ]
           );
       } 

       public function loadquestions(): View|RedirectResponse
       {
           if (!Auth::check()) { 
               return $this->guestRedirect();
             }   

             $classid = (int) request()->query('classid');

           return view(
               'admin.load.question-options',
               [
                   'questionsmanagemnet' => $this->questionOptionsBySubjectAndClass(1, $classid),
                   'inputName' => 'questionsetgk',
               ]
           );
       } 

       public function loadquestionscince(): View|RedirectResponse
       {
           if (!Auth::check()) { 
               return $this->guestRedirect();
             }   

             $classid = (int) request()->query('classid');

           return view(
               'admin.load.question-options',
               [
                   'questionsmanagemnet' => $this->questionOptionsBySubjectAndClass(2, $classid),
                   'inputName' => 'questionsetnscince',
               ]
           );
       } 

       public function loadquestionhindi(): View|RedirectResponse
       {
           if (!Auth::check()) { 
               return $this->guestRedirect();
             }   

             $classid = (int) request()->query('classid');

           return view(
               'admin.load.question-options',
               [
                   'questionsmanagemnet' => $this->questionOptionsBySubjectAndClass(4, $classid),
                   'inputName' => 'questionsetnhindi',
               ]
           );
       } 

       public function loadquestionenglish(): View|RedirectResponse
       {
           if (!Auth::check()) { 
               return $this->guestRedirect();
             }   

             $classid = (int) request()->query('classid');

           return view(
               'admin.load.question-options',
               [
                   'questionsmanagemnet' => $this->questionOptionsBySubjectAndClass(3, $classid),
                   'inputName' => 'questionsetenglish',
               ]
           );
       } 
       public function loadquestionmaths(): View|RedirectResponse
       {
           if (!Auth::check()) { 
               return $this->guestRedirect();
             }   

             $classid = (int) request()->query('classid');

           return view(
               'admin.load.question-options',
               [
                   'questionsmanagemnet' => $this->questionOptionsBySubjectAndClass(5, $classid),
                   'inputName' => 'questionsetmath',
               ]
           );
       }  
       
       public function savequestionsset(StoreQuestionSetRequest $request): RedirectResponse
       {
           $payload = $this->buildQuestionSetPayload($request->validated());
           $payload['status'] = 1;
           $payload['createdby'] = Auth::id();
           $payload['createdtime'] = now();

           QuestionSetup::query()->create($payload);
           
           Session::flash('sucmessage', "Successful, Student Question Set has Added"); 
            
           return Redirect::back(); 
       } 


       public function editquestionsset(int $id): View|RedirectResponse
       {
           if (!Auth::check()) { 
               return $this->guestRedirect();
             }           
            $questionsetup = QuestionSetup::query()->findOrFail($id); 

           return view(
               'admin.questions.editquestionsset',
               [
                   'studentsgroup' => StudentGroup::query()->orderByDesc('id')->get(),
                   'questionsetup' => $questionsetup,
                   'questionSetPanels' => $this->questionSetPanelData((int) $questionsetup->questionsetclassid),
               ]
           );
       } 


       public function updatequestionsset(UpdateQuestionSetRequest $request): RedirectResponse
       {
           $validated = $request->validated();
           $questionSetup = QuestionSetup::query()->findOrFail($validated['editid']);

           $questionSetup->update($this->buildQuestionSetPayload($validated, $questionSetup));  
           
           Session::flash('sucmessage', "Successful, Student Question Set has Updated"); 

           return redirect()->route('admin.managequestionssets');
            
          //// return Redirect::back(); 
       } 


       public function deletequestionsset($id) {

        if (!Auth::check()) { 
            return $this->guestRedirect();
          }    
          
           QuestionSetup::query()->findOrFail($id)->delete();  
          
        Session::flash('sucmessage', "Successful, Questions Set has Deleted"); 
         
        return Redirect::back(); 
        
    } 

    //////////////////
    // Assign Compitetion
    /////////////////////


    public function assigncompetition(Request $request): View|RedirectResponse
    {
        if (!Auth::check()) { 
            return $this->guestRedirect();
          }           

          $selectedGroupId = (int) $request->query('goupsclass', 0);
          $moduleConfig = $this->contestModuleConfig(MatchContest::TYPE_PAID);

          $studentsgroup = StudentGroup::query()->orderByDesc('id')->get();

          $compitetionassignment = $this->assignmentQueryByContestType(MatchContest::TYPE_PAID)
              ->when($selectedGroupId > 0, fn ($query) => $query->where('groupclassid', $selectedGroupId))
              ->orderByDesc('id')
              ->get();

        return view('admin.assigncompitetions.assigncompetition', array_merge($moduleConfig, [
            'studentsgroup' => $studentsgroup,
            'compitetionassignment' => $compitetionassignment,
            'selectedGroupId' => $selectedGroupId,
        ]));
    } 

    public function freeassigncompetition(Request $request): View|RedirectResponse
    {
        if (!Auth::check()) {
            return $this->guestRedirect();
        }

        $selectedGroupId = (int) $request->query('goupsclass', 0);
        $moduleConfig = $this->contestModuleConfig(MatchContest::TYPE_FREE);
        $studentsgroup = StudentGroup::query()->orderByDesc('id')->get();

        $compitetionassignment = $this->assignmentQueryByContestType(MatchContest::TYPE_FREE)
            ->when($selectedGroupId > 0, fn ($query) => $query->where('groupclassid', $selectedGroupId))
            ->orderByDesc('id')
            ->get();

        return view('admin.assigncompitetions.assigncompetition', array_merge($moduleConfig, [
            'studentsgroup' => $studentsgroup,
            'compitetionassignment' => $compitetionassignment,
            'selectedGroupId' => $selectedGroupId,
        ]));
    }
    

    public function addassigncompetition(): View|RedirectResponse
    {
        if (!Auth::check()) { 
            return $this->guestRedirect();
          }   

        return view(
            'admin.assigncompitetions.addassigncompetition',
            array_merge(
                $this->contestModuleConfig(MatchContest::TYPE_PAID),
                $this->assignmentFormOptions(MatchContest::TYPE_PAID)
            )
        );
    } 

    public function addfreeassigncompetition(): View|RedirectResponse
    {
        if (!Auth::check()) {
            return $this->guestRedirect();
        }

        return view(
            'admin.assigncompitetions.addassigncompetition',
            array_merge(
                $this->contestModuleConfig(MatchContest::TYPE_FREE),
                $this->assignmentFormOptions(MatchContest::TYPE_FREE)
            )
        );
    }

    public function saveassigncompetition(StoreCompetitionAssignmentRequest $request): RedirectResponse
    {
        if (!Auth::check()) {
            return $this->guestRedirect();
        }

        $payload = $this->buildCompetitionAssignmentPayload($request->validated());
        $payload['status'] = 1;
        $payload['createdby'] = Auth::id();
        $payload['createdtime'] = now();

        CompetitionAssignment::query()->create($payload);  
        
        Session::flash('sucmessage', "Successful, Competition Question Set has Assign"); 
         
        return Redirect::back(); 
    } 

    public function savefreeassigncompetition(StoreCompetitionAssignmentRequest $request): RedirectResponse
    {
        if (!Auth::check()) {
            return $this->guestRedirect();
        }

        $payload = $this->buildCompetitionAssignmentPayload($request->validated());
        $payload['status'] = 1;
        $payload['createdby'] = Auth::id();
        $payload['createdtime'] = now();

        CompetitionAssignment::query()->create($payload);

        Session::flash('sucmessage', "Successful, Free Exam Assignment has Added");

        return Redirect::back();
    }

    public function editassigncompetition(int $id): View|RedirectResponse
    {
        if (!Auth::check()) { 
            return $this->guestRedirect();
          }           
 
          $compitetionassignment = $this->assignmentQueryByContestType(MatchContest::TYPE_PAID)->findOrFail($id); 

        return view(
            'admin.assigncompitetions.editassigncompetition',
            array_merge(
                ['compitetionassignment' => $compitetionassignment],
                $this->contestModuleConfig(MatchContest::TYPE_PAID),
                $this->assignmentFormOptions(MatchContest::TYPE_PAID)
            )
        );
    } 

    public function editfreeassigncompetition(int $id): View|RedirectResponse
    {
        if (!Auth::check()) {
            return $this->guestRedirect();
        }

        $compitetionassignment = $this->assignmentQueryByContestType(MatchContest::TYPE_FREE)->findOrFail($id);

        return view(
            'admin.assigncompitetions.editassigncompetition',
            array_merge(
                ['compitetionassignment' => $compitetionassignment],
                $this->contestModuleConfig(MatchContest::TYPE_FREE),
                $this->assignmentFormOptions(MatchContest::TYPE_FREE)
            )
        );
    }



    public function updateassigncompetition(UpdateCompetitionAssignmentRequest $request): RedirectResponse
    {
        if (!Auth::check()) {
            return $this->guestRedirect();
        }

        $validated = $request->validated();

        CompetitionAssignment::query()
            ->findOrFail($validated['editid'])
            ->update($this->buildCompetitionAssignmentPayload($validated));  
        
        Session::flash('sucmessage', "Successful, Competition Question Set has Assigned Updated"); 


        return redirect()->route('admin.assigncompetition');
         
        /// return Redirect::back(); 
    } 

    public function updatefreeassigncompetition(UpdateCompetitionAssignmentRequest $request): RedirectResponse
    {
        if (!Auth::check()) {
            return $this->guestRedirect();
        }

        $validated = $request->validated();

        $this->assignmentQueryByContestType(MatchContest::TYPE_FREE)
            ->findOrFail($validated['editid'])
            ->update($this->buildCompetitionAssignmentPayload($validated));

        Session::flash('sucmessage', "Successful, Free Exam Assignment has Updated");

        return redirect()->route('admin.freeassigncompetition');
    }

    public function deleteassigncompetition(int $id): RedirectResponse {

      if (!Auth::check()) { 
          return $this->guestRedirect();
        }    
        
         CompetitionAssignment::query()->findOrFail($id)->delete();  
        
      Session::flash('sucmessage', "Successful, Competition Question Set  has Deleted"); 
       
      return Redirect::back(); 
      
  } 

   ///////////////////////////
        /////// Scholarship
        /////////////////////////

        

         
           public function scholarshipcompetition(): View|RedirectResponse
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }   
     
              $competitionAssignments = CompetitionAssignment::query()
                  ->with(['contest', 'board', 'group'])
                  ->withCount('gameplayEntries')
                  ->orderByDesc('id')
                  ->get();

              $distributedAssignmentIds = WinningHistory::query()
                  ->whereNotNull('competitionassignid')
                  ->select('competitionassignid')
                  ->distinct()
                  ->pluck('competitionassignid')
                  ->map(fn ($value) => (int) $value)
                  ->all();

            return view('admin.scholarship.scholarshipcompetition', [
                'competitionAssignments' => $competitionAssignments,
                'distributedAssignmentIds' => $distributedAssignmentIds,
            ]);
        } 


           public function resultdetails(int $id): View|RedirectResponse
       {
           if (!Auth::check()) { 
               return $this->guestRedirect();
             }           

           $assignment = CompetitionAssignment::query()
               ->with(['contest', 'board', 'group'])
               ->withCount('gameplayEntries')
               ->findOrFail($id);

           $contest = $assignment->contest;
  
           $useranswerdetails = UserAnswerDetail::query()
               ->with('user')
               ->where('competitionassignid', $assignment->id)
               ->orderByDesc('totalpercentage')
               ->get();

           $paymentDistributed = WinningHistory::query()
               ->where('competitionassignid', $assignment->id)
               ->exists();

           $distributedWinnerCount = WinningHistory::query()
               ->where('competitionassignid', $assignment->id)
               ->count();
           

           return view('admin.scholarship.resultdetails', [
               'assignment' => $assignment,
               'contest' => $contest,
               'useranswerdetails' => $useranswerdetails,
               'id' => $assignment->id,
               'paymentDistributed' => $paymentDistributed,
               'distributedWinnerCount' => $distributedWinnerCount,
           ]);
       } 

       

          public function paymentdistribute(int $id): RedirectResponse
        {
            if (!Auth::check()) {
                return $this->guestRedirect();
            }

            $assignment = CompetitionAssignment::query()
                ->with('contest')
                ->findOrFail($id);

            $matchcobntests = $assignment->contest;

            if (! $matchcobntests) {
                Session::flash('message', 'Competition details are missing for this assignment.');

                return Redirect::back();
            }

            if (WinningHistory::query()->where('competitionassignid', $assignment->id)->exists()) {
                Session::flash('message', 'Scholarship rewards have already been distributed for this assignment.');

                return Redirect::back();
            }

            $contestPrizeAmounts = array_map('floatval', $this->parseContestCsv($matchcobntests->contestprizeamt));
            $contestStartSeats = array_map('intval', $this->parseContestCsv($matchcobntests->conteststartseat));
            $contestEndSeats = array_map('intval', $this->parseContestCsv($matchcobntests->contestendseat));
            $lastRankValue = collect($contestEndSeats)->filter(fn ($rank) => $rank > 0)->max() ?? 0;

            if ($lastRankValue < 1) {
                Session::flash('message', 'Prize distribution is not configured correctly for this competition.');

                return Redirect::back();
            }

            $useranswerdetails = UserAnswerDetail::query()
                ->with('user')
                ->where('status', 1)
                ->where('competitionassignid', $assignment->id)
                ->orderByDesc('totalpercentage')
                ->limit($lastRankValue)
                ->get();

            if ($useranswerdetails->isEmpty()) {
                Session::flash('message', 'No submitted results are available for distribution yet.');

                return Redirect::back();
            }

            $awardedCount = 0;

            DB::transaction(function () use (
                $useranswerdetails,
                $assignment,
                $matchcobntests,
                $contestPrizeAmounts,
                $contestStartSeats,
                $contestEndSeats,
                &$awardedCount
            ) {
                foreach ($useranswerdetails->values() as $index => $useranswerdetailsdata) {
                    $currentRank = $index + 1;
                    $matchedPrizeIndex = null;

                    foreach ($contestStartSeats as $rankSection => $startSeat) {
                        $endSeat = $contestEndSeats[$rankSection] ?? $startSeat;
                        if ($startSeat <= $currentRank && $endSeat >= $currentRank) {
                            $matchedPrizeIndex = $rankSection;
                            break;
                        }
                    }

                    if ($matchedPrizeIndex === null) {
                        continue;
                    }

                    $usersdetails = $useranswerdetailsdata->user;
                    if (! $usersdetails) {
                        continue;
                    }

                    $prizeAmount = (float) ($contestPrizeAmounts[$matchedPrizeIndex] ?? 0);

                    $alreadyDistributed = WinningHistory::query()
                        ->where('competitionassignid', $assignment->id)
                        ->where('userid', $usersdetails->id)
                        ->exists();

                    if ($alreadyDistributed) {
                        continue;
                    }

                    WinningHistory::query()->create([
                        'competitionid' => $useranswerdetailsdata->competitionid,
                        'competitionname' => $useranswerdetailsdata->competitiontitle,
                        'competitionassignid' => $assignment->id,
                        'competitionassingtitle' => $useranswerdetailsdata->competitionassigntitle,
                        'userid' => $usersdetails->id,
                        'useramount' => $prizeAmount,
                        'username' => $usersdetails->name,
                        'rank' => $currentRank,
                        'createdtime' => now(),
                    ]);

                    $walletusers = WalletUser::query()->firstOrCreate(
                        ['userid' => $usersdetails->id],
                        [
                            'username' => $usersdetails->name,
                            'walletamount' => 0,
                            'updatedtime' => now(),
                        ]
                    );

                    $walletusers->update([
                        'username' => $usersdetails->name,
                        'walletamount' => (float) $walletusers->walletamount + $prizeAmount,
                        'updatedtime' => now(),
                    ]);

                    $awardedCount++;
                }
            });

            if ($awardedCount === 0) {
                Session::flash('message', 'No new scholarship rewards were distributed.');

                return Redirect::back();
            }

            Session::flash('sucmessage', "Successful, Scholership has been distributed to {$awardedCount} student(s)."); 
             
            return Redirect::back(); 
        } 

}

