<?php
  
namespace App\Http\Controllers\frontend;
  
use App\Http\Controllers\Controller;
use App\Http\Requests\Frontend\StoreExamSubmissionRequest;
use App\Http\Requests\Frontend\StoreStudentAttachmentRequest;
use App\Http\Requests\Frontend\StoreWithdrawRequest;
use App\Http\Requests\Frontend\StoreWalletAmountRequest;
use App\Http\Requests\Frontend\UpdateStudentProfileImageRequest;
use App\Http\Requests\Frontend\UpdateStudentProfileRequest;
use App\Http\Requests\Frontend\VerifyStudentOtpRequest;
use App\Models\Attachment;
use App\Models\BannerImage;
use App\Models\BoardPattern;
use App\Models\CompetitionAssignment;
use App\Models\GameplayHistory;
use App\Models\MatchContest;
use App\Models\PageDetail;
use App\Models\QuestionManagement;
use App\Models\QuestionSetup;
use App\Models\SchoolDetail;
use App\Models\SiteDetail;
use App\Models\StudentGroup;
use App\Models\StudentProfile;
use App\Models\UserAnswerDetail;
use App\Support\LegacyJson;
use App\Models\WalletHistory;
use App\Models\WalletUser;
use App\Models\WinningHistory;
use App\Models\WithdrawHistory;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Schema;
use Session;
use Illuminate\Support\Facades\Redirect;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Response;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Hash;
use DB; 
use Illuminate\View\View;
use Throwable;

  
class FrontendController extends Controller
{
    private function redirectAuthenticatedPortalUser(): RedirectResponse
    {
        $user = Auth::user();
        $userType = (int) ($user->usertype ?? 0);

        if ($userType !== 4) {
            return redirect()->route('admin.dashboard');
        }

        $hasProfile = StudentProfile::query()
            ->where('studentid', $user->id)
            ->exists();

        return $hasProfile
            ? redirect()->route('competitionlist')
            : redirect()->route('editprofile');
    }

    private function landingPageStats(): array
    {
        return [
            [
                'value' => MatchContest::query()->count(),
                'label' => 'Competitions',
            ],
            [
                'value' => User::query()->where('usertype', 4)->count(),
                'label' => 'Students',
            ],
            [
                'value' => QuestionSetup::query()->count(),
                'label' => 'Exam Sets',
            ],
        ];
    }

    private function frontendAssetUrl(string $path): string
    {
        return ASSETURL . 'public/frontend/' . ltrim($path, '/');
    }

    private function storedFileUrl(string $relativePath): string
    {
        return ASSETURL . 'files/' . ltrim(str_replace('\\', '/', $relativePath), '/');
    }

    private function studentDisplayName(User $user): string
    {
        return trim($user->name . ' ' . ($user->lastname ?? ''));
    }

    private function currentStudentWalletAmount(int $userId): float
    {
        return (float) WalletUser::query()->where('userid', $userId)->sum('walletamount');
    }

    private function contestDetailsRouteParams(int $contestId, ?int $assignmentId = null): array
    {
        $params = ['id' => $contestId];

        if ($assignmentId) {
            $params['assignment'] = $assignmentId;
        }

        return $params;
    }

    private function dispatchSmsOtp(string $mobile, int $otp): void
    {
        $number = urlencode($mobile);
        $message = rawurlencode(
            "Dear user your registration mobile number verification OTP is {$otp} please do not share the otp with any one. HARIHAR LANGUAGE"
        );
        $smsUrl = 'http://msg.smscluster.com/rest/services/sendSMS/sendGroupSms?AUTH_KEY=f470fdd03171fb2bfe46d29c9f3e936&message='
            . $message
            . '&senderId=HRIHRL&routeId=1&mobileNos='
            . $number;

        try {
            $ch = curl_init($smsUrl);

            if ($ch === false) {
                return;
            }

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_exec($ch);
            curl_close($ch);
        } catch (Throwable) {
            // Keep the existing verification flow resilient in local environments.
        }
    }

    private function issueStudentMobileVerificationOtp(User $user): void
    {
        $otp = random_int(100000, 999999);

        $user->update([
            'otpnumber' => $otp,
            'updated_at' => now(),
        ]);

        $this->dispatchSmsOtp((string) $user->mobileno, $otp);
    }

    private function dispatchEmailVerificationCode(string $email, int $otp): void
    {
        $subject = 'Just Exam League Email Verification';
        $message = '
        <html>
        <head><title>Just Exam League Email Verification</title></head>
        <body>
            <table>
                <tr><th>Email ID:</th><td>' . e($email) . '</td></tr>
                <tr><th>Verification Code:</th><td>' . e((string) $otp) . '</td></tr>
            </table>
        </body>
        </html>';

        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8\r\n";
        $headers .= "From: <info@justexamleague.com>\r\n";

        try {
            @mail($email, $subject, $message, $headers);
        } catch (Throwable) {
            // Keep the existing verification flow resilient in local environments.
        }
    }

    private function issueStudentEmailVerificationOtp(User $user): void
    {
        $otp = random_int(100000, 999999);

        $user->update([
            'emailotp' => $otp,
            'updated_at' => now(),
        ]);

        $this->dispatchEmailVerificationCode((string) $user->useremailid, $otp);
    }

    private function studentGuestRedirect(): RedirectResponse
    {
        return redirect()->route('student.entry')
            ->with('message', 'Please login to continue.');
    }

    private function noStoreViewResponse(string $view, array $data = []): Response
    {
        return response()
            ->view($view, $data)
            ->header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
            ->header('Pragma', 'no-cache')
            ->header('Expires', 'Thu, 01 Jan 1970 00:00:00 GMT');
    }

    private function currentStudentProfile(): object
    {
        $profile = StudentProfile::query()->where('studentid', Auth::id())->first();

        if ($profile) {
            return $profile;
        }

        $user = Auth::user();

        return (object) [
            'id' => Auth::id(),
            'studentid' => Auth::id(),
            'classid' => $user->classid ?? null,
            'classname' => null,
            'fathername' => null,
            'mothername' => null,
            'dateofbirth' => null,
            'srnumber' => null,
            'studentupiid' => null,
            'pancardnumber' => null,
            'bankaccountnumber' => null,
            'bankaccountholdername' => null,
            'bankbranch' => null,
            'bankifsccode' => null,
            'religion' => null,
        ];
    }

    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 buildProfileImageUrl(User $user): string
    {
        $fallbackUrl = $this->frontendAssetUrl('images/logo.png');

        if (! $user->profileimh) {
            return $fallbackUrl;
        }

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

        return $attachment ? $this->storedFileUrl($attachment->att_url) : $fallbackUrl;
    }

    private function buildWalletRechargeAmounts(User $user): array
    {
        $siteDetails = SiteDetail::query()->find(1);

        if (! $siteDetails || blank($siteDetails->appamount)) {
            return [[], 0];
        }

        $schoolDetails = null;
        $instituteCode = str_replace('jel_', '', (string) $user->institutecode);
        if ($instituteCode !== '') {
            $schoolDetails = SchoolDetail::query()->where('schoolid', $instituteCode)->first();
        }

        $commission = (float) ($schoolDetails->schoolcommision ?? 0);
        $amounts = [];

        foreach (explode(',', (string) $siteDetails->appamount) as $amount) {
            $baseAmount = (float) trim($amount);

            if ($baseAmount <= 0) {
                continue;
            }

            $adjustedAmount = $baseAmount;
            if ($commission > 0) {
                $adjustedAmount += ($commission / 100) * $baseAmount;
            }

            $amounts[] = round($adjustedAmount, 2);
        }

        $amounts = array_values(array_unique(array_filter($amounts, static fn ($amount) => $amount > 0)));
        sort($amounts);

        return [$amounts, $amounts[0] ?? 0];
    }

    private function attachmentUrl(?int $attachmentId, string $fallbackUrl): string
    {
        if (! $attachmentId) {
            return $fallbackUrl;
        }

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

        return $attachment ? $this->storedFileUrl($attachment->att_url) : $fallbackUrl;
    }

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

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

    private function buildContestRankRows(MatchContest $contest): array
    {
        $prizeAmounts = $this->splitLegacyList($contest->contestprizeamt);
        $startRanks = $this->splitLegacyList($contest->conteststartseat);
        $endRanks = $this->splitLegacyList($contest->contestendseat);
        $rows = [];
        $totalRows = max(count($prizeAmounts), count($startRanks), count($endRanks));

        for ($index = 0; $index < $totalRows; $index++) {
            $startRank = isset($startRanks[$index]) ? (int) $startRanks[$index] : null;
            $endRank = isset($endRanks[$index]) ? (int) $endRanks[$index] : $startRank;
            $prizeAmount = isset($prizeAmounts[$index]) ? (float) $prizeAmounts[$index] : 0.0;

            if ($startRank === null && $endRank === null && $prizeAmount <= 0) {
                continue;
            }

            $rows[] = [
                'start_rank' => $startRank,
                'end_rank' => $endRank,
                'prize_amount' => $prizeAmount,
            ];
        }

        return $rows;
    }

    private function isAssignmentJoinWindowOpen(CompetitionAssignment $assignment): bool
    {
        $today = now()->toDateString();

        if ($assignment->startdate && $today < $assignment->startdate->format('Y-m-d')) {
            return false;
        }

        if ($assignment->enddate && $today > $assignment->enddate->format('Y-m-d')) {
            return false;
        }

        return true;
    }

