<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Message;
use App\Models\User;
use App\Models\UserProfile;
use App\Models\UserProfileLike;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class ProfileController extends Controller
{
    // public function index()
    // {
    //     $user = Auth::user();
    //     $profile = $user->profile;

    //     $conversations = Message::with(['sender.profile', 'receiver.profile'])
    //         ->where(function ($query) use ($user) {
    //             $query->where('sender_id', $user->id)
    //                 ->orWhere('receiver_id', $user->id);
    //         })
    //         ->get()
    //         ->groupBy(function ($message) use ($user) {
    //             return $message->sender_id == $user->id
    //                 ? $message->receiver_id
    //                 : $message->sender_id;
    //         })
    //         ->map(function ($messages) use ($user) {
    //             $otherUserId = $messages->first()->sender_id == $user->id
    //                 ? $messages->first()->receiver_id
    //                 : $messages->first()->sender_id;

    //             $otherUser = User::with('profile')->find($otherUserId);

    //             return (object) [
    //                 'other_user' => $otherUser ?? null, // Handle null case
    //                 'last_message' => $messages->sortByDesc('created_at')->first(),
    //                 'unread_count' => $messages->where('receiver_id', $user->id)
    //                     ->where('is_read', false)
    //                     ->count(),
    //             ];
    //         })
    //         ->sortByDesc(function ($conv) {
    //             return $conv->last_message->created_at;
    //         });

    //         // print_r($conversations);

    //     $latestSubscription = DB::table('user_subscription')
    //         ->where('user_id', $user->id)
    //         ->orderByDesc('id')
    //         ->first();

    //     return view('website.profile', compact('profile', 'conversations', 'latestSubscription'));
    // }
    public function index()
    {
        $user = Auth::user();
        $profile = $user->profile;

        // Get latest subscription
        $latestSubscription = DB::table('user_subscription')
            ->where('user_id', $user->id)
            ->orderByDesc('id')
            ->first();


        $subscriptionHistory = collect(); // default empty collection

        if ($latestSubscription) {
            $subscriptionHistory = DB::table('user_subscription')
                ->where('user_id', $user->id)
                ->where('id', '<', $latestSubscription->id) // exclude the latest
                ->orderByDesc('id')
                ->get();
        }
        // Check if active
        $isActive = false;
        if ($latestSubscription && $latestSubscription->subscription_end) {
            $isActive = \Carbon\Carbon::parse($latestSubscription->subscription_end)->isFuture();
        }

        $conversations = Message::with(['sender.profile', 'receiver.profile'])
            ->where(function ($query) use ($user) {
                $query->where('sender_id', $user->id)
                    ->orWhere('receiver_id', $user->id);
            })
            ->get()
            ->groupBy(function ($message) use ($user) {
                return $message->sender_id == $user->id
                    ? $message->receiver_id
                    : $message->sender_id;
            })
            ->map(function ($messages) use ($user) {
                $otherUserId = $messages->first()->sender_id == $user->id
                    ? $messages->first()->receiver_id
                    : $messages->first()->sender_id;

                // Try to find the other user
                $otherUser = User::with('profile')->find($otherUserId);

                // If other user is deleted, skip this conversation
                if (!$otherUser) {
                    return null;
                }

                return (object)[
                    'other_user' => $otherUser,
                    'last_message' => $messages->sortByDesc('created_at')->first(),
                    'unread_count' => $messages->where('receiver_id', $user->id)
                        ->where('is_read', false)->count(),
                ];
            })
            ->filter() // remove nulls (deleted users)
            ->sortByDesc(fn($conv) => $conv->last_message->created_at);

        $totalChats = $conversations->count();
        $pageTitle = 'Profile';

        return view('website.profile', compact('profile', 'pageTitle', 'conversations', 'latestSubscription', 'isActive', 'totalChats', 'subscriptionHistory'));
    }


    public function store(Request $request)
    {
        try {
            $userId = Auth::id();
            if (!$userId) {
                return response()->json([
                    'success' => false,
                    'message' => 'You must be logged in.'
                ], 401);
            }

            $existing = UserProfile::where('user_id', $userId)->first();

            $validationRules = [
                'real_name' => 'required|string|max:255',
                'nickname' => 'required|string|max:255',
                'phone_country_code' => 'required|string|max:5',
                'phone_number' => 'required|string|max:20',
                'gender' => 'required|in:male,female,others',
                'country' => 'required|string|max:50',
                'book_name' => 'required|string|max:255',
                'author_name' => 'required|string|max:255',
                'short_description' => 'required|string|max:100',
                'favorite_quotes' => 'required|string|max:100',
                'terms' => 'accepted',
            ];

            // Make files conditionally required
            $validationRules['profile_photo'] = $existing && $existing->profile_photo
                ? 'nullable|image|mimes:jpeg,png,jpg,webp|max:2048'
                : 'required|image|mimes:jpeg,png,jpg,webp|max:2048';

            $validationRules['book_cover'] = $existing && $existing->book_cover
                ? 'nullable|image|mimes:jpeg,png,jpg,webp|max:2048'
                : 'required|image|mimes:jpeg,png,jpg,webp|max:2048';

            $validator = Validator::make($request->all(), $validationRules);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'errors' => $validator->errors()
                ], 422);
            }

            // Process file uploads
            $profilePhotoPath = $existing->profile_photo ?? null;
            $bookCoverPath = $existing->book_cover ?? null;

            if ($request->hasFile('profile_photo')) {
                $file = $request->file('profile_photo');
                $fileName = time() . '_profile_' . $file->getClientOriginalName();

                // Ensure directory exists
                $uploadPath = public_path('website/uploads/profile_images');
                if (!file_exists($uploadPath)) {
                    mkdir($uploadPath, 0755, true);
                }

                // Delete old file if exists
                if ($profilePhotoPath && file_exists(public_path('website/uploads/profile_images/' . $profilePhotoPath))) {
                    unlink(public_path('website/uploads/profile_images/' . $profilePhotoPath));
                }

                $file->move($uploadPath, $fileName);
                $profilePhotoPath = $fileName;
            }

            if ($request->hasFile('book_cover')) {
                $file = $request->file('book_cover');
                $fileName = time() . '_cover_' . $file->getClientOriginalName();

                // Ensure directory exists
                $uploadPath = public_path('website/uploads/book_covers');
                if (!file_exists($uploadPath)) {
                    mkdir($uploadPath, 0755, true);
                }

                // Delete old file if exists
                if ($bookCoverPath && file_exists(public_path('website/uploads/book_covers/' . $bookCoverPath))) {
                    unlink(public_path('website/uploads/book_covers/' . $bookCoverPath));
                }

                $file->move($uploadPath, $fileName);
                $bookCoverPath = $fileName;
            }

            UserProfile::updateOrCreate(
                ['user_id' => $userId],
                [
                    'real_name' => $request->real_name,
                    'nickname' => $request->nickname,
                    'phone_country_code' => $request->phone_country_code,
                    'phone_number' => $request->phone_number,
                    'gender' => $request->gender,
                    'country' => $request->country,
                    'book_name' => $request->book_name,
                    'author_name' => $request->author_name,
                    'short_description' => $request->short_description,
                    'favorite_quotes' => $request->favorite_quotes,
                    'profile_photo' => $profilePhotoPath,
                    'book_cover' => $bookCoverPath,
                    'verification_status' => 'unverified',
                    'terms' => $request->has('terms'),
                ]
            );

            return response()->json([
                'success' => true,
                'message' => 'Profile updated successfully!'
            ]);
        } catch (\Exception $e) {
            \Log::error('Profile update error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'An error occurred: ' . $e->getMessage()
            ], 500);
        }
    }


    public function deletePhoto(Request $request)
    {
        $user = Auth::user();
        $profile = UserProfile::where('user_id', $user->id)->first();

        if ($profile && $profile->profile_photo) {
            $imagePath = public_path('website/uploads/profile_images/' . $profile->profile_photo);

            if (file_exists($imagePath)) {
                unlink($imagePath); // delete file
            }

            $profile->profile_photo = null;
            $profile->save();

            return response()->json(['success' => true]);
        }

        return response()->json(['success' => false]);
    }


    public function updatePassword(Request $request)
    {
        $request->validate([
            'current_password' => ['required'],
            'new_password' => ['required', 'min:6', 'confirmed'],
        ]);

        $user = Auth::user();

        if (!Hash::check($request->current_password, $user->password)) {
            if ($request->wantsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Current password is incorrect.'
                ], 422);
            }
            return back()->withErrors(['current_password' => 'Current password is incorrect.']);
        }

        $user->password = Hash::make($request->new_password);
        $user->save();

        if ($request->wantsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Password updated successfully!'
            ]);
        }

        return back()->with('toast', [
            'type' => 'success',
            'message' => 'Password updated successfully!'
        ]);
    }

    public function logout(Request $request)
    {
        Cache::forget('user-is-online-' . Auth::id());
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/');
    }


    public function destroy(Request $request)
    {
        $user = Auth::user();

        // Optional: delete related data
        UserProfile::where('user_id', $user->id)->delete();

        // Delete user account
        $user->delete();

        // Logout user
        Auth::logout();

        // Redirect to homepage or goodbye page
        return redirect('/')->with('success', 'Your account has been deleted.');
    }


    // public function likeProfile(Request $request)
    // {
    //     $request->validate([
    //         'profile_id' => 'required|exists:user_profiles,id',
    //         'type' => 'required|in:profile,book',
    //     ]);

    //     $userId = Auth::id();

    //     // Prevent double like
    //     $exists = UserProfileLike::where('user_id', $userId)
    //                 ->where('profile_id', $request->profile_id)
    //                 ->where('type', $request->type)
    //                 ->exists();

    //     if ($exists) {
    //         return response()->json(['message' => 'Already liked'], 200);
    //     }

    //     // Save like
    //    UserProfileLike::create([
    //         'user_id' => $userId,
    //         'profile_id' => $request->profile_id,
    //         'type' => $request->type,
    //     ]);

    //     // Update like count
    //     $profile = UserProfile::findOrFail($request->profile_id);
    //     if ($request->type === 'profile') {
    //         $profile->increment('prfile_likes');
    //     } else {
    //         $profile->increment('book_likes');
    //     }

    //     return response()->json(['message' => 'Liked successfully']);
    // }

    public function likeProfile(Request $request)
    {
        $user = auth()->user();

        if (!$user) {
            return response()->json(['message' => 'Unauthorized'], 401);
        }

        $profileId = $request->profile_id;
        $type = $request->type;

        // Check if already liked
        $alreadyLiked = UserProfileLike::where('user_id', $user->id)
            ->where('profile_id', $profileId)
            ->where('type', $type)
            ->first();

        if ($alreadyLiked) {
            return response()->json([
                'status' => 'already_liked',
                'message' => 'You already liked this.',
                'id' => $profileId,
                'type' => $type,
                'hide' => true // <-- indicate to hide button
            ]);
        }

        // Create the like
        UserProfileLike::create([
            'user_id' => $user->id,
            'profile_id' => $profileId,
            'type' => $type
        ]);

        // Update like count
        if ($type === 'book') {
            UserProfile::where('id', $profileId)->increment('book_likes');
        } elseif ($type === 'profile') {
            UserProfile::where('id', $profileId)->increment('prfile_likes'); // NOTE: spelling 'prfile_likes' is probably incorrect; see below
        }

        // Get new like count
        $likes = UserProfileLike::where('profile_id', $profileId)
            ->where('type', $type)
            ->count();

        return response()->json([
            'status' => 'liked',
            'message' => 'Liked successfully',
            'id' => $profileId,
            'type' => $type,
            'likes' => $likes,
            'hide' => true
        ]);
    }
}
