<?php
  
namespace App\Http\Controllers\Admin;
  
use App\Http\Requests\Admin\UpdateWalletStatusRequest;
use App\Http\Requests\Admin\UpdateWithdrawStatusRequest;
use App\Http\Controllers\Controller;
use App\Models\Attachment;
use App\Models\WalletHistory;
use App\Models\WalletUser;
use App\Models\WithdrawHistory;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Session;
use Illuminate\Support\Facades\Redirect;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
  
class WalletController extends Controller
{
    private function guestRedirect(): RedirectResponse
    {
        return redirect()->route('admin.logindata')
            ->with('message', 'Please login to continue.');
    }

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

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

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

    private function mapWalletHistories($histories)
    {
        return $histories->map(function (WalletHistory $history) {
            $history->preview_url = $this->attachmentUrl((int) $history->transectionimg, ASSETURL.'public/newlogo.jpg');

            return $history;
        });
    }

    private function applyWalletRechargeStatus(WalletHistory $history, int $newStatus): void
    {
        $previousStatus = (int) $history->status;

        DB::transaction(function () use ($history, $newStatus, $previousStatus) {
            $wallet = WalletUser::query()->firstOrCreate(
                ['userid' => $history->userid],
                [
                    'username' => $history->username,
                    'walletamount' => 0,
                    'updatedtime' => $history->createdtime ?? now(),
                ]
            );

            $amount = (float) $history->addamount;
            $walletAmount = (float) $wallet->walletamount;

            if ($newStatus === 1 && $previousStatus !== 1) {
                $walletAmount += $amount;
            }

            if ($newStatus === 3 && $previousStatus === 1) {
                $walletAmount = max(0, $walletAmount - $amount);
            }

            $history->update(['status' => $newStatus]);
            $wallet->update([
                'walletamount' => $walletAmount,
                'updatedtime' => now(),
            ]);
        });
    }

    private function applyWithdrawStatus(WithdrawHistory $history, int $newStatus): void
    {
        $previousStatus = (int) $history->status;

        DB::transaction(function () use ($history, $newStatus, $previousStatus) {
            $wallet = WalletUser::query()->firstOrCreate(
                ['userid' => $history->createdby],
                [
                    'username' => $history->username,
                    'walletamount' => 0,
                    'updatedtime' => $history->createdtime ?? now(),
                ]
            );

            $amount = (float) $history->withdrawamt;
            $walletAmount = (float) $wallet->walletamount;

            if ($newStatus === 1 && $previousStatus !== 1) {
                $walletAmount = max(0, $walletAmount - $amount);
            }

            if ($newStatus === 3 && $previousStatus === 1) {
                $walletAmount += $amount;
            }

            $history->update(['status' => $newStatus]);
            $wallet->update([
                'walletamount' => $walletAmount,
                'updatedtime' => now(),
            ]);
        });
    }
 

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


        public function amountrequest()
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }   
     
              $wallethistory = $this->mapWalletHistories(
                  WalletHistory::query()->where('status', 2)->orderByDesc('id')->get()
              );  

            return view('admin.wallets.amountrequest')->with('wallethistory',$wallethistory);
        } 

        public function amountrequestaccepted()
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }   
     
              $wallethistory = $this->mapWalletHistories(
                  WalletHistory::query()->where('status', 1)->orderByDesc('id')->get()
              );  

            return view('admin.wallets.amountrequestaccepted')->with('wallethistory',$wallethistory);
        } 

        public function rejectrequest()
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }   
     
              $wallethistory = $this->mapWalletHistories(
                  WalletHistory::query()->where('status', 3)->orderByDesc('id')->get()
              );  

            return view('admin.wallets.rejectrequest')->with('wallethistory',$wallethistory);
        } 

        
        
    
        public function changestatus(UpdateWalletStatusRequest $request, $id)
        {
            if (!Auth::check()) {
                return $this->guestRedirect();
            }

            $validated = $request->validated();
            $status = (int) $validated['status'];

            $history = WalletHistory::query()->findOrFail($id);
            $this->applyWalletRechargeStatus($history, $status);
            
            Session::flash('sucmessage', "Successful,  Wallet Amount  has Updated"); 
             
            return Redirect::back(); 
        } 

          public function withdrawrequest()
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }   
     
              $wallethistory = WithdrawHistory::query()->where('status', 2)->orderByDesc('id')->get();  

            return view('admin.wallets.withdraw.withdrawrequest')->with('wallethistory',$wallethistory);
        } 


        
        public function changewithdrawstatus(UpdateWithdrawStatusRequest $request, $id)
        {
            if (!Auth::check()) {
                return $this->guestRedirect();
            }

            $validated = $request->validated();
            $status = (int) $validated['status'];

            $history = WithdrawHistory::query()->findOrFail($id);
            $this->applyWithdrawStatus($history, $status);
            
            Session::flash('sucmessage', "Successful,  Wallet Amount  has Updated"); 
             
            return Redirect::back(); 
        } 

           public function withdrawrequestaccepted()
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }   
     
              $wallethistory = WithdrawHistory::query()->where('status', 1)->orderByDesc('id')->get();  

            return view('admin.wallets.withdraw.withdrawrequestaccepted')->with('wallethistory',$wallethistory);
        } 

        
        
           public function rejectwithdraw()
        {
            if (!Auth::check()) { 
                return $this->guestRedirect();
              }   
     
              $wallethistory = WithdrawHistory::query()->where('status', 3)->orderByDesc('id')->get();  

            return view('admin.wallets.withdraw.rejectwithdraw')->with('wallethistory',$wallethistory);
        } 

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

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

       
        
         

}