    private function joinWindowStatusMessage(CompetitionAssignment $assignment): ?string
    {
        $today = now()->toDateString();

        if ($assignment->startdate && $today < $assignment->startdate->format('Y-m-d')) {
            return 'Registration will open on '.$assignment->startdate->format('d M Y').'.';
        }

        if ($assignment->enddate && $today > $assignment->enddate->format('Y-m-d')) {
            return 'Registration is closed for this competition.';
        }

        return null;
    }

    private function isCompetitionSeatAvailable(MatchContest $contest, ?int $joinedCount = null): bool
    {
        $contestSeat = max(0, (int) $contest->contestseat);

        if ($contestSeat === 0) {
            return false;
        }

        $joinedCount ??= GameplayHistory::query()->where('contestid', $contest->id)->count();

        return $joinedCount < $contestSeat;
    }

    private function isAssignmentExamLive(CompetitionAssignment $assignment): bool
    {
        if (! $assignment->examdate) {
            return false;
        }

        if (now()->toDateString() !== $assignment->examdate->format('Y-m-d')) {
            return false;
        }

        if (! $assignment->examendtime) {
            return true;
        }

        return now()->format('H:i:s') <= (string) $assignment->examendtime;
    }

    private function examWindowStatusMessage(CompetitionAssignment $assignment): string
    {
        if (! $assignment->examdate) {
            return 'Exam schedule is not available right now.';
        }

        $today = now()->toDateString();
        $examDate = $assignment->examdate->format('Y-m-d');

        if ($today < $examDate) {
            return 'Exam will start on '.$assignment->examdate->format('d M Y').'.';
        }

        if ($today > $examDate) {
            return 'Exam window is closed for this competition.';
        }

        if ($assignment->examendtime && now()->format('H:i:s') > (string) $assignment->examendtime) {
            return 'Exam time is over for today.';
        }

        return 'Exam is not available right now.';
    }

    private function buildCompetitionSections(object $studentsprofile): Collection
    {
        $currentDate = now()->toDateString();

        $assignments = CompetitionAssignment::query()
            ->with(['contest', 'board'])
            ->when(
                $studentsprofile->classid,
                fn ($query) => $query->where('groupclassid', $studentsprofile->classid),
                fn ($query) => $query->whereRaw('1 = 0')
            )
            ->where('startdate', '<=', $currentDate)
            ->where('enddate', '>=', $currentDate)
            ->orderBy('startdate', 'ASC')
            ->get();

        $assignmentIds = $assignments
            ->pluck('id')
            ->filter()
            ->unique()
            ->values();

        $boardIds = $assignments
            ->pluck('boardpatternid')
            ->filter()
            ->unique()
            ->values();

        $joinedCounts = $assignmentIds->isEmpty()
            ? collect()
            : GameplayHistory::query()
                ->select('assignquestionid', DB::raw('COUNT(*) as total'))
                ->whereIn('assignquestionid', $assignmentIds)
                ->groupBy('assignquestionid')
                ->pluck('total', 'assignquestionid');

        $assignmentsByBoard = $assignments->groupBy('boardpatternid');

        return BoardPattern::query()
            ->when(
                $boardIds->isNotEmpty(),
                fn ($query) => $query->whereIn('id', $boardIds),
                fn ($query) => $query->whereRaw('1 = 0')
            )
            ->orderBy('showname', 'ASC')
            ->get()
            ->map(function (BoardPattern $board) use ($assignmentsByBoard, $joinedCounts) {
                $cards = $assignmentsByBoard
                    ->get($board->id, collect())
                    ->map(function (CompetitionAssignment $assignment) use ($joinedCounts) {
                        $contest = $assignment->contest;

                        if (! $contest) {
                            return null;
                        }

                        $joinedCount = (int) ($joinedCounts[$assignment->id] ?? 0);
                        $contestSeat = max(0, (int) $contest->contestseat);
                        $joinedPercent = $contestSeat > 0 ? round(($joinedCount / $contestSeat) * 100, 2) : 0;
                        $rankRows = $this->buildContestRankRows($contest);
                        $lastRankRow = ! empty($rankRows) ? $rankRows[array_key_last($rankRows)] : null;

                        return [
                            'assignment' => $assignment,
                            'contest' => $contest,
                            'detail_url' => route('contestdetails', $this->contestDetailsRouteParams($contest->id, (int) $assignment->id)),
                            'remaining_seat' => max(0, $contestSeat - $joinedCount),
                            'joined_percent' => $joinedPercent,
                            'first_prize' => $rankRows[0]['prize_amount'] ?? 0,
                            'last_rank' => $lastRankRow['end_rank'] ?? null,
                        ];
                    })
                    ->filter()
                    ->values()
                    ->all();

                return [
                    'board' => $board,
                    'cards' => $cards,
                ];
            })
            ->filter(fn ($section) => ! empty($section['cards']))
            ->values();
    }

    private function buildStudentCompetitionTimeline(object $studentsprofile): Collection
    {
        if (! $studentsprofile->classid) {
            return collect();
        }

        $today = now()->toDateString();
        $joinedAssignments = GameplayHistory::query()
            ->where('userid', Auth::id())
            ->pluck('assignquestionid')
            ->map(fn ($assignmentId) => (int) $assignmentId)
            ->flip();
        $submittedAssignments = UserAnswerDetail::query()
            ->where('createdby', Auth::id())
            ->pluck('competitionassignid')
            ->map(fn ($assignmentId) => (int) $assignmentId)
            ->flip();

        return CompetitionAssignment::query()
            ->with(['contest', 'board'])
            ->where('groupclassid', $studentsprofile->classid)
            ->orderByDesc('examdate')
            ->orderByDesc('startdate')
            ->limit(6)
            ->get()
            ->map(function (CompetitionAssignment $assignment) use ($today, $joinedAssignments, $submittedAssignments) {
                $contest = $assignment->contest;

                if (! $contest) {
                    return null;
                }

                $rankRows = $this->buildContestRankRows($contest);
                $lastRankRow = ! empty($rankRows) ? $rankRows[array_key_last($rankRows)] : null;
                $isJoined = $joinedAssignments->has((int) $assignment->id);
                $isSubmitted = $submittedAssignments->has((int) $assignment->id);
                $statusLabel = 'Open';
                $statusTone = 'success';
                $statusCopy = 'Competition details available for review.';

                if ($isSubmitted) {
                    $statusLabel = 'Submitted';
                    $statusTone = 'success';
                    $statusCopy = 'Your exam submission is already recorded.';
                } elseif ($assignment->resultdate && $today >= $assignment->resultdate->format('Y-m-d')) {
                    $statusLabel = 'Result Live';
                    $statusTone = 'success';
                    $statusCopy = 'Result date is active for this competition.';
                } elseif ($assignment->answersheetdate && $today >= $assignment->answersheetdate->format('Y-m-d')) {
                    $statusLabel = 'Answer Sheet';
                    $statusTone = 'secondary';
                    $statusCopy = 'Answer sheet date is active for this competition.';
                } elseif ($assignment->examdate && $today === $assignment->examdate->format('Y-m-d') && $this->isAssignmentExamLive($assignment)) {
                    $statusLabel = 'Exam Live';
                    $statusTone = 'success';
                    $statusCopy = 'Exam window is currently live.';
                } elseif ($assignment->startdate && $today < $assignment->startdate->format('Y-m-d')) {
                    $statusLabel = 'Upcoming';
                    $statusTone = 'secondary';
                    $statusCopy = 'Registration will open soon.';
                } elseif ($assignment->enddate && $today > $assignment->enddate->format('Y-m-d')) {
                    $statusLabel = 'Closed';
                    $statusTone = 'danger';
                    $statusCopy = $isJoined
                        ? 'You joined this competition earlier, but the registration window is closed now.'
                        : 'Registration window is closed for this competition.';
                } elseif ($isJoined) {
                    $statusLabel = 'Joined';
                    $statusTone = 'warning';
                    $statusCopy = 'You have already joined this competition.';
                }

                return [
                    'assignment' => $assignment,
                    'contest' => $contest,
                    'status_label' => $statusLabel,
                    'status_tone' => $statusTone,
                    'status_copy' => $statusCopy,
                    'is_joined' => $isJoined,
                    'is_submitted' => $isSubmitted,
                    'first_prize' => $rankRows[0]['prize_amount'] ?? 0,
                    'last_rank' => $lastRankRow['end_rank'] ?? null,
                    'detail_url' => route('contestdetails', $this->contestDetailsRouteParams($contest->id, (int) $assignment->id)),
                ];
            })
            ->filter()
            ->values();
    }

