<?php

namespace App\Http\Controllers;

use App\Models\JobCategory;
use App\Models\CustomPage;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;


class WebController extends BaseController
{

    // Constructor with auth check
    public function __construct()
    {
        $this->middleware('auth');
    }
    public function completeProfile()
    {
        $user = Auth::user();

        $completionSections = [
            'avatar' => !empty($user?->avatar),
            'cover' => !empty($user?->cover),
            'bio' => !empty($user?->bio),
            'address' => !empty($user?->address),
        ];

        $completedCount = collect($completionSections)->filter()->count();
        $totalCount = max(count($completionSections), 1);
        $progress = (int) round(($completedCount / $totalCount) * 100);

        return view('front_end.pages.profile.complete_profile', [
            'user' => $user,
            'progress' => $progress,
            'sectionsRemaining' => $totalCount - $completedCount,
        ]);
    }

    public function saveProfileCompletion(Request $request)
    {
        $user = Auth::user();
        
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'bio' => 'nullable|string|max:160',
            'location' => 'nullable|string|max:255',
            'avatar' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:2048',
            'cover' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:5120',
            'remove_avatar' => 'nullable|boolean',
            'remove_cover' => 'nullable|boolean',
        ]);

        if ($request->boolean('remove_avatar')) {
            $this->deleteMediaIfLocal($user->avatar);
            $user->avatar = null;
        }

        if ($request->boolean('remove_cover')) {
            $this->deleteMediaIfLocal($user->cover);
            $user->cover = null;
        }

        // Handle avatar upload
        if ($request->hasFile('avatar')) {
            $this->deleteMediaIfLocal($user->avatar);
            $avatarUpload = app('media')->store($request->file('avatar'), 'avatar');

            if (!($avatarUpload['success'] ?? false)) {
                return back()->withErrors([
                    'avatar' => $avatarUpload['error'] ?? 'Unable to upload avatar. Please try again.',
                ])->withInput();
            }

            $user->avatar = $avatarUpload['path'];
        }

        // Handle cover upload
        if ($request->hasFile('cover')) {
            $this->deleteMediaIfLocal($user->cover);
            $coverUpload = app('media')->store($request->file('cover'), 'cover');

            if (!($coverUpload['success'] ?? false)) {
                return back()->withErrors([
                    'cover' => $coverUpload['error'] ?? 'Unable to upload cover image. Please try again.',
                ])->withInput();
            }

            $user->cover = $coverUpload['path'];
        }

        $user->name = $validated['name'];
        $user->bio = $validated['bio'] ?? null;
        $user->address = $validated['location'] ?? null;
        $user->save();

        $user->setMeta('profile_completion_status', 'complete');
        $user->setMeta('profile_completion_completed_at', now()->toDateTimeString());
        $user->setMeta('profile_completion_skipped_at', null);

        // Redirect to intended URL or home
        $intendedUrl = session('intended_url', route('newsfeed'));
        session()->forget('intended_url');

        return redirect($intendedUrl)->with('success', 'Profile completed successfully!');
    }

    public function skipProfileCompletion()
    {
        $user = Auth::user();

        if ($user) {
            $user->setMeta('profile_completion_status', 'skipped');
            $user->setMeta('profile_completion_skipped_at', now()->toDateTimeString());
        }

        $intendedUrl = session('intended_url', route('newsfeed'));
        session()->forget('intended_url');

        return redirect($intendedUrl)->with('info', 'You can finish your profile anytime from settings.');
    }

    protected function deleteMediaIfLocal(?string $path): void
    {
        if (empty($path) || filter_var($path, FILTER_VALIDATE_URL)) {
            return;
        }

        $cleanPath = ltrim($path, '/');

        if (Storage::disk('public')->exists($cleanPath)) {
            Storage::disk('public')->delete($cleanPath);
        }

        $dotPosition = strrpos($cleanPath, '.');
        if ($dotPosition !== false) {
            $basename = substr($cleanPath, 0, $dotPosition);
            $extension = substr($cleanPath, $dotPosition + 1);
            foreach (['small', 'medium', 'large'] as $size) {
                $thumbnailPath = sprintf('%s_%s.%s', $basename, $size, $extension);
                if (Storage::disk('public')->exists($thumbnailPath)) {
                    Storage::disk('public')->delete($thumbnailPath);
                }
            }
        }
    }

    public function newsfeed()
    {
         // Redirect logged-in users to the dashboard
         if (!Auth::check()) {
            if(setting('landing_page')=='login'){
                return redirect()->route('login')->with('info', 'You are not logged in.');
            }
            else{
                return redirect()->route('register')->with('info', 'You are not logged in.');

            }
        }
        return view('front_end.pages.newsfeed.home');
    }

    public function friends()
    {
        return view('front_end.pages.friends.friends');
    }

    public function pages()
    {
        $totalPages = \App\Models\Page::count();
        $myPages = \App\Models\Page::where('user_id', Auth::id())->count();
        return view('front_end.pages.pages.all_pages', compact('totalPages', 'myPages'));
    }

    public function my_pages()
    {
        $pages = \App\Models\Page::where('user_id', Auth::id())
                    ->orderBy('created_at', 'desc')
                    ->paginate(10);
                    
        return view('front_end.pages.pages.my_pages', compact('pages'));
    }

    public function liked_pages()
    {
        $likedPages = \App\Models\Page::whereHas('likes', function($query) {
                        $query->where('user_id', Auth::id());
                    })
                    ->orderBy('created_at', 'desc')
                    ->paginate(10);
                    
        return view('front_end.pages.pages.liked_pages', compact('likedPages'));
    }

    public function detail_page($slug)
    {
        // First check if it's a regular Page
        $page = \App\Models\Page::with([
                'creator:id,name,avatar,username'
            ])
            ->withCount('likes')
            ->where(function ($query) use ($slug) {
                $query->where('page_username', $slug);
                
                // Only check id if slug is numeric
                if (is_numeric($slug)) {
                    $query->orWhere('id', (int) $slug);
                }
            })
            ->first();
        
        // If not a regular page, check if it's a custom page
        if (!$page) {
            $customPage = \App\Models\CustomPage::where('slug', $slug)
                ->where('active', true)
                ->first();
            
            if ($customPage) {
                // Redirect to custom page handler
                return app(\App\Http\Controllers\PageController::class)->showCustomPage($slug);
            }
            
            // Neither found, show 404
            abort(404, 'Page not found');
        }

        $page->cover_url = getMedia($page->cover);
        $page->avatar_url = getMedia($page->avatar);

        if ($page->creator) {
            $page->creator->avatar_url = getMedia($page->creator->avatar);
        }

        $recentFollowers = $page->likes()
            ->with(['user:id,name,username,avatar'])
            ->latest()
            ->take(5)
            ->get()
            ->map(function ($like) {
                if ($like->user) {
                    $like->user->avatar_url = getMedia($like->user->avatar);
                }
                return $like;
            });

        // Fetch page posts with media (for photos and videos)
        $postsWithMedia = \App\Models\Post::where('page_id', $page->id)
            ->where('status', 1)
            ->whereHas('media')
            ->with(['media' => function($query) {
                $query->orderBy('created_at', 'desc');
            }])
            ->orderBy('created_at', 'desc')
            ->limit(50)
            ->get();

        $isOwner = Auth::id() === $page->user_id;
        $isFollowing = Auth::user()?->hasLikedPage($page->id) ?? false;
        // User can post if they're the owner or if they're following the page
        $canPost = $isOwner || $isFollowing;

        return view('front_end.pages.pages.detail_page', [
            'page' => $page,
            'recentFollowers' => $recentFollowers,
            'photos' => $postsWithMedia,
            'isOwner' => $isOwner,
            'isFollowing' => $isFollowing,
            'canPost' => $canPost,
        ]);
    }

    public function create_page()
    {
        $categories = [
            'business_finance' => 'Business & Finance',
            'art_entertainment' => 'Art & Entertainment',
            'education' => 'Education',
            'food_drink' => 'Food & Drink',
            'health_wellness' => 'Health & Wellness',
            'technology' => 'Technology',
            'sports' => 'Sports',
            'travel' => 'Travel',
            'fashion' => 'Fashion',
            'science' => 'Science',
            'politics' => 'Politics',
            'real_estate' => 'Real Estate',
            'automotive' => 'Automotive',
            'gaming' => 'Gaming',
            'parenting' => 'Parenting',
            'spirituality' => 'Spirituality',
            'personal_development' => 'Personal Development',
            'law_legal' => 'Law & Legal',
            'history' => 'History',
            'environment' => 'Environment',
            'music' => 'Music',
            'movies_tv' => 'Movies & TV',
            'home_garden' => 'Home & Garden',
            'books_literature' => 'Books & Literature',
            'pets_animals' => 'Pets & Animals',
            'career' => 'Career',
            'relationships' => 'Relationships',
            'fitness' => 'Fitness',
            'news_media' => 'News & Media',
            'marketing' => 'Marketing',
            'social_media' => 'Social Media',
            'photography' => 'Photography'
        ];
    
        return view('front_end.pages.pages.create_page', compact('categories'));
    }

    public function groups()
    {
        // Total groups
        $totalGroups = \App\Models\Group::count();
        // Total joined groups
        $totalJoinedGroups = \App\Models\GroupMember::where('user_id', Auth::id())->count();
        // Total admin groups
        $totalAdminGroups = \App\Models\Group::where('user_id', Auth::id())->count();
        return view('front_end.pages.groups.all_groups', compact('totalGroups', 'totalJoinedGroups', 'totalAdminGroups'));
    }

    public function create_group()
    {
        return view('front_end.pages.groups.create_group');
    }

    public function my_groups()
    {
        $groups = \App\Models\Group::where('user_id', Auth::id())
                    ->orderBy('created_at', 'desc')
                    ->paginate(10);
                    
        return view('front_end.pages.groups.my_groups', compact('groups'));
    }

    public function liked_groups()
    {
        return view('front_end.pages.groups.liked_groups');
    }

    public function details($slug){
        $group = \App\Models\Group::withCount('members')
            ->where('slug', $slug)
            ->firstOrFail();
        
        $group->cover_url = getMedia($group->cover_image);
        $group->avatar_url = getMedia($group->avatar ?? null);
        
        $checkAlreadyMember = \App\Models\GroupMember::where('group_id', $group->id)->where('user_id', Auth::id())->first();
        $group->already_member = $checkAlreadyMember ? true : false;
        $group->is_group_owner = Auth::id() === $group->user_id;
        
        $user = \App\Models\User::find($group->user_id);
        if ($user) {
            $user->avatar_url = getMedia($user->avatar);
            $group->creator = $user;
        }
        
        // Get members with proper data
        $members = \App\Models\GroupMember::where('group_id', $group->id)
            ->join('users', 'group_members.user_id', '=', 'users.id')
            ->select('users.id', 'users.name', 'users.avatar', 'users.username', 'users.first_name', 'users.last_name', 'group_members.created_at as joined_at')
            ->orderBy('group_members.created_at', 'desc')
            ->get()
            ->map(function($member) {
                $member->avatar_url = getMedia($member->avatar);
                return $member;
            });
        $group->members = $members;
        
        // Get recent members for sidebar
        $recentMembers = $members->take(6);
        
        // Fetch group posts with media (for photos and videos)
        $postsWithMedia = \App\Models\Post::where('group_id', $group->id)
            ->where('status', 1)
            ->whereHas('media')
            ->with(['media' => function($query) {
                $query->orderBy('created_at', 'desc');
            }])
            ->orderBy('created_at', 'desc')
            ->limit(50)
            ->get();
        
        // User can post if they're a member or owner
        $canPost = $group->already_member || $group->is_group_owner;
        
        return view('front_end.pages.groups.details', [
            'group' => $group,
            'recentMembers' => $recentMembers,
            'photos' => $postsWithMedia,
            'canPost' => $canPost,
        ]);
    }

    // public function events()
    // {
    //     $totalEvents = \App\Models\Event::count();
    //     // My events and upcoming events
    //     $myEvents = \App\Models\Event::where('user_id', Auth::id())->get();
    //     $upcomingEvents = \App\Models\Event::where('start_date', '>', now())->get();
    //     //on going events
    //     $ongoingEvents = \App\Models\Event::where('start_date', '<=', now())->where('end_date', '>=', now())->get();
    //     return view('front_end.pages.events.all_events', compact('totalEvents', 'myEvents', 'upcomingEvents', 'ongoingEvents'));
    // }

    // public function create_event()
    // {
    //     return view('front_end.pages.events.create_event');
    // }

    // public function my_events()
    // {
    //     return view('front_end.pages.events.my_events');
    // }

    public function wallet()
    {
        return view('front_end.pages.wallet.wallet');
    }
    public function marketplace()
    {
        return view('front_end.pages.marketplace.marketplace_main');
    }
    public function jobs()
    {
        return view('front_end.pages.jobs.jobs_main');
    }

    public function jobs_create()
    {
      
            // Get all active job categories
            $jobCategories = JobCategory::where('status', 1)
                ->orderBy('name', 'asc')
                ->get();
    
            return view('front_end.pages.jobs.job_create', [
                'jobCategories' => $jobCategories,
                'currencies' => config('constants.currencies'), // If you have currencies in config
                'jobTypes' => [
                    'full-time' => 'Full Time',
                    'part-time' => 'Part Time',
                    'contract' => 'Contract',
                    'internship' => 'Internship',
                    'temporary' => 'Temporary',
                    'freelance' => 'Freelance'
                ]
            ]);
       
        //return view('front_end.pages.jobs.job_create');
    }

    public function jobs_detail($id)
    {
        return view('front_end.pages.jobs.job_detail');
    }
    public function jobs_applied()
    {
        return view('front_end.pages.jobs.job_applied');
    }

    public function jobs_discover()
    {
        return view('front_end.pages.jobs.job_discover');
    }

    public function bloodbank()
    {
        return view('front_end.pages.bloodbank.bloodbank_main');
    }
    
    public function create_story()
    {
        return view('front_end.pages.newsfeed.create_story');
    }

    // Logout Method
    public function logout(Request $request)
    {
        Auth::logout(); // Logout the user

        // Invalidate session
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('login')->with('success', 'You have been logged out.');
    }
}
