<?php

namespace App\Http\Controllers;

use App\Helpers\MediaHelper;
use App\Http\Requests\VirtualCardKyUpdateRequest;
use App\Models\VirtualCardKy;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use App\Http\Requests\VirtualCardKyRequest;
use Illuminate\Support\Facades\Redirect;
use Illuminate\View\View;

class VirtualCardKyController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): View
    {
        $virtualQuery = VirtualCardKy::query();

// Handle search filter
        if ($request->filled('search')) {
            $searchTerm = $request->input('search');
            $virtualQuery->where(function ($query) use ($searchTerm) {
                $query->whereHas('user', function ($userQuery) use ($searchTerm) {
                    $userQuery->where('email', 'like', '%' . $searchTerm . '%')
                        ->orWhere('phone', 'like', '%' . $searchTerm . '%');
                });
            });
        }

// Handle status filter
        if ($request->filled('status')) {
            $virtualQuery->where('status', $request->input('status'));
        }

// Handle kyc_status filter
        if ($request->filled('kyc_status')) {
            $virtualQuery->where('kyc_status', $request->input('kyc_status'));
        }

// Paginate the results
        $virtualCardKies = $virtualQuery->paginate(15);

        return view('virtual-card-ky.index', compact('virtualCardKies'))
            ->with('i', ($request->input('page', 1) - 1) * $virtualCardKies->perPage());

    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(): View
    {
        $virtualCardKy = new VirtualCardKy();

        return view('virtual-card-ky.create', compact('virtualCardKy'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(VirtualCardKyRequest $request)//: RedirectResponse
    {

        $validated = $request->validated();
       // dd($validated); // Check the validated data
//check if nin or bvn exit
        $checkData = VirtualCardKy::where('nin_no', $request->nin_no)
                ->orWhere('bvn', $request->bvn_no)
            ->first();

        if ($checkData) {
            return back()->with('error', 'NIN or BVN Already Exist. Please check your input');
        }
        if($request->hasFile('photo')){
            $filename = MediaHelper::handleMakeImage($request->photo);
            $validated['photo']=$filename;
        }
        if($request->hasFile('id_image_url')){
            $filename = MediaHelper::handleMakeImage($request->id_image_url);
            $validated['id_image_url']=$filename;
        }
       $validated['user_id']=auth()->user()->id;
        $validated['status']='pending';
        $validated['id_number']=$request->nin_no;
        $validated['phone_number']=auth()->user()->phone;


        VirtualCardKy::create($validated);

        return Redirect::route('user.virtual-cards.mycards')
            ->with('success', 'Virtual Card KYC Submitted Successfully, Please note that the your data is under review this can take like 10Minute.');
    }

    /**
     * Display the specified resource.
     */
    public function show($id): View
    {
        $virtualCardKy = VirtualCardKy::where('_id',$id)->firstOrFail();

        return view('virtual-card-ky.show', compact('virtualCardKy'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(): View
    {
        $virtualCardKy = VirtualCardKy::where('user_id', auth()->user()->id)->first();
        if($virtualCardKy) { //check if exist
if($virtualCardKy->status=='pending' || $virtualCardKy->status=='rejected') {
    return view('virtual-card-ky.edit', compact('virtualCardKy'));
}else{
    return Redirect::route('user.virtual-cards.mycards')
        ->with('success', 'Virtual Card KYC Already Submitted.');
}
        }else{ //if not redirect to create new one
            return Redirect::route('user.virtual-card-kyc.create');
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(VirtualCardKyUpdateRequest $request): RedirectResponse
    {
        $userId = auth()->user()->id;
        $virtualCardKy = VirtualCardKy::where('user_id', auth()->user()->id)->first();

        if ($virtualCardKy) {
            if($virtualCardKy->status=='pending' || $virtualCardKy->status=='rejected') {
                $validated = $request->validated();
                $checkData = VirtualCardKy::where(function ($query) use ($request) {
                    $query->where('nin_no', $request->nin_no)
                        ->orWhere('bvn', $request->bvn_no);
                })
                    ->where('user_id', '!=', auth()->user()->id)
                    ->first();

                if ($checkData) {
                    return back()->with('error', 'NIN or BVN Already Exist. Please check your input');
                }
                // Handle photo update
                if ($request->hasFile('photo')) {
                    // Delete old photo if exists
                    if ($virtualCardKy->photo) {
                        MediaHelper::handleDeleteImage($virtualCardKy->photo); // Assuming `deleteImage` is a method

                    }
                        // Upload new photo
                        $filename = MediaHelper::handleMakeImage($request->photo);
                        $validated['photo'] = $filename;

                }

                // Handle ID image update
                if ($request->hasFile('id_image_url')) {
                    // Delete old ID image if exists
                    if ($virtualCardKy->id_image_url) {
                        MediaHelper::handleDeleteImage($request->id_image_url);
                    }
                        // Upload new ID image
                        $filename = MediaHelper::handleMakeImage($request->id_image_url);
                        $validated['id_image_url'] = $filename;

                }

                // Update other fields
                $validated['user_id'] = $userId;
                $validated['status'] = 'pending';

                // Update the record
                $virtualCardKy->update($validated);

                return Redirect::route('user.virtual-cards.mycards')
                    ->with('success', 'Virtual Card KYC Updated Successfully. Your data is under review.');
            }else{
                return Redirect::route('user.virtual-cards.mycards')
                    ->with('success', 'Virtual Card KYC Already Submitted.');
            }
        } else {
            return Redirect::route('user.virtual-card-kyc.create')
                ->with('error', 'No existing KYC data found. Please create one.');
        }
    }


    public function destroy($id): RedirectResponse
    {
        VirtualCardKy::find($id)->delete();

        return Redirect::route('virtual-card-kies.index')
            ->with('success', 'VirtualCardKy deleted successfully');
    }

    public function rejectKyc(Request $request,$id)
    {
        $request->validate(['reason'=>'required']);

     $virtualCardKy = VirtualCardKy::where('_id',$id)->firstOrFail();


        $virtualCardKy->status = "rejected";
        $virtualCardKy->note_on_status = $request->reason;
        $virtualCardKy->update();

        @email([
            'email'   => $virtualCardKy->user->email,
            'name'    => $virtualCardKy->name->name,
            'subject' => 'Virtual Card KYC info rejected',
            'message' =>'Your KYC information has been rejected'.$virtualCardKy->note_on_status,
        ]);

        return back()->with('success','KYC info has been rejected');
    }
    public function approveKyc($id)
    {

        $virtualCardKy = VirtualCardKy::where('_id',$id)->firstOrFail();


        $virtualCardKy->status = "approved";
        $virtualCardKy->update();

        @email([
            'email'   => $virtualCardKy->user->email,
            'name'    => $virtualCardKy->name->name,
            'subject' => 'KYC info approved',
            'message' => 'Your KYC information has been approved, You can now create your virtual card',
        ]);
        return back()->with('success','KYC info has been approved');
    }
}