    private function buildContestDetailsData(MatchContest $contest, ?CompetitionAssignment $assignment = null): array
    {
        $rankRows = $this->buildContestRankRows($contest);
        $latestGameplay = null;
        $userAnswer = null;
        $showAlreadyJoined = false;
        $showJoinButton = false;
        $showWalletButton = false;
        $canStartExam = false;
        $answersheetAvailable = false;
        $resultAvailable = false;
        $joinDisabledReason = null;
        $examStatusMessage = null;
        $walletAmount = Auth::check() ? $this->currentStudentWalletAmount(Auth::id()) : 0;
        $walletShortfall = 0.0;

        $assignment ??= CompetitionAssignment::query()
            ->where('compitetionid', $contest->id)
            ->orderByDesc('id')
            ->first();

        $joinedCount = $assignment
            ? GameplayHistory::query()->where('assignquestionid', $assignment->id)->count()
            : GameplayHistory::query()->where('contestid', $contest->id)->count();
        $contestSeat = max(0, (int) $contest->contestseat);
        $joinedPercent = $contestSeat > 0 ? round(($joinedCount / $contestSeat) * 100, 2) : 0;
        $seatAvailable = $this->isCompetitionSeatAvailable($contest, $joinedCount);

        if ($assignment) {
            $allowedEntries = max(1, (int) $contest->userentery);
            $joinedEntries = GameplayHistory::query()
                ->where('assignquestionid', $assignment->id)
                ->where('userid', Auth::id())
                ->orderByDesc('id')
                ->get();

            $showAlreadyJoined = $joinedEntries->count() >= $allowedEntries;

            if (! $showAlreadyJoined) {
                $joinDisabledReason = $this->joinWindowStatusMessage($assignment);

                if (! $joinDisabledReason && ! $seatAvailable) {
                    $joinDisabledReason = 'All available seats are already filled.';
                }

                $walletShortfall = max(0, (float) $contest->joinamt - $walletAmount);

                if (! $joinDisabledReason && $walletShortfall > 0) {
                    $joinDisabledReason = 'Add wallet balance before joining this competition.';
                    $showWalletButton = true;
                }

                $showJoinButton = $joinDisabledReason === null;
            }

            $latestGameplay = GameplayHistory::query()
                ->where('assignquestionid', $assignment->id)
                ->where('userid', Auth::id())
                ->orderByDesc('id')
                ->first();

            if ($latestGameplay) {
                $userAnswer = UserAnswerDetail::query()
                    ->where('competitionassignid', $assignment->id)
                    ->where('createdby', Auth::id())
                    ->orderByDesc('id')
                    ->first();

                if ($userAnswer) {
                    $answersheetAvailable = $assignment->answersheetdate
                        && now()->toDateString() >= $assignment->answersheetdate->format('Y-m-d');
                    $resultAvailable = $assignment->resultdate
                        && now()->toDateString() >= $assignment->resultdate->format('Y-m-d');
                } else {
                    $canStartExam = $this->isAssignmentExamLive($assignment);

                    if (! $canStartExam) {
                        if ($latestGameplay && $assignment->examdate && now()->toDateString() > $assignment->examdate->format('Y-m-d')) {
                            $examStatusMessage = 'You joined this competition earlier, but no final exam submission was recorded before the exam window closed.';
                        } else {
                            $examStatusMessage = $this->examWindowStatusMessage($assignment);
                        }
                    }
                }
            }
        }

        $lastRankRow = ! empty($rankRows) ? $rankRows[array_key_last($rankRows)] : null;

        return [
            'assignment' => $assignment,
            'remaining_seat' => max(0, $contestSeat - $joinedCount),
            'joined_percent' => $joinedPercent,
            'first_prize' => $rankRows[0]['prize_amount'] ?? 0,
            'last_rank' => $lastRankRow['end_rank'] ?? null,
            'top_rank_rows' => array_slice($rankRows, 0, 3),
            'other_rank_rows' => array_slice($rankRows, 3),
            'show_join_button' => (bool) ($assignment && $showJoinButton),
            'show_already_joined' => (bool) ($assignment && $showAlreadyJoined),
            'show_wallet_button' => (bool) ($assignment && $showWalletButton),
            'join_url' => $assignment ? route('competitionjoin', ['id' => $assignment->id]) : null,
            'wallet_url' => route('walletrecharge'),
            'has_gameplay' => (bool) $latestGameplay,
            'has_submitted_answer' => (bool) $userAnswer,
            'answersheet_available' => $answersheetAvailable,
            'result_available' => $resultAvailable,
            'can_start_exam' => $canStartExam,
            'join_disabled_reason' => $joinDisabledReason,
            'exam_status_message' => $examStatusMessage,
            'wallet_amount' => $walletAmount,
            'wallet_shortfall' => $walletShortfall,
            'seat_available' => $seatAvailable,
            'answer_sheet_url' => $assignment ? route('examsanswersheet', ['id' => $assignment->id]) : null,
            'result_url' => $assignment ? route('examsresultt', ['id' => $assignment->id]) : null,
            'exam_start_url' => $assignment ? route('examstart', ['id' => $assignment->id]) : null,
            'answer_sheet_date_display' => $assignment && $assignment->answersheetdate
                ? $assignment->answersheetdate->format('d-m-Y')
                : null,
            'result_date_display' => $assignment && $assignment->resultdate
                ? $assignment->resultdate->format('d-m-Y')
                : null,
            'exam_date_display' => $assignment && $assignment->examdate
                ? $assignment->examdate->format('d-m-Y')
                : null,
            'exam_end_time_display' => $assignment && $assignment->examendtime
                ? date('h:i A', strtotime((string) $assignment->examendtime))
                : null,
        ];
    }

    private function maskMobileNumber(?string $mobile): string
    {
        $mobile = preg_replace('/\D+/', '', (string) $mobile) ?? '';

        if (strlen($mobile) !== 10) {
            return $mobile;
        }

        return substr($mobile, 0, 2) . 'XXXXXX' . substr($mobile, -2);
    }

    private function decorateWalletHistories($histories)
    {
        return $histories->map(function (WalletHistory $history) {
            $history->status_label = match ((int) $history->status) {
                1 => 'Added',
                2 => 'Pending',
                3 => 'Cancelled',
                default => 'Unknown',
            };

            return $history;
        });
    }

    private function decorateWithdrawHistories($histories)
    {
        return $histories->map(function (WithdrawHistory $history) {
            $history->status_label = match ((int) $history->status) {
                1 => 'Success',
                2 => 'Pending',
                3 => 'Cancelled',
                default => 'Unknown',
            };
            $history->status_tone = match ((int) $history->status) {
                1 => 'success',
                2 => 'warning',
                3 => 'danger',
                default => 'secondary',
            };

            return $history;
        });
    }

    private function buildScholarshipResultCards(object $studentsprofile): array
    {
        $submittedAssignmentIds = UserAnswerDetail::query()
            ->where('createdby', Auth::id())
            ->pluck('competitionassignid')
            ->filter()
            ->map(fn ($assignmentId) => (int) $assignmentId)
            ->unique()
            ->values();

        if ($submittedAssignmentIds->isEmpty()) {
            return [];
        }

        $assignments = CompetitionAssignment::query()
            ->with('contest')
            ->when(
                $studentsprofile->classid,
                fn ($query) => $query->where('groupclassid', $studentsprofile->classid),
                fn ($query) => $query->whereRaw('1 = 0')
            )
            ->whereIn('id', $submittedAssignmentIds->all())
            ->whereNotNull('resultdate')
            ->whereDate('resultdate', '<=', now()->toDateString())
            ->orderBy('resultdate', 'DESC')
            ->orderBy('startdate', 'ASC')
            ->get();

        $joinedCounts = GameplayHistory::query()
            ->select('assignquestionid', DB::raw('COUNT(*) as total'))
            ->whereIn('assignquestionid', $assignments->pluck('id')->all())
            ->groupBy('assignquestionid')
            ->pluck('total', 'assignquestionid');

        return $assignments
            ->map(function (CompetitionAssignment $assignment) use ($joinedCounts) {
                $contest = $assignment->contest;

                if (! $contest) {
                    return null;
                }

                $rankRows = $this->buildContestRankRows($contest);
                $lastRankRow = ! empty($rankRows) ? $rankRows[array_key_last($rankRows)] : null;
                $joinedCount = (int) ($joinedCounts[$assignment->id] ?? 0);
                $contestSeat = max(0, (int) $contest->contestseat);

                return [
                    'assignment' => $assignment,
                    'contest' => $contest,
                    'detail_url' => route('myexamresultdetails', ['id' => $assignment->id]),
                    'remaining_seat' => max(0, $contestSeat - $joinedCount),
                    'first_prize' => $rankRows[0]['prize_amount'] ?? 0,
                    'last_rank' => $lastRankRow['end_rank'] ?? null,
                ];
            })
            ->filter()
            ->values()
            ->all();
    }

    private function buildWithdrawPageData(int $userId): array
    {
        $walletAmount = (float) WalletUser::query()->where('userid', $userId)->sum('walletamount');
        $totalWithdrawn = (float) WithdrawHistory::query()->where('createdby', $userId)->sum('withdrawamt');
        $totalWinning = (float) WinningHistory::query()->where('userid', $userId)->sum('useramount');
        $availableWinningAmount = max(0, $totalWinning - $totalWithdrawn);

        return [
            'wallet_amount' => $walletAmount,
            'total_withdrawn' => $totalWithdrawn,
            'total_winning' => $totalWinning,
            'available_winning_amount' => $availableWinningAmount,
        ];
    }

    private function buildScoringEntries($entries)
    {
        $winningHistories = WinningHistory::query()
            ->where('userid', Auth::id())
            ->orderByDesc('id')
            ->get()
            ->keyBy('competitionid');

        return $entries->through(function (GameplayHistory $history) use ($winningHistories) {
            $winning = $winningHistories->get($history->contestid);
            $history->winning_rank = $winning?->rank ?? '-';
            $history->winning_amount = (float) ($winning?->useramount ?? 0);

            return $history;
        });
    }

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

