<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use App\Http\Resources\UserResource;
use App\Models\User;
use App\Models\Friend;
use App\Models\Follower;
use App\Models\Post;
use App\Models\Notification;
use App\Models\BloodDonation;

class ProfileController extends Controller
{
    /**
     * Display the user's profile.
     */
    public function show(Request $request, $username)
    {
        // Attempt to retrieve the user by username
        $user = User::where('username', $username)->first();

        // If no user is found, return a 404 response
        if (!$user) {
            return response()->json(['message' => 'User not found'], 404);
        }

        $loggedInUserId = Auth::id();

        // If the user is viewing their own profile, return the full user resource
        if ($user->id === $loggedInUserId) {
            return new UserResource($user);
        }

        // Check if the user is blocked
        if ($user->isBlockedBy($loggedInUserId)) {
            return response()->json(['message' => 'You are not authorized to view this profile.'], 403);
        }

        // Return the user details and other information
        return response()->json([
            'user' => new UserResource($user),
            'followers_count' => $user->followers()->count(),
            'mutual_friends' => Friend::getMutualFriendsCount($user->id, $loggedInUserId),
            'is_following' => Follower::isFollowing($loggedInUserId, $user->id),
            'is_friend' => Friend::isFriend($loggedInUserId, $user->id),
        ]);
    }
    /**
     * Update the user's profile.
     */
    public function update(Request $request)
    {
        $user = Auth::user();
        if (!$user) {
            return response()->json([
                'status' => 404,
                'message' => 'User not found or not authenticated.',
            ], 404);
        }

        // ✅ Validation rules
        $validatedData = $request->validate([
            'first_name' => 'nullable|string|max:255',
            'last_name' => 'nullable|string|max:255',
            'relationship' => 'nullable|string|max:255',
            'workspace' => 'nullable|string|max:255',
            'bio' => 'nullable|string|max:500',
            'phone' => 'nullable|string|max:20',
            'gender' => 'nullable|in:male,female,other',
            'date_of_birth' => 'nullable|date|before:today',
            'address' => 'nullable|string|max:500',
            'latitude' => 'nullable|numeric',
            'longitude' => 'nullable|numeric',
            'avatar' => 'nullable|image|mimes:jpg,jpeg,png|max:2048', // 2MB max
            'cover' => 'nullable|image|mimes:jpg,jpeg,png|max:4096',  // 4MB max
        ], [
            'first_name.string' => 'The first name must be a valid string.',
            'last_name.string' => 'The last name must be a valid string.',
            'bio.string' => 'The bio must be a valid string.',
            'phone.string' => 'The mobile number must be a valid string.',
            'gender.in' => 'The gender must be one of male, female, or other.',
            'date_of_birth.date' => 'The date of birth must be a valid date.',
            'date_of_birth.before' => 'The date of birth must be a date before today.',
            'address.string' => 'The address must be a valid string.',
            'avatar.image' => 'The avatar must be a valid image file.',
            'avatar.mimes' => 'The avatar must be a jpg, jpeg, or png image.',
            'cover.image' => 'The cover must be a valid image file.',
            'cover.mimes' => 'The cover must be a jpg, jpeg, or png image.',
        ]);

        try {
            $updateData = $validatedData;

            // ✅ Handle avatar upload
            if ($request->hasFile('avatar')) {
                $avatarPath = storeMedia($request->file('avatar'), 'profile_image');
                $updateData['avatar'] = $avatarPath;
            }

            // ✅ Handle cover upload
            if ($request->hasFile('cover')) {
                $coverPath = storeMedia($request->file('cover'), 'cover');
                $updateData['cover'] = $coverPath;
            }

            // ✅ Update user profile
            $user->update($updateData);

            return response()->json([
                'status' => 200,
                'message' => 'Profile updated successfully.',
                'data' => new UserResource($user),
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'An error occurred while updating the profile. Please try again.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }
    public function updateNotificatinSetting(Request $request)
    {
        $validated = $request->validate([
            "notify_like" => "required|boolean",
            "notify_comment" => "required|boolean",
            "notify_share_post" => "required|boolean",
            "notify_accept_request" => "required|boolean",
            "notify_liked_page" => "required|boolean",
            "notify_joined_group" => "required|boolean",
            "notify_view_story" => "required|boolean",
            "notify_visited_my_profile" => "required|boolean",
            "notify_mentioned_me" => "required|boolean",
            "notify_message" => "required|boolean",
            "notify_friends_newpost" => "required|boolean",
            "notify_profile_visit" => "required|boolean",
            "notify_send_request" => "required|boolean",
        ]);

        $user = Auth::user();
        $user->notification_setting = $validated;
        $user->save();

        return response()->json([
            "success" => true,
            "message" => "Notification settings updated successfully",
            "data" => $user->notification_setting
        ]);
    }




    /**
     * Update the user's profile picture.
     */
    public function updateProfilePicture(Request $request)
    {
        // Ensure the user is authenticated
        $user = Auth::user();

        if (!$user) {
            return response()->json([
                'status' => 404,
                'message' => 'User not found or not authenticated.',
            ], 404);
        }

        // Validate the incoming request
        $request->validate([
            'avatar' => 'required|image|max:8048',
        ], [
            'avatar.required' => 'An avatar image is required.',
            'avatar.image' => 'The uploaded file must be an image.',
            'avatar.max' => 'The image size must not exceed 8 MB.',
        ]);


        $file = $request->file('avatar');
        if (!$file) {
            return response()->json([
                'status' => 400,
                'message' => 'No file uploaded.',
            ], 400);
        }

        try {
            // Use the storeMedia helper to save the new avatar
            $path = storeMedia($file, 'avatars');

            // Update the user's avatar path in the database
            $user->update(['avatar' => $path]);

            // Return the URL using the getMedia helper
            return response()->json([
                'status' => 200,
                'message' => 'Profile picture updated successfully.',
                'data' => ['avatar_url' => getMedia($path, 'avatar')],
            ]);
        } catch (\Exception $e) {
            // Return a meaningful error response
            return response()->json([
                'status' => 500,
                'message' => 'Failed to update profile picture. Please try again later.',
            ], 500);
        }
    }

    /**
     * Update the user's cover photo.
     */
    public function updateCoverPhoto(Request $request)
    {
        // Ensure the user is authenticated
        $user = Auth::user();

        if (!$user) {
            return response()->json([
                'status' => 404,
                'message' => 'User not found or not authenticated.',
            ], 404);
        }

        // Validate the incoming request
        $request->validate([
            'cover' => 'required|image|max:2048',
        ], [
            'cover.required' => 'A cover image is required.',
            'cover.image' => 'The uploaded file must be an image.',
            'cover.max' => 'The image size must not exceed 2 MB.',
        ]);

        $file = $request->file('cover');
        if (!$file) {
            return response()->json([
                'status' => 400,
                'message' => 'No file uploaded.',
            ], 400);
        }

        try {
            // Use the storeMedia helper to save the new cover photo
            $path = storeMedia($file, 'covers');

            // Update the user's cover path in the database
            $user->update(['cover' => $path]);

            // Return the URL using the getMedia helper
            return response()->json([
                'status' => 200,
                'message' => 'Cover photo updated successfully.',
                'data' => ['cover_url' => getMedia($path)],
            ]);
        } catch (\Exception $e) {
            // Return a meaningful error response
            return response()->json([
                'status' => 500,
                'message' => 'Failed to update cover photo. Please try again later.',
            ], 500);
        }
    }


    /**
     * Delete the user's account.
     */
    public function destroy(Request $request)
    {
        $request->validate([
            'password' => 'required|current_password',
        ]);

        $user = Auth::user();
        $user->delete();

        return response()->json(['message' => 'Account deleted successfully.']);
    }

    /**
     * Search for users.
     */
    public function search(Request $request)
    {
        $query = $request->input('query');
        $user_id = $request->user()->id;
        $users = User::query()
            ->where('id', '!=', $user_id)
            ->where('username', 'LIKE', "%$query%")
            ->orWhere('first_name', 'LIKE', "%$query%")
            ->orWhere('last_name', 'LIKE', "%$query%")
            ->orWhere('email', 'LIKE', "%$query%")
            ->paginate(10);

        return UserResource::collection($users);
    }

    /**
     * Display the user's profile by ID.
     */
    public function showById(Request $request, $id)
    {
        // Attempt to retrieve the user by ID
        $user = User::find($id);

        // If no user is found, return a 404 response
        if (!$user) {
            return response()->json(['message' => 'User not found0000'], 404);
        }

        $loggedInUserId = Auth::id();

        // If the user is viewing their own profile, return the full user resource
        if ($user->id === $loggedInUserId) {
            return response()->json([
                'status' => 200,
                'message' => 'User profile retrieved successfully.',
                'data' => new UserResource($user),
            ], 200);
        }

        // Check if the user is blocked
        if ($user->isBlockedBy($loggedInUserId)) {
            return response()->json(['message' => 'You are not authorized to view this profile.'], 403);
        }
        $userdata = new UserResource($user);
        return response()->json([
            'status' => 200,
            'message' => 'User profile retrieved successfully.',
            'data' => $userdata->additional([
                'followers_count' => $user->followers()->count(),
                'mutual_friends' => Friend::getMutualFriendsCount($user->id, $loggedInUserId),
                'is_following' => Follower::isFollowing($loggedInUserId, $user->id),
                'is_friend' => Friend::isFriend($loggedInUserId, $user->id),
                'friend_request_status' => Friend::pendingRequestStatus($loggedInUserId, $user->id),
            ]),
        ], 200);
    }

    /**
     * Become a blood donor.
     */
    public function becomeDonor(Request $request)
    {
        $user = Auth::user();

        $validatedData = $request->validate([
            'location' => 'required|string|max:255',
            'last_donation' => 'nullable|date',
            'blood_group' => 'required|string|max:3',
            'phone_no' => 'required|string|max:15',
        ]);

        $user->bloodDonation()->updateOrCreate(['user_id' => $user->id], $validatedData);

        return response()->json(['message' => 'Blood donor information updated successfully.']);
    }

    /**
     * List blood donors.
     */
    public function listDonors(Request $request)
    {
        $bloodGroup = $request->input('blood_group');
        $donors = User::whereHas('bloodDonation', function ($query) use ($bloodGroup) {
            if ($bloodGroup) {
                $query->where('blood_group', $bloodGroup);
            }
        })->paginate(10);

        return UserResource::collection($donors);
    }

    /**
     * Get profile completion status for the authenticated user
     */
    public function getProfileCompletion(Request $request)
    {
        $user = Auth::user();

        if (!$user) {
            return response()->json([
                'status' => 404,
                'message' => 'User not found or not authenticated.',
            ], 404);
        }

        // Calculate completion based on various profile fields
        $completionData = [
            'general_info' => [
                'name' => 'General Information',
                'completed' => 0,
                'total' => 6,
                'percentage' => 0,
                'status' => 'incomplete'
            ],
            'work_experience' => [
                'name' => 'Work Experience',
                'completed' => 0,
                'total' => 3,
                'percentage' => 0,
                'status' => 'incomplete'
            ],
            'profile_photo' => [
                'name' => 'Profile Photo',
                'completed' => 0,
                'total' => 1,
                'percentage' => 0,
                'status' => 'incomplete'
            ],
            'cover_photo' => [
                'name' => 'Cover Photo',
                'completed' => 0,
                'total' => 1,
                'percentage' => 0,
                'status' => 'incomplete'
            ]
        ];

        // Check general information (name, bio, gender, date_of_birth, mobile, address)
        $generalFields = ['first_name', 'last_name', 'bio', 'gender', 'date_of_birth', 'mobile'];
        $generalCompleted = 0;
        foreach ($generalFields as $field) {
            if (!empty($user->$field)) {
                $generalCompleted++;
            }
        }
        $completionData['general_info']['completed'] = $generalCompleted;
        $completionData['general_info']['percentage'] = round(($generalCompleted / 6) * 100);
        $completionData['general_info']['status'] = $generalCompleted == 6 ? 'complete' : ($generalCompleted > 3 ? 'warning' : 'incomplete');

        // Check work experience (simplified - you can expand this based on your work experience model)
        // For now, checking if user has filled address and bio as work-related info
        $workCompleted = 0;
        if (!empty($user->address)) $workCompleted++;
        if (!empty($user->bio) && strlen($user->bio) > 50) $workCompleted++;
        if (!empty($user->mobile)) $workCompleted++; // Assuming mobile is work-related

        $completionData['work_experience']['completed'] = $workCompleted;
        $completionData['work_experience']['percentage'] = round(($workCompleted / 3) * 100);
        $completionData['work_experience']['status'] = $workCompleted == 3 ? 'complete' : ($workCompleted > 0 ? 'warning' : 'incomplete');

        // Check profile photo
        if (!empty($user->avatar)) {
            $completionData['profile_photo']['completed'] = 1;
            $completionData['profile_photo']['percentage'] = 100;
            $completionData['profile_photo']['status'] = 'complete';
        }

        // Check cover photo
        if (!empty($user->cover)) {
            $completionData['cover_photo']['completed'] = 1;
            $completionData['cover_photo']['percentage'] = 100;
            $completionData['cover_photo']['status'] = 'complete';
        }

        // Calculate overall completion
        $totalCompleted = $completionData['general_info']['completed'] +
            $completionData['work_experience']['completed'] +
            $completionData['profile_photo']['completed'] +
            $completionData['cover_photo']['completed'];
        $totalPossible = 11; // 6 + 3 + 1 + 1
        $overallPercentage = round(($totalCompleted / $totalPossible) * 100);

        return response()->json([
            'status' => 200,
            'data' => [
                'overall_percentage' => $overallPercentage,
                'sections' => $completionData
            ]
        ]);
    }

    public function profile_settings(Request $request)
    {
        die('sd');
        $user = Auth::user();
        echo '<pre>';
        print_r($user);
        echo '</pre>';
        return response()->json(['settings' => new UserResource($user)]);
    }
    public function nearByUsers(Request $request)
    {
        $user = Auth::user();
        $latitude = $user->latitude;
        $longitude = $user->longitude;
        $radius = $request->radius ?? 10;  // Default radius is 10 km

        // Use the User model to get nearby users
        $users = User::nearbyUsers($latitude, $longitude, $radius)->get();
        return response()->json(['status' => 200, 'data' => $users]);
    }
}
