<?php

namespace App\Http\Controllers\Backend;

use Carbon\Carbon;
use App\Models\Page;
use App\Models\User;
use App\Models\Category;
use App\Models\PageLike;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;

class PageManagementController extends Controller
{
    /**
     * Display a listing of pages.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        $query = Page::with('creator', 'category');
        
        // Filter by search term
        if ($request->filled('search')) {
            $search = $request->input('search');
            $query->where(function($q) use ($search) {
                $q->where('page_username', 'like', "%{$search}%")
                  ->orWhere('page_description', 'like', "%{$search}%");
            });
        }
        
        // Filter by category
        if ($request->filled('category')) {
            $category = $request->input('category');
            if ($category === 'uncategorized') {
                $query->whereNull('page_category');
            } elseif ($category !== 'all') {
                $query->where('page_category', $category);
            }
        }
        // Filter by status
        if ($request->filled('status')) {
            $status = $request->input('status');
            if (in_array($status, ['active', 'inactive'])) {
                $query->where('active', $status === 'active');
            }
        }
        
        // Filter by featured
        if ($request->filled('featured')) {
            $featured = $request->input('featured');
            if (in_array($featured, ['yes', 'no'])) {
                $query->where('is_featured', $featured === 'yes');
            }
        }
        
        // Order by
        $orderBy = $request->input('order_by', 'created_at');
        $orderDir = $request->input('order_dir', 'desc');
        $query->orderBy($orderBy, $orderDir);
        
        $pages = $query->paginate(10)->appends($request->query());
        
        // Get counts for the filter badges
        $totalPages = Page::count();
        $activePages = Page::where('active', 1)->count();
        $inactivePages = Page::where('active', 0)->count();
        $featuredPages = Page::where('is_featured', 1)->count();
        
        // Get categories for the filter dropdown
        $categories = Category::orderBy('name')->get();
        return view('admin.pages.page_management.index', compact(
            'pages', 
            'totalPages', 
            'activePages', 
            'inactivePages', 
            'featuredPages', 
            'categories'
        ));
    }
    
    /**
     * Display the specified page.
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function show($id)
    {
        $page = Page::with(['creator', 'category'])->findOrFail($id);
        
        // Get follower/like count
        $likeCount = PageLike::where('page_id', $id)->count();
        
        // Get recent followers
        $recentLikes = PageLike::where('page_id', $id)
            ->with('user')
            ->latest()
            ->limit(10)
            ->get();
        
        // Get page posts count
        $postCount = DB::table('posts')->where('page_id', $id)->count();
        
        return view('admin.pages.page_management.show', compact(
            'page', 
            'likeCount', 
            'recentLikes', 
            'postCount'
        ));
    }
    
    /**
     * Show the form for editing the specified page.
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function edit($id)
    {
        $page = Page::findOrFail($id);
        $categories = Category::orderBy('name')->get();
        
        return view('admin.pages.page_management.edit', compact('page', 'categories'));
    }
    
    /**
     * Update the specified page.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'required|string',
            'category_id' => 'required|exists:categories,id',
            'active' => 'boolean',
            'is_featured' => 'boolean',
        ]);
        
        $page = Page::findOrFail($id);
        
        // Update basic info
        $page->page_title = $request->input('name');
        // Create slug but check if it already exists
        $slug = strtolower(str_replace(' ', '-', $request->input('name')));
        $existingSlug = Page::where('page_username', $slug)->first();
        if ($existingSlug && $existingSlug->id != $page->id) {
            $slug .= '-' . $page->id;
        }
        $page->page_username = $slug;
        $page->page_description = $request->input('description');
        $page->page_category = $request->input('category_id');
        $page->active = $request->input('active', false);
        $page->is_featured = $request->input('is_featured', false);
        
        // Handle cover photo upload
        if ($request->hasFile('cover_photo')) {
            // Delete old photo if exists
            if ($page->cover && file_exists(public_path($page->cover))) {
                unlink(public_path($page->cover));
            }
            
            // Store the new photo
            $file = $request->file('cover_photo');
            $fileName = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('page_covers'), $fileName);
            $page->cover = 'page_covers/' . $fileName;
        }
        
        $page->save();
        
        return redirect()->route('admin.pages.index')
            ->with('success', 'Page updated successfully.');
    }
    
    /**
     * Toggle the featured status of a page.
     *
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function toggleFeatured($id)
    {
        $page = Page::findOrFail($id);
        $page->is_featured = !$page->is_featured;
        $page->save();
        
        return back()->with('success', 'Page featured status updated successfully.');
    }
    
    /**
     * Toggle the active status of a page.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function updateStatus(Request $request, $id)
    {
        $request->validate([
            'active' => 'required|boolean',
        ]);
        
        $page = Page::findOrFail($id);
        $page->active = $request->input('active');
        $page->save();
        
        return back()->with('success', 'Page status updated successfully.');
    }
    
    /**
     * Display a listing of featured pages.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\View\View
     */
    public function featured(Request $request)
    {
        $featuredPages = Page::with(['creator', 'category'])
            ->where('is_featured', true)
            ->orderBy('created_at', 'desc')
            ->paginate(12);
        
        // Get suggested pages to feature (popular non-featured pages)
        $suggestedPages = Page::with(['creator', 'category'])
            ->where('is_featured', false)
            ->where('active', true)
            ->withCount('likes')
            ->orderBy('likes_count', 'desc')
            ->limit(10)
            ->get();
        
        return view('admin.pages.page_management.featured', compact('featuredPages', 'suggestedPages'));
    }
    