        return array_values(array_filter(
            array_map(
                static fn (string $item): int => (int) trim($item),
                explode(',', $value)
            ),
            static fn (int $id): bool => $id > 0
        ));
    }

    private function examDurationMinutes(): int
    {
        // Preserve the legacy live-exam duration that was used in the old working flow.
        return 25;
    }

    private function examActiveQuestionSetSessionKey(int $assignmentId): string
    {
        return 'exam.active_question_sets.'.$assignmentId;
    }

    private function examStartedAtSessionKey(int $assignmentId): string
    {
        return 'exam.started_at.'.$assignmentId;
    }

    private function clearExamSession(int $assignmentId): void
    {
        session()->forget([
            $this->examActiveQuestionSetSessionKey($assignmentId),
            $this->examStartedAtSessionKey($assignmentId),
        ]);
    }

    private function hasJoinedCompetitionAssignment(int $assignmentId): bool
    {
        return GameplayHistory::query()
            ->where('userid', Auth::id())
            ->where('assignquestionid', $assignmentId)
            ->exists();
    }

    private function hasSubmittedCompetitionAssignment(int $assignmentId): bool
    {
        return UserAnswerDetail::query()
            ->where('createdby', Auth::id())
            ->where('competitionassignid', $assignmentId)
            ->exists();
    }

    private function studentOwnsAttachment(?int $attachmentId): bool
    {
        if (! $attachmentId) {
            return false;
        }

        return Attachment::query()
            ->where('id', $attachmentId)
            ->where('userid', Auth::id())
            ->exists();
    }

    private function storeAttachmentFile(UploadedFile $file, int $userId): Attachment
    {
        $extension = strtolower($file->getClientOriginalExtension() ?: $file->extension() ?: 'jpg');
        $fileName = now()->format('Ymd_His').'_'.$userId.'_'.Str::random(12).'.'.$extension;
        $relativePath = 'images/'.$fileName;
        $targetDirectory = base_path('files/images');

        File::ensureDirectoryExists($targetDirectory);
        $file->move($targetDirectory, $fileName);

        return Attachment::query()->create([
            'att_name' => $fileName,
            'att_slug' => $fileName,
            'att_url' => $relativePath,
            'att_date' => now(),
            'userid' => $userId,
        ]);
    }

    private function resolveAssignedQuestionSetup(CompetitionAssignment $assignment, ?int $questionSetId): ?QuestionSetup
    {
        if (! $questionSetId) {
            return null;
        }

        if (! in_array($questionSetId, $this->parseLegacyIdList((string) $assignment->questionsetid), true)) {
            return null;
        }

        return QuestionSetup::query()->find($questionSetId);
    }

    private function loadQuestionBanks(QuestionSetup $questionsetup): array
    {
        return [
            'questions_general' => QuestionManagement::query()->find($questionsetup->questionsetgkid),
            'questions_science' => QuestionManagement::query()->find($questionsetup->questionsetscienceid),
            'questions_hindi' => QuestionManagement::query()->find($questionsetup->questionsethindiid),
            'questions_english' => QuestionManagement::query()->find($questionsetup->questionsetenglishid),
            'questions_maths' => QuestionManagement::query()->find($questionsetup->questionsetmathsid),
        ];
    }

    private function examSubjectDefinitions(): array
    {
        return [
            [
                'key' => 'gk',
                'label' => 'G.K.',
                'title' => 'General Knowledge',
                'bank_key' => 'questions_general',
                'palette_start' => 0,
                'submission_start' => 0,
                'supports_hindi' => true,
                'user_answer_field' => 'gkuseranswer',
                'correct_answer_field' => 'gkcorrectanswer',
            ],
            [
                'key' => 'science',
                'label' => 'Science',
                'title' => 'Science',
                'bank_key' => 'questions_science',
                'palette_start' => 10,
                'submission_start' => 11,
                'supports_hindi' => true,
                'user_answer_field' => 'scienceuseranswer',
                'correct_answer_field' => 'sciencecorrectanswer',
            ],
            [
                'key' => 'hindi',
                'label' => 'Hindi',
                'title' => 'Hindi',
                'bank_key' => 'questions_hindi',
                'palette_start' => 20,
                'submission_start' => 21,
                'supports_hindi' => false,
                'user_answer_field' => 'hindiuseranswer',
                'correct_answer_field' => 'hindicorrectanswer',
            ],
            [
                'key' => 'english',
                'label' => 'English',
                'title' => 'English',
                'bank_key' => 'questions_english',
                'palette_start' => 30,
                'submission_start' => 31,
                'supports_hindi' => false,
                'user_answer_field' => 'englishuseranswer',
                'correct_answer_field' => 'englishcorrectanswer',
            ],
            [
                'key' => 'maths',
                'label' => 'Maths',
                'title' => 'Mathematics',
                'bank_key' => 'questions_maths',
                'palette_start' => 40,
                'submission_start' => 41,
                'supports_hindi' => true,
                'user_answer_field' => 'mathsusersanswer',
                'correct_answer_field' => 'mathscorrectanswer',
            ],
        ];
    }

    private function buildExamSections(QuestionSetup $questionsetup, ?UserAnswerDetail $userAnswerDetail = null): array
    {
        $questionBanks = $this->loadQuestionBanks($questionsetup);
        $sections = [];
        $displayNumber = 1;

        foreach ($this->examSubjectDefinitions() as $definition) {
            $bank = $questionBanks[$definition['bank_key']] ?? null;
            $questions = LegacyJson::toArray($bank?->questionlist);
            $questionHindi = LegacyJson::toArray($bank?->questionhindi);
            $firstOptions = LegacyJson::toArray($bank?->questionobjectfirst);
            $secondOptions = LegacyJson::toArray($bank?->questionobjectsecond);
            $thirdOptions = LegacyJson::toArray($bank?->questionobjectthird);
            $fourthOptions = LegacyJson::toArray($bank?->questionobjectfourth);
            $firstOptionsHindi = LegacyJson::toArray($bank?->questionobjectfirsthindi);
            $secondOptionsHindi = LegacyJson::toArray($bank?->questionobjectsecondhindi);
            $thirdOptionsHindi = LegacyJson::toArray($bank?->questionobjectthirdhindi);
            $fourthOptionsHindi = LegacyJson::toArray($bank?->questionobjectfourthhindi);
            $userAnswers = $userAnswerDetail
                ? LegacyJson::toArray($userAnswerDetail->{$definition['user_answer_field']})
                : [];
            $correctAnswers = $userAnswerDetail
                ? LegacyJson::toArray($userAnswerDetail->{$definition['correct_answer_field']})
                : [];
            $sectionQuestions = [];

            foreach ($questions as $localIndex => $questionText) {
                $normalizedPrompt = trim((string) $questionText);

                if ($normalizedPrompt === '') {
                    continue;
                }

                $submissionKey = $definition['submission_start'] + $localIndex;
                $paletteIndex = $definition['palette_start'] + $localIndex;
                $userAnswer = $userAnswers[$localIndex] ?? null;
                $correctAnswer = $correctAnswers[$localIndex] ?? null;
                $status = $userAnswer === null || $userAnswer === ''
                    ? 'unanswered'
                    : (($correctAnswer !== null && $userAnswer === $correctAnswer) ? 'correct' : 'wrong');

                $sectionQuestions[] = [
                    'global_number' => $displayNumber,
                    'palette_index' => $paletteIndex,
                    'submission_key' => $submissionKey,
                    'prompt' => $normalizedPrompt,
                    'prompt_hindi' => $definition['supports_hindi']
                        ? ($this->normalizeLegacyExamText($questionHindi[$localIndex] ?? null))
                        : null,
                    'options' => [
                        [
                            'key' => 'A',
                            'english' => $this->normalizeLegacyExamText($firstOptions[$localIndex] ?? null),
                            'hindi' => $definition['supports_hindi']
                                ? ($this->normalizeLegacyExamText($firstOptionsHindi[$localIndex] ?? null))
                                : null,
                        ],
                        [
                            'key' => 'B',
                            'english' => $this->normalizeLegacyExamText($secondOptions[$localIndex] ?? null),
                            'hindi' => $definition['supports_hindi']
                                ? ($this->normalizeLegacyExamText($secondOptionsHindi[$localIndex] ?? null))
                                : null,
                        ],
                        [
                            'key' => 'C',
                            'english' => $this->normalizeLegacyExamText($thirdOptions[$localIndex] ?? null),
                            'hindi' => $definition['supports_hindi']
                                ? ($this->normalizeLegacyExamText($thirdOptionsHindi[$localIndex] ?? null))
                                : null,
                        ],
                        [
                            'key' => 'D',
                            'english' => $this->normalizeLegacyExamText($fourthOptions[$localIndex] ?? null),
                            'hindi' => $definition['supports_hindi']
                                ? ($this->normalizeLegacyExamText($fourthOptionsHindi[$localIndex] ?? null))
                                : null,
                        ],
                    ],
                    'user_answer' => $userAnswer,
                    'correct_answer' => $correctAnswer,
                    'status' => $status,
                ];

                $displayNumber++;
            }

            $sections[] = [
                'key' => $definition['key'],
                'label' => $definition['label'],
                'title' => $definition['title'],
                'supports_hindi' => $definition['supports_hindi'],
                'palette_start' => $definition['palette_start'],
                'count' => count($sectionQuestions),
                'questions' => $sectionQuestions,
            ];
        }

        return $sections;
    }

    private function normalizeLegacyExamText(mixed $value): ?string
    {
        $normalized = trim((string) $value);

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

    private function buildExamCountdownFromStart(string $examStartTime): string
    {
        $startDateTime = new \DateTime(date('Y-m-d').' '.$examStartTime);
        $currentDateTime = new \DateTime(date('Y-m-d H:i:s'));
        $diff = $startDateTime->diff($currentDateTime);
        $elapsedSeconds = ((int) $diff->i * 60) + (int) $diff->s;
        $remainingSeconds = max(0, ($this->examDurationMinutes() * 60) - $elapsedSeconds);

        return sprintf('%02d:%02d', intdiv($remainingSeconds, 60), $remainingSeconds % 60);
    }

    private function buildExamAnswerMap(QuestionSetup $questionsetup): array
    {
        $questionBanks = $this->loadQuestionBanks($questionsetup);

        return [
            'gk' => LegacyJson::toArray($questionBanks['questions_general']?->questionobjectanswer),
            'science' => LegacyJson::toArray($questionBanks['questions_science']?->questionobjectanswer),
            'hindi' => LegacyJson::toArray($questionBanks['questions_hindi']?->questionobjectanswer),
            'english' => LegacyJson::toArray($questionBanks['questions_english']?->questionobjectanswer),
            'maths' => LegacyJson::toArray($questionBanks['questions_maths']?->questionobjectanswer),
        ];
    }

    private function calculateSubjectResult(array $correctAnswers, array $userOptions, int $userStartIndex): array
    {
        $userAnswers = [];
        $correctAnswerList = [];
        $correctMarks = [];
        $wrongMarks = [];

        for ($offset = 0; $offset < 10; $offset++) {
            if (! array_key_exists($offset, $correctAnswers)) {
                continue;
            }

            $correctAnswerList[$offset] = $correctAnswers[$offset];
            $userKey = $userStartIndex + $offset;

            if (! isset($userOptions[$userKey])) {
                $userAnswers[$offset] = null;
                continue;
            }

            $selectedOption = $userOptions[$userKey];
            $userAnswers[$offset] = $selectedOption;

            if ($selectedOption === $correctAnswers[$offset]) {
                $correctMarks[$userKey] = 1;
            } else {
                $wrongMarks[$userKey] = 0.25;
            }
        }

        $marks = array_sum($correctMarks) - array_sum($wrongMarks);

        return [
            'user_answers' => $userAnswers,
            'correct_answers' => $correctAnswerList,
            'marks' => $marks,
            'percentage' => $marks > 0 ? round($marks / 10 * 100, 2) : 0,
        ];
    }

    private function buildExamResultPageData(int $assignmentId): array
    {
        $userAnswerDetail = UserAnswerDetail::query()
            ->where('createdby', Auth::id())
            ->where('competitionassignid', $assignmentId)
            ->orderByDesc('id')
            ->first();

        $leaderboardQuery = UserAnswerDetail::query()
            ->with('user')
            ->where('competitionassignid', $assignmentId)
            ->where('status', 1)
            ->orderByDesc('totalpercentage')
            ->orderBy('id');

        $rankedEntries = $leaderboardQuery->get()->values()->map(function (UserAnswerDetail $entry, int $index) {
            $entry->display_rank = $index + 1;
            $entry->masked_mobile = $this->maskMobileNumber($entry->user?->mobileno);

            return $entry;
        });

        $leaderboardPage = $leaderboardQuery->paginate(20);
        $leaderboardPage->getCollection()->transform(function (UserAnswerDetail $entry, int $index) use ($leaderboardPage) {
            $entry->display_rank = (($leaderboardPage->currentPage() - 1) * $leaderboardPage->perPage()) + $index + 1;
            $entry->masked_mobile = $this->maskMobileNumber($entry->user?->mobileno);

            return $entry;
        });

        return [
            'user_answer_detail' => $userAnswerDetail,
            'qualified_entries' => $rankedEntries,
            'leaderboard_page' => $leaderboardPage,
            'subject_rows' => $userAnswerDetail ? [
                ['label' => 'G.K.', 'marks' => $userAnswerDetail->gkmarks, 'percentage' => $userAnswerDetail->gkpercentage],
                ['label' => 'Science', 'marks' => $userAnswerDetail->sciencemarks, 'percentage' => $userAnswerDetail->sciencepercentage],
                ['label' => 'Hindi', 'marks' => $userAnswerDetail->hindimarks, 'percentage' => $userAnswerDetail->hindipercentage],
                ['label' => 'English', 'marks' => $userAnswerDetail->englishmarks, 'percentage' => $userAnswerDetail->englishpercentage],
                ['label' => 'Maths', 'marks' => $userAnswerDetail->mathsmarks, 'percentage' => $userAnswerDetail->mathspercentage],
            ] : [],
        ];
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(): View|RedirectResponse
    {
        if (Auth::check()) {
            return $this->redirectAuthenticatedPortalUser();
        }

        $landingStats = [
            ['value' => 0, 'label' => 'Competitions'],
            ['value' => 0, 'label' => 'Students'],
            ['value' => 0, 'label' => 'Exam Sets'],
        ];

        try {
            $landingStats = $this->landingPageStats();
        } catch (Throwable) {
            // Keep the landing page available even if the live schema is still being aligned.
        }

        $pageLinks = collect();

        try {
            if (
                Schema::hasTable('pagedetails')
                && Schema::hasColumn('pagedetails', 'pagename')
                && Schema::hasColumn('pagedetails', 'pageslug')
            ) {
                $pageLinksQuery = PageDetail::query()->whereNotNull('pageslug');

                if (Schema::hasColumn('pagedetails', 'pageorder')) {
                    $pageLinksQuery
                        ->orderByRaw('CASE WHEN pageorder IS NULL THEN 1 ELSE 0 END')
                        ->orderBy('pageorder');
                }

                $pageLinks = $pageLinksQuery
                    ->orderBy('pagename')
                    ->limit(4)
                    ->get(['pagename', 'pageslug']);
            }
        } catch (Throwable) {
            // Ignore partial legacy schema mismatches on the public landing page.
        }

        return view('welcome', [
            'landingStats' => $landingStats,
            'subjectHighlights' => ['Hindi', 'English', 'Math', 'G.K.', 'Science'],
            'pageLinks' => $pageLinks,
        ]);
    }

    public function competitionlist(): View|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }

        $studentsprofile = $this->currentStudentProfile();
        $bannerimages = BannerImage::query()
            ->orderByDesc('id')
            ->get()
            ->map(function (BannerImage $bannerImage) {
                $bannerImage->image_url = $this->attachmentUrl(
                    (int) $bannerImage->bannerimg,
                    $this->frontendAssetUrl('images/logo.png')
                );

                return $bannerImage;
            });
        $competitionSections = $this->buildCompetitionSections($studentsprofile);
        $competitionTimeline = $this->buildStudentCompetitionTimeline($studentsprofile);
        $walletBalance = $this->currentStudentWalletAmount(Auth::id());

        return view('front.competitionlist')
            ->with('studentsprofile', $studentsprofile)
            ->with('bannerimages', $bannerimages)
            ->with('competitionSections', $competitionSections)
            ->with('competitionTimeline', $competitionTimeline)
            ->with('walletBalance', $walletBalance);
    }

    public function scholershipresult(): View|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }

        $studentsprofile = $this->currentStudentProfile();
        $resultCards = $this->buildScholarshipResultCards($studentsprofile);

        return view('front.scholershipresult')
            ->with('studentsprofile', $studentsprofile)
            ->with('resultCards', $resultCards);
    }


    


    public function contestlist($id): View|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }   

        Session::flash('message', 'This old contest route has been moved to the current competition dashboard.');

        return redirect()->route('competitionlist');
    }
    
    public function userpasswordchange(): View|RedirectResponse
    {

       //// echo Auth::user()->id; exit;
        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }

        $studentsprofile = $this->currentStudentProfile();

        return view('front.passwordchange')->with('studentsprofile', $studentsprofile);
    }
 

    
    


    public function walletrecharge(): View|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }   

        $user = User::query()->findOrFail(Auth::id());
        $walletamt = $this->currentStudentWalletAmount($user->id);
        [$rechargeAmounts, $firstAmount] = $this->buildWalletRechargeAmounts($user);

        return view('front.walletrecharge')
            ->with('walletamt', $walletamt)
            ->with('rechargeAmounts', $rechargeAmounts)
            ->with('firstAmount', $firstAmount);
    }

    public function contestdetails(Request $request, $id): View|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }   
             
        $matchcobntests = MatchContest::query()->findOrFail($id);
        $assignment = CompetitionAssignment::query()
            ->when(
                (int) $request->query('assignment', 0) > 0,
                fn ($query) => $query->whereKey((int) $request->query('assignment'))
            )
            ->where('compitetionid', $matchcobntests->id)
            ->orderByDesc('id')
            ->first();
        $contestPage = $this->buildContestDetailsData($matchcobntests, $assignment);

        return view('front.contestdetails')
            ->with('matchcobntests', $matchcobntests)
            ->with('contestPage', $contestPage);
    }

    public function uploadStudentAttachment(StoreStudentAttachmentRequest $request): JsonResponse|RedirectResponse
    {
        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }

        $validated = $request->validated();

        $attachment = $this->storeAttachmentFile($validated['userImage'], Auth::id());

        return response()->json([
            'attachment_id' => $attachment->id,
            'preview_url' => $this->storedFileUrl($attachment->att_url),
            'message' => 'Upload successful.',
        ]);
    }

    public function walletamount($amt): View|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }   
             

          $walletamt = $this->currentStudentWalletAmount(Auth::id());
          $amt = max(0, (float) $amt);

          //// echo '<pre>'; print_r($matchesdetails); echo '</pre>'; exit; 
           
        return view('front.walletamount')->with('walletamt',$walletamt)->with('amt',$amt);
    }


    

    public function walletamountsave(StoreWalletAmountRequest $request)
    {
        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }

        $validated = $request->validated();
        $user = User::query()->findOrFail(Auth::id());

        if (! empty($validated['photoid']) && ! $this->studentOwnsAttachment((int) $validated['photoid'])) {
            return back()
                ->withErrors(['photoid' => 'Invalid wallet proof selected. Please upload again.'])
                ->withInput();
        }

        WalletHistory::query()->create([
            'username' => $this->studentDisplayName($user),
            'userid' => $user->id,
            'addamount' => $validated['rechargeamt'],
            'transectionid' => $validated['transctionid'],
            'transectionimg' => $validated['photoid'] ?? null,
            'status' => 2,
            'createdby' => $user->id,
            'createdtime' => now(),
        ]);
  
        Session::flash('sucmessage', "Successful,  Wallet Amount  has Added"); 
         
        /// return Redirect::back(); 

        return redirect()->route('competitionlist');
    } 

  
    public function pagesdetails($slug): View|RedirectResponse
    {
        $pagedetails = is_numeric($slug)
            ? PageDetail::query()->where('id', $slug)->firstOrFail()
            : PageDetail::query()->where('pageslug', $slug)->firstOrFail();

        if (! Auth::check()) {
            return view('front.pagesdetails-public')->with('pagedetails', $pagedetails);
        }

        return view('front.pagesdetails')->with('pagedetails',$pagedetails);
    }
     
    public function competitionjoin(Request $request, $id): View|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }   

        $user = User::query()->findOrFail(Auth::id());
        $contestquestions = CompetitionAssignment::query()
            ->with(['contest', 'board', 'group'])
            ->findOrFail($id);
        $joinAmount = (float) MatchContest::query()
            ->where('id', $contestquestions->compitetionid)
            ->value('joinamt');
        $contest = $contestquestions->contest;

        if (! $contest) {
            abort(404);
        }

        if ($request->isMethod('get')) {
            Session::flash('message', 'Please confirm the join request from the competition details page.');

            return redirect()->route('contestdetails', $this->contestDetailsRouteParams((int) $contestquestions->compitetionid, (int) $contestquestions->id));
        }

        if (! $this->isAssignmentJoinWindowOpen($contestquestions)) {
            Session::flash('message', $this->joinWindowStatusMessage($contestquestions) ?? 'Registration is not active for this competition.');

            return redirect()->route('contestdetails', $this->contestDetailsRouteParams((int) $contestquestions->compitetionid, (int) $contestquestions->id));
        }

        if (! $this->isCompetitionSeatAvailable(
            $contest,
            GameplayHistory::query()->where('assignquestionid', $contestquestions->id)->count()
        )) {
            Session::flash('message', 'All available seats are already filled for this competition.');

            return redirect()->route('contestdetails', $this->contestDetailsRouteParams((int) $contestquestions->compitetionid, (int) $contestquestions->id));
        }
        $joinResult = DB::transaction(function () use ($user, $contestquestions, $contest, $joinAmount) {
            $lockedContest = MatchContest::query()
                ->whereKey($contest->id)
                ->lockForUpdate()
                ->firstOrFail();

            $joinedCount = GameplayHistory::query()
                ->where('assignquestionid', $contestquestions->id)
                ->count();

            if (! $this->isCompetitionSeatAvailable($lockedContest, $joinedCount)) {
                return [
                    'status' => 'full',
                    'wallet_balance' => $this->currentStudentWalletAmount($user->id),
                ];
            }

            $existingGameplay = GameplayHistory::query()
                ->where('userid', $user->id)
                ->where('assignquestionid', $contestquestions->id)
                ->lockForUpdate()
                ->first();

            if ($existingGameplay) {
                return [
                    'status' => 'already_joined',
                    'wallet_balance' => $this->currentStudentWalletAmount($user->id),
                ];
            }

            $walletusers = WalletUser::query()
                ->where('userid', $user->id)
                ->lockForUpdate()
                ->first();

            if (! $walletusers) {
                $walletusers = WalletUser::query()->create([
                    'userid' => $user->id,
                    'username' => $this->studentDisplayName($user),
                    'walletamount' => 0,
                    'updatedtime' => now(),
                ]);

                $walletusers = WalletUser::query()
                    ->whereKey($walletusers->id)
                    ->lockForUpdate()
                    ->firstOrFail();
            }

            if ((float) $walletusers->walletamount < $joinAmount) {
                return [
                    'status' => 'insufficient_wallet',
                    'wallet_balance' => (float) $walletusers->walletamount,
                ];
            }

            $walletusers->update([
                'walletamount' => (float) $walletusers->walletamount - $joinAmount,
                'updatedtime' => now(),
            ]);

            GameplayHistory::query()->create([
                'userid' => $user->id,
                'username' => $user->name,
                'contestid' => $contestquestions->compitetionid,
                'questionsetid' => $contestquestions->questionsetid,
                'questionsetname' => $contestquestions->questiomnsetname,
                'contestname' => $contestquestions->compitetionname,
                'assignquestionid' => $contestquestions->id,
                'assignquestionname' => $contestquestions->compitetiontitle,
                'playedamount' => $joinAmount,
                'createtime' => now(),
            ]);

            return [
                'status' => 'joined',
                'wallet_balance' => (float) $walletusers->walletamount,
            ];
        });

        if ($joinResult['status'] === 'full') {
            Session::flash('message', 'All available seats are already filled for this competition.');

            return redirect()->route('contestdetails', $this->contestDetailsRouteParams((int) $contestquestions->compitetionid, (int) $contestquestions->id));
        }

        if ($joinResult['status'] === 'insufficient_wallet') {
            Session::flash('message', 'Insufficient wallet balance to join this competition.');

            return redirect()->route('contestdetails', $this->contestDetailsRouteParams((int) $contestquestions->compitetionid, (int) $contestquestions->id));
        }

        if ($joinResult['status'] === 'joined') {
            Session::flash('sucmessage', "Successful, Compitetion Exam has been joined by You ... ");
        } else {
            Session::flash('sucmessage', "Successful, Compitetion Exam have Joined Before ... ");
        }

        return view('front.competitionjoin')
            ->with('contestquestions', $contestquestions)
            ->with('joinedContest', $contest)
            ->with('walletBalance', (float) ($joinResult['wallet_balance'] ?? $this->currentStudentWalletAmount($user->id)))
            ->with('joinSummary', [
                'competition_title' => $contest?->contesttitile ?: $contestquestions->compitetionname,
                'class_name' => $contestquestions->groupclassname ?: 'Not assigned',
                'board_name' => $contestquestions->board?->showname ?: 'Board pattern not available',
                'join_amount' => (float) ($contest?->joinamt ?? $joinAmount),
                'result_date' => $contestquestions->resultdate?->format('d M Y'),
                'answer_sheet_date' => $contestquestions->answersheetdate?->format('d M Y'),
                'exam_date' => $contestquestions->examdate?->format('d M Y'),
                'exam_end_time' => $contestquestions->examendtime
                    ? date('h:i A', strtotime((string) $contestquestions->examendtime))
                    : null,
            ]);
    }


    

    public function saveuseranswersheet(Request $request)
    {
        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }

        $validated = $request->validate([
            'contestid' => ['nullable', 'integer'],
        ]);

        Session::flash('message', 'This old answer sheet flow is no longer active. Please use the current competition exam screens.');

        if (! empty($validated['contestid'])) {
            return redirect()->route('contestdetails', ['id' => (int) $validated['contestid']]);
        }

        return redirect()->route('competitionlist');
    } 
    
    
    public function gamehistory(): View|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }   
             
        $gameplayhistory = GameplayHistory::query()
            ->where('userid', Auth::id())
            ->orderByDesc('id')
            ->get();

        return view('front.gamehistory')->with('gameplayhistory',$gameplayhistory);
    }


    public function withdrawhistory(): View|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }   
             
        $withdrawhistory = $this->decorateWithdrawHistories(
            WithdrawHistory::query()->where('createdby', Auth::id())->orderByDesc('id')->get()
        );

        return view('front.withdrawhistory')->with('withdrawhistory',$withdrawhistory);
    }

    

    public function userwithdraw(): View|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }   
             
        $withdrawPage = $this->buildWithdrawPageData(Auth::id());

        return view('front.userwithdraw')->with('withdrawPage',$withdrawPage);
    }

    

    
    
    public function withdrawrequest(StoreWithdrawRequest $request)
    {
        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }

        $validated = $request->validated();
        $user = User::query()->findOrFail(Auth::id());
        $withdrawPage = $this->buildWithdrawPageData($user->id);
        $withdrawAmount = (float) $validated['withdrawamunt'];

        if ($withdrawAmount > (float) $withdrawPage['available_winning_amount']) {
            Session::flash('message', 'Sorry, withdraw amount is not sufficient.');

            return Redirect::back()->withInput();
        }

        WithdrawHistory::query()->create([
            'username' => $this->studentDisplayName($user),
            'paymenttype' => $validated['paymentwallets'],
            'mobilenumber' => $validated['mobilenumber'],
            'withdrawamt' => $withdrawAmount,
            'status' => 2,
            'createdby' => $user->id,
            'createdtime' => now(),
        ]);

        Session::flash('sucmessage', 'Successful, request has been sent');

        return Redirect::back();
    }
    
    
    
    public function editprofile(): View|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }   

        $usersdata = User::query()->findOrFail(Auth::id());
        $studentsprofile = $this->currentStudentProfile();
        $studentsgroup = StudentGroup::query()->orderByDesc('id')->get();
        $profileImageUrl = $this->buildProfileImageUrl($usersdata);

        return view('front.editprofile')
            ->with('usersdata',$usersdata)
            ->with('studentsprofile', $studentsprofile)
            ->with('studentsgroup', $studentsgroup)
            ->with('profileImageUrl', $profileImageUrl);
    }

    public function saveprofile(UpdateStudentProfileRequest $request)
    {
        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }

        $validated = $request->validated();
        $user = User::query()->findOrFail(Auth::id());
        $class = $this->parseCompoundValue($validated['questiongoupsclass']);

        $user->update([
            'name' => $validated['username'],
            'aadharcard' => $validated['aadharcardnumber'],
            'updated_at' => now(),
        ]);

        StudentProfile::query()->updateOrCreate(
            ['studentid' => $user->id],
            [
                'classid' => $class['id'],
                'classname' => $class['name'],
                'fathername' => $validated['fathername'],
                'mothername' => $validated['mothername'],
                'dateofbirth' => $validated['dateofbirth'],
                'srnumber' => $validated['srnumber'] ?? null,
                'studentupiid' => $validated['emailid'],
                'pancardnumber' => $validated['pancardnumber'],
                'bankaccountnumber' => $validated['bankaccountnumber'],
                'bankaccountholdername' => $validated['bankholdername'],
                'bankbranch' => $validated['bankbranchname'] ?? null,
                'bankifsccode' => $validated['bankifscocde'],
                'religion' => $validated['userreligion'],
                'updatetime' => now(),
            ]
        );
 
        
                Session::flash('sucmessage', "Successful, User Profile  has been Updated"); 

          //  $urlsectin = SITEURL.'contestdetails/'.$savedata['contestid'].'/'.$savedata['matchid'];

      //  return redirect()->to( $urlsectin);
         
        return Redirect::back(); 
    }
    
    public function profileimg(): View|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }   

        $usersdata = User::query()->findOrFail(Auth::id());
        $profileImageUrl = $this->buildProfileImageUrl($usersdata);

        return view('front.profileimg')
            ->with('usersdata', $usersdata)
            ->with('profileImageUrl', $profileImageUrl);
    }

    public function profileimagesave(UpdateStudentProfileImageRequest $request)
    {
        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }

        $validated = $request->validated();

        if (! $this->studentOwnsAttachment((int) $validated['photoid'])) {
            return back()->withErrors(['photoid' => 'Invalid profile image selected. Please upload again.']);
        }

        User::query()
            ->findOrFail(Auth::id())
            ->update([
                'profileimh' => (int) $validated['photoid'],
                'updated_at' => now(),
            ]);

        Session::flash('sucmessage', "Successful, User Profile Image  has been Updated");

        return Redirect::back();
    }

    

    public function wallethistory(): View|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }   
             
        $wallethistory = $this->decorateWalletHistories(
            WalletHistory::query()->where('userid', Auth::id())->orderByDesc('id')->get()
        );

        return view('front.wallethistory')->with('wallethistory',$wallethistory);
    }


    public function mobileverify(Request $request, $mobile)
    {
        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }

        if ($request->isMethod('get')) {
            Session::flash('message', 'Please request OTP from the secure profile screen.');

            return redirect()->route('editprofile');
        }

        $user = User::query()->findOrFail(Auth::id());
        $mobile = $user->mobileno;

        if (! $mobile) {
            Session::flash('message', 'Please update your mobile number first.');

            return redirect()->route('editprofile');
        }

        $this->issueStudentMobileVerificationOtp($user);

        Session::flash('sucmessage', "OTP has been Sent.."); 

        return redirect()->route('mobileotp');
         
        //  return Redirect::back(); 
    }

    public function mobileotp(): View|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }   
              
           
        return view('front.mobileotp');
    }


    public function savemobileotp(VerifyStudentOtpRequest $request)
    {
        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }

        $validated = $request->validated();
        $user = User::query()->findOrFail(Auth::id());

         if((string) $validated['mobileotp'] === (string) $user->otpnumber) {

            $user->update([
                'mobilevarification' => 1,
                'updated_at' => now(),
            ]);
            
      
                Session::flash('sucmessage', "Successful, Varification has been Completed"); 

          } else {

            Session::flash('message', "Enter Valid OTP Number"); 

          }

         return redirect()->route('editprofile');
         
        ///  return Redirect::back(); 
    }

    public function emailvarificarion(Request $request, $emailid)
    {
        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }

        if ($request->isMethod('get')) {
            Session::flash('message', 'Please request email verification code from the secure profile screen.');

            return redirect()->route('editprofile');
        }

        $user = User::query()->findOrFail(Auth::id());
        $emailid = $user->useremailid;

        if (! $emailid) {
            Session::flash('message', 'Please update your email ID first.');

            return redirect()->route('editprofile');
        }

        $this->issueStudentEmailVerificationOtp($user);

        Session::flash('sucmessage', "OTP has been Sent.."); 

         return redirect()->route('emailvarification');
         
        //  return Redirect::back(); 
    }

    public function emailvarification(): View|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }   
              
           
        return view('front.emailvarification');
    }

    public function saveemailcode(VerifyStudentOtpRequest $request)
    {
        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }

        $validated = $request->validated();
        $user = User::query()->findOrFail(Auth::id());
 
         if((string) $validated['mobileotp'] === (string) $user->emailotp) {

            $user->update([
                'emailvarify' => 1,
                'updated_at' => now(),
            ]);
            
      
                Session::flash('sucmessage', "Successful, Email Varification has been Completed"); 

          } else {

            Session::flash('message', "Enter Valid Code Number"); 

            return Redirect::back(); 

          }

         return redirect()->route('editprofile');
         
        ///
    }



    //////////////////
    // Exam Section
    ///////////////
      
    public function examstart($id): Response|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }

        $compitetionassignment = CompetitionAssignment::query()->findOrFail($id);

        if (! $this->hasJoinedCompetitionAssignment((int) $compitetionassignment->id)) {
            Session::flash('message', 'Please join this competition before starting the exam.');

            return redirect()->route('contestdetails', $this->contestDetailsRouteParams((int) $compitetionassignment->compitetionid, (int) $compitetionassignment->id));
        }

        if ($this->hasSubmittedCompetitionAssignment((int) $compitetionassignment->id)) {
            Session::flash('message', 'This exam has already been submitted.');

            return redirect()->route('contestdetails', $this->contestDetailsRouteParams((int) $compitetionassignment->compitetionid, (int) $compitetionassignment->id));
        }

        if (! $this->isAssignmentExamLive($compitetionassignment)) {
            Session::flash('message', $this->examWindowStatusMessage($compitetionassignment));

            return redirect()->route('contestdetails', $this->contestDetailsRouteParams((int) $compitetionassignment->compitetionid, (int) $compitetionassignment->id));
        }

        return $this->noStoreViewResponse('front.examstart', [
            'compitetionassignment' => $compitetionassignment,
            'availableQuestionSetIds' => $this->parseLegacyIdList((string) $compitetionassignment->questionsetid),
            'examDurationMinutes' => $this->examDurationMinutes(),
        ]);
    }

    public function examslive(Request $request, $id): Response|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }   

        $compitetionassignment = CompetitionAssignment::query()->findOrFail($id);

        if (! $this->hasJoinedCompetitionAssignment((int) $compitetionassignment->id)) {
            Session::flash('message', 'Please join this competition before starting the exam.');

            return redirect()->route('contestdetails', $this->contestDetailsRouteParams((int) $compitetionassignment->compitetionid, (int) $compitetionassignment->id));
        }

        if ($this->hasSubmittedCompetitionAssignment((int) $compitetionassignment->id)) {
            Session::flash('message', 'This exam has already been submitted.');

            return redirect()->route('contestdetails', $this->contestDetailsRouteParams((int) $compitetionassignment->compitetionid, (int) $compitetionassignment->id));
        }

        if (! $this->isAssignmentExamLive($compitetionassignment)) {
            $this->clearExamSession((int) $compitetionassignment->id);
            Session::flash('message', $this->examWindowStatusMessage($compitetionassignment));

            return redirect()->route('contestdetails', $this->contestDetailsRouteParams((int) $compitetionassignment->compitetionid, (int) $compitetionassignment->id));
        }

        $activeSessionKey = $this->examActiveQuestionSetSessionKey((int) $compitetionassignment->id);
        $activeQuestionSetId = (int) session($activeSessionKey, 0);
        $requestedQuestionSetId = (int) $request->query('questionid', 0);
        $questionSetId = $activeQuestionSetId ?: $requestedQuestionSetId;
        $questionsetup = $this->resolveAssignedQuestionSetup($compitetionassignment, $questionSetId);

        if (! $questionsetup) {
            $this->clearExamSession((int) $compitetionassignment->id);
            Session::flash('message', 'Invalid exam session. Please start the exam again.');

            return redirect()->route('examstart', ['id' => $compitetionassignment->id]);
        }

        if (! $activeQuestionSetId) {
            session()->put($activeSessionKey, (int) $questionsetup->id);
            session()->put($this->examStartedAtSessionKey((int) $compitetionassignment->id), now()->format('H:i:s'));
        }

        $examStartTime = (string) session(
            $this->examStartedAtSessionKey((int) $compitetionassignment->id),
            now()->format('H:i:s')
        );

        return $this->noStoreViewResponse('front.examslive', [
            'compitetionassignment' => $compitetionassignment,
            'questionsetup' => $questionsetup,
            'examSections' => $this->buildExamSections($questionsetup),
            'examCountdown' => $this->buildExamCountdownFromStart($examStartTime),
        ]);
    }


     public function examsanswersheet($id): Response|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }   

        $compitetionassignment = CompetitionAssignment::query()->findOrFail($id);
        $useranswerdetails = UserAnswerDetail::query()
            ->where('createdby', Auth::id())
            ->where('competitionassignid', $id)
            ->latest('id')
            ->first();

        if (! $useranswerdetails) {
            Session::flash('message', 'Answer sheet is not available yet.');

            return redirect()->route('contestdetails', $this->contestDetailsRouteParams((int) $compitetionassignment->compitetionid, (int) $compitetionassignment->id));
        }

        $questionSetId = $this->parseLegacyIdList((string) $useranswerdetails->questionsetid)[0]
            ?? $this->parseLegacyIdList((string) $compitetionassignment->questionsetid)[0]
            ?? null;
        $questionsetup = $this->resolveAssignedQuestionSetup($compitetionassignment, $questionSetId);

        if (! $questionsetup) {
            Session::flash('message', 'Question set could not be loaded for this answer sheet.');

            return redirect()->route('contestdetails', $this->contestDetailsRouteParams((int) $compitetionassignment->compitetionid, (int) $compitetionassignment->id));
        }

        return $this->noStoreViewResponse('front.examsanswersheet', [
            'compitetionassignment' => $compitetionassignment,
            'questionsetup' => $questionsetup,
            'useranswerdetails' => $useranswerdetails,
            'examSections' => $this->buildExamSections($questionsetup, $useranswerdetails),
        ]);
    }

  public function examsresultt($id): Response|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }   
        $resultPage = $this->buildExamResultPageData((int) $id);

        return $this->noStoreViewResponse('front.examsresultt', [
            'resultPage' => $resultPage,
            'useranswerdetails' => $resultPage['user_answer_detail'],
            'leadreboard' => $resultPage['leaderboard_page'],
            'leaderboarduserrank' => $resultPage['qualified_entries'],
        ]);

     }
    

    
    public function savepaper(StoreExamSubmissionRequest $request)
    {
        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }

        $validated = $request->validated();

        $submissionResult = DB::transaction(function () use ($validated) {
            User::query()
                ->whereKey(Auth::id())
                ->lockForUpdate()
                ->firstOrFail();

            $compitetionassignment = CompetitionAssignment::query()->findOrFail($validated['competitionassignid']);

            if (! $this->hasJoinedCompetitionAssignment((int) $compitetionassignment->id)) {
                return [
                    'status' => 'not_joined',
                    'contest_id' => (int) $compitetionassignment->compitetionid,
                ];
            }

            $existingSubmission = UserAnswerDetail::query()
                ->where('createdby', Auth::id())
                ->where('competitionassignid', $compitetionassignment->id)
                ->lockForUpdate()
                ->first();

            if ($existingSubmission) {
                $this->clearExamSession((int) $compitetionassignment->id);

                return [
                    'status' => 'already_submitted',
                    'contest_id' => (int) $compitetionassignment->compitetionid,
                ];
            }

            if (! $this->isAssignmentExamLive($compitetionassignment)) {
                $this->clearExamSession((int) $compitetionassignment->id);

                return [
                    'status' => 'closed',
                    'contest_id' => (int) $compitetionassignment->compitetionid,
                    'message' => $this->examWindowStatusMessage($compitetionassignment),
                ];
            }

            $questionSetId = (int) session($this->examActiveQuestionSetSessionKey((int) $compitetionassignment->id), 0);
            $questionsetup = $this->resolveAssignedQuestionSetup($compitetionassignment, $questionSetId);

            if (! $questionsetup) {
                $this->clearExamSession((int) $compitetionassignment->id);

                return [
                    'status' => 'expired',
                    'assignment_id' => (int) $compitetionassignment->id,
                ];
            }

            $userOptions = $validated['useroption'] ?? [];
            $answerMap = $this->buildExamAnswerMap($questionsetup);
            $gkResult = $this->calculateSubjectResult($answerMap['gk'], $userOptions, 0);
            $scienceResult = $this->calculateSubjectResult($answerMap['science'], $userOptions, 11);
            $hindiResult = $this->calculateSubjectResult($answerMap['hindi'], $userOptions, 21);
            $englishResult = $this->calculateSubjectResult($answerMap['english'], $userOptions, 31);
            $mathsResult = $this->calculateSubjectResult($answerMap['maths'], $userOptions, 41);

            $totalmatks = $gkResult['marks']
                + $scienceResult['marks']
                + $hindiResult['marks']
                + $englishResult['marks']
                + $mathsResult['marks'];
            $totalpercentage = (
                $gkResult['percentage']
                + $scienceResult['percentage']
                + $hindiResult['percentage']
                + $englishResult['percentage']
                + $mathsResult['percentage']
            ) / 5;
            $status = (
                $gkResult['percentage'] >= 40
                && $scienceResult['percentage'] >= 40
                && $hindiResult['percentage'] >= 40
                && $englishResult['percentage'] >= 40
                && $mathsResult['percentage'] >= 40
            ) ? 1 : 0;

            UserAnswerDetail::query()->create([
                'competitiontitle' => $compitetionassignment->compitetionname,
                'competitionassignid' => $compitetionassignment->id,
                'competitionassigntitle' => $compitetionassignment->compitetiontitle,
                'competitionid' => $compitetionassignment->compitetionid,
                'classgroupid' => $compitetionassignment->groupclassid,
                'classgroupname' => $compitetionassignment->groupclassname,
                'questionsetid' => $questionsetup->id,
                'questionsettitle' => $questionsetup->questionsettitle,
                'gkuseranswer' => $gkResult['user_answers'],
                'gkcorrectanswer' => $gkResult['correct_answers'],
                'scienceuseranswer' => $scienceResult['user_answers'],
                'sciencecorrectanswer' => $scienceResult['correct_answers'],
                'hindiuseranswer' => $hindiResult['user_answers'],
                'hindicorrectanswer' => $hindiResult['correct_answers'],
                'englishuseranswer' => $englishResult['user_answers'],
                'englishcorrectanswer' => $englishResult['correct_answers'],
                'mathsusersanswer' => $mathsResult['user_answers'],
                'mathscorrectanswer' => $mathsResult['correct_answers'],
                'gkmarks' => $gkResult['marks'],
                'gkpercentage' => $gkResult['percentage'],
                'sciencemarks' => $scienceResult['marks'],
                'sciencepercentage' => $scienceResult['percentage'],
                'hindimarks' => $hindiResult['marks'],
                'hindipercentage' => $hindiResult['percentage'],
                'englishmarks' => $englishResult['marks'],
                'englishpercentage' => $englishResult['percentage'],
                'mathsmarks' => $mathsResult['marks'],
                'mathspercentage' => $mathsResult['percentage'],
                'totalmarks' => $totalmatks,
                'totalpercentage' => $totalpercentage,
                'usertime' => $validated['usertime'] ?? '00:00',
                'status' => $status,
                'createdby' => Auth::id(),
                'createdtime' => now(),
            ]);

            $this->clearExamSession((int) $compitetionassignment->id);

            return [
                'status' => 'submitted',
                'contest_id' => (int) $compitetionassignment->compitetionid,
            ];
        });

        if ($submissionResult['status'] === 'not_joined') {
            Session::flash('message', 'Please join this competition before submitting the exam.');

            return redirect()->route('contestdetails', $this->contestDetailsRouteParams((int) $submissionResult['contest_id'], (int) $validated['competitionassignid']));
        }

        if ($submissionResult['status'] === 'already_submitted') {
            Session::flash('message', 'This exam has already been submitted.');

            return redirect()->route('contestdetails', $this->contestDetailsRouteParams((int) $submissionResult['contest_id'], (int) $validated['competitionassignid']));
        }

        if ($submissionResult['status'] === 'closed') {
            Session::flash('message', $submissionResult['message']);

            return redirect()->route('contestdetails', $this->contestDetailsRouteParams((int) $submissionResult['contest_id'], (int) $validated['competitionassignid']));
        }

        if ($submissionResult['status'] === 'expired') {
            Session::flash('message', 'Exam session expired. Please start the exam again.');

            return redirect()->route('examstart', ['id' => $submissionResult['assignment_id']]);
        }

        Session::flash('sucmessage', 'Successful,  Exam has been Completed');

        return redirect()->route('contestdetails', $this->contestDetailsRouteParams((int) $submissionResult['contest_id'], (int) $validated['competitionassignid']));
    }
    
    
        public function myexamresultdetails($id): View|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }

        $assignment = CompetitionAssignment::query()->with('contest')->findOrFail($id);
        $contest = $assignment->contest ?? MatchContest::query()->findOrFail($assignment->compitetionid);
        $contestPage = $this->buildContestDetailsData($contest, $assignment);
        $userAnswer = UserAnswerDetail::query()
            ->where('createdby', Auth::id())
            ->where('competitionassignid', $assignment->id)
            ->latest('id')
            ->first();

        if (! $assignment || ! $userAnswer) {
            Session::flash('message', 'Result details tab available hongi jab aap is competition ka exam submit kar chuke honge.');

            return redirect()->route('contestdetails', $this->contestDetailsRouteParams((int) $contest->id, (int) $assignment->id));
        }

        if ($contestPage['result_available']) {
            return redirect()->route('examsresultt', ['id' => $assignment->id]);
        }

        if ($contestPage['answersheet_available']) {
            Session::flash('message', 'Final result abhi publish nahi hua hai. Answer sheet available hai.');

            return redirect()->route('examsanswersheet', ['id' => $assignment->id]);
        }

        if ($contestPage['result_date_display']) {
            Session::flash('message', 'Result '.$contestPage['result_date_display'].' ko publish hoga.');
        } else {
            Session::flash('message', 'Result abhi publish nahi hua hai.');
        }

        return redirect()->route('contestdetails', $this->contestDetailsRouteParams((int) $contest->id, (int) $assignment->id));
    }

    
       public function scoringresult(): View|RedirectResponse
    {

        if (! Auth::check()) {
            return $this->studentGuestRedirect();
        }   

        $gameplayhistory = GameplayHistory::query()
            ->where('userid', Auth::id())
            ->orderByDesc('id')
            ->paginate(15);

        $gameplayhistory = $this->buildScoringEntries($gameplayhistory);

        return view('front.scoringresult')->with('gameplayhistory',$gameplayhistory);
    }


}
