<?php

namespace App\Http\Controllers\website;

use App\Http\Controllers\Controller;
use App\Models\HomeSection;
use App\Models\UserProfile;
use App\Models\UserProfileLike;
use Illuminate\Support\Facades\Auth; // Import Auth Facade
use App\Models\Message;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function index()
    {
        $loggedInUserId = auth()->id();
        $loggedInUser = auth()->user();
        $loggedInGender = optional(UserProfile::where('user_id', $loggedInUserId)->first())->gender;

        $hasActiveSubscription = false;
        if ($loggedInUserId) {
            $subscription = DB::table('user_subscription')
                ->where('user_id', $loggedInUserId)
                ->orderByDesc('id') // ✅ get latest record first
                ->limit(1)
                ->first();

            if (
                $subscription &&
                $subscription->subscription_type !== 'free' &&
                !is_null($subscription->subscription_start) &&
                !is_null($subscription->subscription_end) &&
                Carbon::parse($subscription->subscription_start)->isPast() &&
                Carbon::parse($subscription->subscription_end)->isFuture()
            ) {
                $hasActiveSubscription = true;
            }

            // Debug output (optional)
            // dd($subscription, $hasActiveSubscription);
        }
        // Gender filter
        $oppositeGender = null;
        if ($loggedInGender === 'male') {
            $oppositeGender = 'female';
        } elseif ($loggedInGender === 'female') {
            $oppositeGender = 'male';
        }elseif($loggedInGender === 'others'){
            $oppositeGender = 'others';
        }

        $bookCovers = UserProfile::with('user')
            ->whereNotNull('book_cover')
            ->where('user_id', '!=', $loggedInUserId)
            ->where('verification_status', 'verified') 
            ->when($oppositeGender, function ($query) use ($oppositeGender) {
                $query->where('gender', $oppositeGender);
            })
            ->get();

        $countries = $bookCovers->pluck('country')->unique()->sort()->values();
        $data = HomeSection::first();

        $likedItems = UserProfileLike::where('user_id', $loggedInUserId)
            ->get()
            ->groupBy('type');

        $likedProfileIds = $likedItems->get('profile', collect())->pluck('profile_id')->toArray();
        $likedBookIds = $likedItems->get('book', collect())->pluck('profile_id')->toArray();

        $chatUserCounts = [];
        foreach ($bookCovers as $cover) {
            $userId = $cover->user_id;

            $chatUserIds = Message::where(function ($query) use ($userId) {
                $query->where('sender_id', $userId)
                    ->orWhere('receiver_id', $userId);
            })
                ->get()
                ->map(function ($msg) use ($userId) {
                    return $msg->sender_id == $userId ? $msg->receiver_id : $msg->sender_id;
                })
                ->unique()
                ->values();

            // Filter out deleted users
            $existingUserIds = \App\Models\User::whereIn('id', $chatUserIds)->pluck('id')->toArray();
            $chatUserIds = $chatUserIds->filter(function ($id) use ($existingUserIds) {
                return in_array($id, $existingUserIds);
            });

            $chatUserCounts[$userId] = $chatUserIds->count();
        }

        $page = DB::table('home_sections')->select('page_title')->first();
        $pageTitle = $page->page_title ?? 'Home';

        return view('website.index', compact(
            'bookCovers',
            'countries',
            'data',
            'likedProfileIds',
            'likedBookIds',
            'chatUserCounts',
            'hasActiveSubscription', // 🔁 Pass to view
            'pageTitle'
        ));





        // public function index()
        // {
        //     $loggedInUserId = auth()->id(); // Get the currently logged-in user's ID

        //     $bookCovers = UserProfile::with('user')
        //         ->whereNotNull('book_cover')
        //         ->where('user_id', '!=', $loggedInUserId) // Exclude the logged-in user's record
        //         ->get();

        //     $countries = $bookCovers->pluck('country')->unique()->sort()->values();

        //     $data = HomeSection::first();

        //     $likedItems = UserProfileLike::where('user_id', auth()->id())
        //         ->get()
        //         ->groupBy('type');

        //     $likedProfileIds = $likedItems->get('profile', collect())->pluck('profile_id')->toArray();
        //     $likedBookIds = $likedItems->get('book', collect())->pluck('profile_id')->toArray();

        //     return view('website.index', compact('bookCovers', 'countries', 'data', 'likedProfileIds', 'likedBookIds'));





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

        // Fetch the book covers for the logged-in user
        // $bookCovers = UserProfile::where('user_id', $userId)
        //                          ->whereNotNull('book_cover')
        //                          ->pluck('book_cover');  // Get only the book_cover field

        // return view('website.index', compact('bookCovers'));
    }
}