    /**
     * Display statistics about pages.
     *
     * @return \Illuminate\View\View
     */
    // public function statistics()
    // {
    //     // Basic stats
    //     $totalPages = Page::count();
    //     $totalActivePages = Page::where('active', true)->count();
    //     $totalInactivePages = Page::where('active', false)->count();
    //     $totalFeaturedPages = Page::where('is_featured', true)->count();
    //     $activePages = Page::where('active', true)->count();
    //     $featuredPages = Page::where('is_featured', true)->count();
        
    //     // Pages by category
    //     $pagesByCategory = Category::withCount('pages')
    //         ->orderBy('pages_count', 'desc')
    //         ->get();
        
    //     // Most liked pages
    //     $mostLikedPages = Page::withCount('likes')
    //         ->orderBy('likes_count', 'desc')
    //         ->limit(10)
    //         ->get();
        
    //     // Most active pages (based on post count)
    //     $mostActivePages = Page::select('pages.*', DB::raw('COUNT(posts.id) as posts_count'))
    //         ->leftJoin('posts', 'pages.id', '=', 'posts.page_id')
    //         ->groupBy('pages.id')
    //         ->orderBy('posts_count', 'desc')
    //         ->limit(10)
    //         ->get();
        
    //     // Page creation trend (last 12 months)
    //     $pagesTrend = DB::table('pages')
    //         ->select(DB::raw('DATE_FORMAT(created_at, "%Y-%m") as month'), DB::raw('COUNT(*) as count'))
    //         ->where('created_at', '>=', now()->subMonths(12))
    //         ->groupBy('month')
    //         ->orderBy('month')
    //         ->get();
        
    //     // Format data for charts
    //     $trendLabels = $pagesTrend->pluck('month')->map(function ($month) {
    //         return date('M Y', strtotime($month . '-01'));
    //     })->toJson();
        
    //     $trendCounts = $pagesTrend->pluck('count')->toJson();
        
    //     $categoryLabels = $pagesByCategory->pluck('name')->toJson();
    //     $categoryCounts = $pagesByCategory->pluck('pages_count')->toJson();
        
    //     return view('admin.pages.page_management.statistics', compact(
    //         'totalPages',
    //         'totalActivePages',
    //         'totalInactivePages',
    //         'totalFeaturedPages',
    //         'activePages',
    //         'featuredPages',
    //         'pagesByCategory',  
    //         'mostLikedPages',
    //         'mostActivePages',
    //         'trendLabels',
    //         'trendCounts',
    //         'categoryLabels',
    //         'categoryCounts'
    //     ));
    // }

    public function statistics()
    {
        // Get basic stats
        $totalPages = Page::count();
        $activePages = Page::where('active', true)->count();
        $featuredPages = Page::where('is_featured', true)->count();
        $totalLikes = PageLike::count();
        
        // Get category data for chart
        $categoriesData = Category::withCount('pages')
            ->having('pages_count', '>', 0)
            ->get()
            ->map(function ($category) {
                return [
                    'name' => $category->name,
                    'count' => $category->pages_count
                ];
            })
            ->toArray();
            
        // Add uncategorized pages
        $uncategorizedCount = Page::whereNull('page_category')->count();
        if ($uncategorizedCount > 0) {
            $categoriesData[] = [
                'name' => 'Uncategorized',
                'count' => $uncategorizedCount
            ];
        }
        
        // Colors for charts
        $categoryColors = [
            '#4e73df', '#1cc88a', '#36b9cc', '#f6c23e', '#e74a3b', 
            '#6f42c1', '#5a5c69', '#858796', '#f8f9fc', '#d1d3e2'
        ];
        
        // Pages growth data (last 12 months)
        $growthData = [];
        for ($i = 11; $i >= 0; $i--) {
            $date = Carbon::now()->subMonths($i);
            $count = Page::whereYear('created_at', $date->year)
                ->whereMonth('created_at', $date->month)
                ->count();
                
            $growthData[] = [
                'month' => $date->format('M Y'),
                'count' => $count
            ];
        }
        
        // Most liked pages
        $topLikedPages = Page::withCount('likes')
            ->orderBy('likes_count', 'desc')
            ->take(5)
            ->get()
            ->map(function ($page) {
                return [
                    'name' => $page->name,
                    'likes_count' => $page->likes_count
                ];
            })
            ->toArray();
            
        // Page activity (last 30 days)
        $activityData = [];
        for ($i = 29; $i >= 0; $i--) {
            $date = Carbon::now()->subDays($i);
            $likesCount = PageLike::whereDate('created_at', $date->toDateString())->count();
            
            // Replace with actual posts count when implemented
            $postsCount = 0;
            
            $activityData[] = [
                'date' => $date->format('M d'),
                'likes' => $likesCount,
                'posts' => $postsCount
            ];
        }
        
        // Top pages for table
        $topPages = Page::with(['category', 'creator'])
            ->withCount(['likes', 'posts'])
            ->orderBy('likes_count', 'desc')
            ->take(10)
            ->get();
            
        return view('admin.pages.page_management.statistics', compact(
            'totalPages',
            'activePages',
            'featuredPages',
            'totalLikes',
            'categoriesData',
            'categoryColors',
            'growthData',
            'topLikedPages',
            'activityData',
            'topPages'
        ));
    }
    
    /**
     * Remove the specified page from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy($id)
    {
        $page = Page::findOrFail($id);
        $page->delete();
        
        return redirect()->route('admin.pages.index')
            ->with('success', 'Page deleted successfully.');
    }
}