<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\BloodRequest;
use App\Models\BloodRequestMessage;
use App\Models\Division;

use App\Models\District;
use App\Models\Upazilla;
use App\Models\Union;
use App\Models\Ward;
use App\Models\Village;
use App\Models\BloodGroup;

use App\Models\Hospital;
use App\Models\Profession;
use App\Models\UserProfile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Str;

class UserProfileController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $Division = Division::all();
        $District = District::all();
        $Upazilla = Upazilla::all();
        $professions = Profession::all();
        $Union = Union::all();
        $Ward = Ward::all();
        $Village = Village::all();

        $BloodGroup = BloodGroup::all();
        $user = Auth::user();
        $UserProfile = UserProfile::where('User_id', Auth::user()->id)->first();
        // return view('frontend.pages.profile', compact('user', 'BloodGroup', 'professions', 'UserProfile', 'Division', 'District', 'Upazilla', 'Union', 'Ward', 'Village'));
        return view('user.profile.index', compact('user', 'BloodGroup', 'professions', 'UserProfile', 'Division', 'District', 'Upazilla', 'Union', 'Ward', 'Village'));
    }

    public function DivisionByDist(Request $request)
    {
        $districts = Division::find($request->id)->districts()->get(['id', 'title']);
        return response()->json($districts);
    }
    public function DistrictsByUpzilla(Request $request)
    {
        return $Upazilla = Upazilla::where('district_id', $request->id)->get(['id', 'title', 'district_id']);
    }
    public function UpzillaByUnion(Request $request)
    {
        return $Union = Union::where('upazilla_id', $request->id)->get();
    }
    public function UnionByWard(Request $request)
    {
        return $Ward = Ward::where('union_id', $request->id)->get();
    }
    public function WardByVallage(Request $request)
    {
        return $Village = Village::where('ward_id', $request->id)->get();
    }
    public function createProfile(Request $request)
    {
        // Retrieve the authenticated user’s ID
        $userId = Auth::id(); // Use Auth::id() if creating a profile for the logged-in user

        if (!$userId) {
            return redirect()->back()->withErrors('User not authenticated.');
        }

        $ProfileImage = $request->file('ProfileImage');
        if ($ProfileImage) {
            $imagename = time() . '.' . $ProfileImage->getClientOriginalExtension();
            $ProfileImage->move(public_path('user'), $imagename); // Use public_path to ensure proper storage
            $data['image'] = $imagename; // Store image name in the data array
        }
        $data = [
            'user_id' => $userId,
            'Name' => $request->Name,
            'FatherName' => $request->FatherName,
            'MotherName' => $request->MotherName,
            'Gender' => $request->Gender,
            'Email' => $request->Email,
            'MaritalStatus' => $request->MaritalStatus,
            'AnotherPhone' => $request->AnotherPhone,
            'BloodGroup' => $request->BloodGroup,
            'Occupation' => $request->Occupation,
            'BirthplaceDivision' => $request->BirthplaceDivision,
            'BirthplaceDistrict' => $request->BirthplaceDistrict,
            'BirthplaceUpzilla' => $request->BirthplaceUpzilla,
            'BirthplaceUnion' => $request->BirthplaceUnion,
            'BirthplaceWard' => $request->BirthplaceWard,
            'BirthplaceVillage' => $request->BirthplaceVillage,
            'PermanentDivision' => $request->PermanentDivision,
            'PermanentDistrict' => $request->PermanentDistrict,
            'PermanentUpzilla' => $request->PermanentUpzilla,
            'PermanentUnion' => $request->PermanentUnion,
            'PermanentWard' => $request->PermanentWard,
            'PermanentVillage' => $request->PermanentVillage,
            'CurrentDivision' => $request->CurrentDivision,
            'CurrentDistrict' => $request->CurrentDistrict,
            'CurrentUpzilla' => $request->CurrentUpzilla,
            'CurrentUnion' => $request->CurrentUnion,
            'CurrentWard' => $request->CurrentWard,
            'CurrentVillage' => $request->CurrentVillage,

        ];
        UserProfile::updateOrCreate(
            ['user_id' => $userId],
            $data
        );

        return redirect()->back()->with('success', 'Profile saved successfully.');
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function updateProfileImage(Request $request)
    {
        // Validate the uploaded image
        $request->validate([
            'ProfileImage' => 'nullable|image|mimes:jpg,jpeg,png,gif,bmp|max:2048', // Acceptable formats and max size
        ]);

        // Handle the image upload
        if ($request->hasFile('ProfileImage')) {
            // Get the uploaded image
            $image = $request->file('ProfileImage');

            // Generate a unique name for the image
            $imageName = time() . '.' . $image->getClientOriginalExtension();

            // Move the image to the 'user' folder in the public directory
            $image->move(public_path('user'), $imageName);

            // Get the authenticated user
            $user = auth()->user();

            // Check if the user has a profile and update it
            $profile = $user->profile; // Assuming the User model has a 'profile' relationship

            if ($profile) {
                // If the profile exists, update the ProfileImage in the user_profiles table
                $profile->ProfileImage = $imageName;
                $profile->save();
            } else {
                // If profile doesn't exist, create a new profile
                $profile = new UserProfile(); // Assuming the UserProfile model exists
                $profile->user_id = $user->id; // Associate with the authenticated user
                $profile->ProfileImage = $imageName;
                $profile->save();
            }

            // Redirect back with success message
            return redirect()->back()->with('success', 'Profile image updated successfully.');
        } else {
            // If no file was uploaded, return an error message
            return redirect()->back()->with('error', 'No image uploaded. Please select a valid image file.');
        }
    }


    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\UserProfile  $userProfile
     * @return \Illuminate\Http\Response
     */

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\UserProfile  $userProfile
     * @return \Illuminate\Http\Response
     */
    public function edit(UserProfile $userProfile)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\UserProfile  $userProfile
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, UserProfile $userProfile)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\UserProfile  $userProfile
     * @return \Illuminate\Http\Response
     */
    public function destroy(UserProfile $userProfile)
    {
        //
    }
    public function blood_request()
    {
        $divisions = Division::query()->select(['id', 'title'])->get();
        $hospitals = Hospital::query()->select(['id', 'title'])->get();

        return view('frontend.pages.blood_request', compact('divisions', 'hospitals'));
    }
    public function blood_request_upload(Request $request)
    {

        $blood          = new BloodRequest();
        $blood->user_id = Auth::user()->id;
        // $blood->permission='yes';
        $blood->division       = $request->division;
        $blood->district       = $request->district;
        $blood->upzilla        = $request->upzilla;
        $blood->hospital       = $request->hospital;
        $blood->patientName    = $request->patientName;
        $blood->patientPhone   = $request->patientPhone;
        $blood->referenceName  = $request->referenceName;
        $blood->referencePhone = $request->referencePhone;
        $blood->bloodGroup     = $request->bloodGroup;
        $blood->bagBlood       = $request->bagBlood;
        $blood->message        = $request->message;
        $blood->save();

        $hospital = Hospital::query()->select(['title'])->where(['id' => $request->hospital])->first();
        $division = Division::query()->select(['title'])->where(['id' => $request->division])->first();

        $code = strtoupper(Str::random(10));
        $link = request()->getSchemeAndHttpHost() . "/{$code}";

        BloodRequestMessage::create([
            'blood_request_id' => $blood->id,
            'code'             => $code,
            'message'          => "Please help me!, My name is {$request->patientName} need this {$request->bloodGroup} blood {$blood->bagBlood} bags {$division->title}, {$hospital->title} contact {$request->patientPhone},{$request->referencePhone}, details {$link}",
        ]);

        return redirect()->back();
    }
}