<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ForumCategory;
use App\Models\ForumBoard;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class ForumController extends Controller
{
    // =========================================================================
    // Forum Categories Methods
    // =========================================================================
    
    /**
     * Display a listing of forum categories
     */
    public function categories()
    {
        $categories = ForumCategory::with('boards')
            ->orderBy('order')
            ->get();
            
        return view('admin.forum.categories.index', compact('categories'));
    }
    
    /**
     * Show the form for creating a new category
     */
    public function createCategory()
    {
        $roles = Role::all();
        $permissions = Permission::all();
        
        return view('admin.forum.categories.create', compact('roles', 'permissions'));
    }
    
    /**
     * Store a newly created category in storage
     */
    public function storeCategory(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|max:255',
            'description' => 'nullable',
            'order' => 'required|integer|min:0',
            'is_active' => 'boolean',
            'is_public' => 'boolean',
            'required_roles' => 'nullable|array',
            'required_roles.*' => 'exists:roles,name',
            'required_permissions' => 'nullable|array',
            'required_permissions.*' => 'exists:permissions,name',
        ], [
            'required_roles.*.exists' => 'One or more selected roles do not exist.',
            'required_permissions.*.exists' => 'One or more selected permissions do not exist.',
        ]);
        
        // Generate slug from name
        $validated['slug'] = Str::slug($request->name);
        
        // Handle checkboxes (they're not included in request if unchecked)
        $validated['is_active'] = $request->has('is_active');
        $validated['is_public'] = $request->has('is_public');
        
        // Handle required roles and permissions (set to null if empty)
        $validated['required_roles'] = !empty($request->required_roles) ? $request->required_roles : null;
        $validated['required_permissions'] = !empty($request->required_permissions) ? $request->required_permissions : null;
        
        try {
            ForumCategory::create($validated);
            
            return redirect()->route('admin.forum.categories')
                ->with('success', 'Forum category created successfully.');
        } catch (\Exception $e) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Error creating category: ' . $e->getMessage());
        }
    }
    
    /**
     * Show the form for editing the specified category
     */
    public function editCategory(ForumCategory $category)
    {
        $roles = Role::all();
        $permissions = Permission::all();
        
        return view('admin.forum.categories.edit', compact('category', 'roles', 'permissions'));
    }
    
    /**
     * Update the specified category in storage
     */
    public function updateCategory(Request $request, ForumCategory $category)
    {
        $validated = $request->validate([
            'name' => 'required|max:255',
            'description' => 'nullable',
            'order' => 'required|integer|min:0',
            'is_active' => 'boolean',
            'is_public' => 'boolean',
            'required_roles' => 'nullable|array',
            'required_roles.*' => 'exists:roles,name',
            'required_permissions' => 'nullable|array',
            'required_permissions.*' => 'exists:permissions,name',
        ], [
            'required_roles.*.exists' => 'One or more selected roles do not exist.',
            'required_permissions.*.exists' => 'One or more selected permissions do not exist.',
        ]);
        
        // Generate slug from name
        $validated['slug'] = Str::slug($request->name);
        
        // Handle checkboxes
        $validated['is_active'] = $request->has('is_active');
        $validated['is_public'] = $request->has('is_public');
        
        // Handle required roles and permissions
        $validated['required_roles'] = !empty($request->required_roles) ? $request->required_roles : null;
        $validated['required_permissions'] = !empty($request->required_permissions) ? $request->required_permissions : null;
        
        try {
            $category->update($validated);
            
            return redirect()->route('admin.forum.categories')
                ->with('success', 'Forum category updated successfully.');
        } catch (\Exception $e) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Error updating category: ' . $e->getMessage());
        }
    }
    
    /**
     * Remove the specified category from storage
     */
    public function destroyCategory(ForumCategory $category)
    {
        try {
            // Check if category has boards
            if ($category->boards()->count() > 0) {
                return redirect()->route('admin.forum.categories')
                    ->with('error', 'Cannot delete category with boards. Delete the boards first.');
            }
            
            $categoryName = $category->name;
            $category->delete();
            
            return redirect()->route('admin.forum.categories')
                ->with('success', "Forum category '{$categoryName}' deleted successfully.");
        } catch (\Exception $e) {
            return redirect()->route('admin.forum.categories')
                ->with('error', 'Error deleting category: ' . $e->getMessage());
        }
    }
    
    // =========================================================================
    // Forum Boards Methods
    // =========================================================================
    
    /**
     * Display a listing of forum boards
     */
    public function boards()
    {
        $boards = ForumBoard::with(['category', 'threads'])
            ->orderBy('order')
            ->get();
            
        return view('admin.forum.boards.index', compact('boards'));
    }
    
    /**
     * Show the form for creating a new board
     */
    public function createBoard()
    {
        $categories = ForumCategory::where('is_active', true)
            ->orderBy('order')
            ->pluck('name', 'id');
        
        $roles = Role::all();
        $permissions = Permission::all();
            
        return view('admin.forum.boards.create', compact('categories', 'roles', 'permissions'));
    }
    
    /**
     * Store a newly created board in storage
     */
    public function storeBoard(Request $request)
    {
        $validated = $request->validate([
            'category_id' => 'required|exists:forum_categories,id',
            'name' => 'required|max:255',
            'description' => 'nullable',
            'order' => 'required|integer|min:0',
            'is_active' => 'boolean',
            'is_public' => 'boolean',
            'required_roles' => 'nullable|array',
            'required_roles.*' => 'exists:roles,name',
            'required_permissions' => 'nullable|array',
            'required_permissions.*' => 'exists:permissions,name',
        ], [
            'category_id.required' => 'Please select a category.',
            'category_id.exists' => 'The selected category does not exist.',
            'required_roles.*.exists' => 'One or more selected roles do not exist.',
            'required_permissions.*.exists' => 'One or more selected permissions do not exist.',
        ]);
        
        // Generate slug from name
        $validated['slug'] = Str::slug($request->name);
        
        // Handle checkboxes
        $validated['is_active'] = $request->has('is_active');
        $validated['is_public'] = $request->has('is_public');
        
        // Handle required roles and permissions
        $validated['required_roles'] = !empty($request->required_roles) ? $request->required_roles : null;
        $validated['required_permissions'] = !empty($request->required_permissions) ? $request->required_permissions : null;
        
        try {
            ForumBoard::create($validated);
            
            return redirect()->route('admin.forum.boards')
                ->with('success', 'Forum board created successfully.');
        } catch (\Exception $e) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Error creating board: ' . $e->getMessage());
        }
    }
    
    /**
     * Show the form for editing the specified board
     */
    public function editBoard(ForumBoard $board)
    {
        $categories = ForumCategory::where('is_active', true)
            ->orderBy('order')
            ->pluck('name', 'id');
        
        $roles = Role::all();
        $permissions = Permission::all();
            
        return view('admin.forum.boards.edit', compact('board', 'categories', 'roles', 'permissions'));
    }
    
    /**
     * Update the specified board in storage
     */
    public function updateBoard(Request $request, ForumBoard $board)
    {
        $validated = $request->validate([
            'category_id' => 'required|exists:forum_categories,id',
            'name' => 'required|max:255',
            'description' => 'nullable',
            'order' => 'required|integer|min:0',
            'is_active' => 'boolean',
            'is_public' => 'boolean',
            'required_roles' => 'nullable|array',
            'required_roles.*' => 'exists:roles,name',
            'required_permissions' => 'nullable|array',
            'required_permissions.*' => 'exists:permissions,name',
        ], [
            'category_id.required' => 'Please select a category.',
            'category_id.exists' => 'The selected category does not exist.',
            'required_roles.*.exists' => 'One or more selected roles do not exist.',
            'required_permissions.*.exists' => 'One or more selected permissions do not exist.',
        ]);
        
        // Generate slug from name
        $validated['slug'] = Str::slug($request->name);
        
        // Handle checkboxes
        $validated['is_active'] = $request->has('is_active');
        $validated['is_public'] = $request->has('is_public');
        
        // Handle required roles and permissions
        $validated['required_roles'] = !empty($request->required_roles) ? $request->required_roles : null;
        $validated['required_permissions'] = !empty($request->required_permissions) ? $request->required_permissions : null;
        
        try {
            $board->update($validated);
            
            return redirect()->route('admin.forum.boards')
                ->with('success', 'Forum board updated successfully.');
        } catch (\Exception $e) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Error updating board: ' . $e->getMessage());
        }
    }
    
    /**
     * Remove the specified board from storage
     */
    public function destroyBoard(ForumBoard $board)
    {
        try {
            // Check if board has threads
            if ($board->threads()->count() > 0) {
                return redirect()->route('admin.forum.boards')
                    ->with('error', 'Cannot delete board with threads. Delete the threads first.');
            }
            
            $boardName = $board->name;
            $board->delete();
            
            return redirect()->route('admin.forum.boards')
                ->with('success', "Forum board '{$boardName}' deleted successfully.");
        } catch (\Exception $e) {
            return redirect()->route('admin.forum.boards')
                ->with('error', 'Error deleting board: ' . $e->getMessage());
        }
    }

    // =========================================================================
    // Utility Methods
    // =========================================================================

    /**
     * Get summary statistics for admin dashboard
     */
    public function getStatistics()
    {
        $stats = [
            'total_categories' => ForumCategory::count(),
            'active_categories' => ForumCategory::where('is_active', true)->count(),
            'private_categories' => ForumCategory::where('is_public', false)->count(),
            'total_boards' => ForumBoard::count(),
            'active_boards' => ForumBoard::where('is_active', true)->count(),
            'private_boards' => ForumBoard::where('is_public', false)->count(),
            'total_threads' => \App\Models\ForumThread::count(),
            'total_posts' => \App\Models\ForumPost::count(),
        ];

        return $stats;
    }

    /**
     * Bulk update category/board access settings
     */
    public function bulkUpdateAccess(Request $request)
    {
        $validated = $request->validate([
            'type' => 'required|in:categories,boards',
            'ids' => 'required|array',
            'ids.*' => 'integer',
            'action' => 'required|in:make_public,make_private,add_role,remove_role,add_permission,remove_permission',
            'role_name' => 'nullable|exists:roles,name',
            'permission_name' => 'nullable|exists:permissions,name',
        ]);

        try {
            $model = $validated['type'] === 'categories' ? ForumCategory::class : ForumBoard::class;
            $items = $model::whereIn('id', $validated['ids'])->get();
            $updated = 0;

            foreach ($items as $item) {
                switch ($validated['action']) {
                    case 'make_public':
                        $item->update(['is_public' => true]);
                        $updated++;
                        break;
                    
                    case 'make_private':
                        $item->update(['is_public' => false]);
                        $updated++;
                        break;
                    
                    case 'add_role':
                        if ($validated['role_name']) {
                            $roles = $item->required_roles ?? [];
                            if (!in_array($validated['role_name'], $roles)) {
                                $roles[] = $validated['role_name'];
                                $item->update(['required_roles' => $roles]);
                                $updated++;
                            }
                        }
                        break;
                    
                    case 'remove_role':
                        if ($validated['role_name'] && $item->required_roles) {
                            $roles = array_diff($item->required_roles, [$validated['role_name']]);
                            $item->update(['required_roles' => empty($roles) ? null : array_values($roles)]);
                            $updated++;
                        }
                        break;
                    
                    case 'add_permission':
                        if ($validated['permission_name']) {
                            $permissions = $item->required_permissions ?? [];
                            if (!in_array($validated['permission_name'], $permissions)) {
                                $permissions[] = $validated['permission_name'];
                                $item->update(['required_permissions' => $permissions]);
                                $updated++;
                            }
                        }
                        break;
                    
                    case 'remove_permission':
                        if ($validated['permission_name'] && $item->required_permissions) {
                            $permissions = array_diff($item->required_permissions, [$validated['permission_name']]);
                            $item->update(['required_permissions' => empty($permissions) ? null : array_values($permissions)]);
                            $updated++;
                        }
                        break;
                }
            }

            $itemType = $validated['type'] === 'categories' ? 'categories' : 'boards';
            return redirect()->back()
                ->with('success', "Successfully updated {$updated} {$itemType}.");

        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Error performing bulk update: ' . $e->getMessage());
        }
    }

    /**
     * Export forum structure for backup
     */
    public function exportStructure()
    {
        try {
            $categories = ForumCategory::with(['boards' => function($query) {
                $query->orderBy('order');
            }])->orderBy('order')->get();

            $structure = [
                'categories' => $categories->toArray(),
                'exported_at' => now()->toISOString(),
                'version' => '1.0'
            ];

            $filename = 'forum_structure_' . now()->format('Y-m-d_H-i-s') . '.json';
            
            return response()->json($structure)
                ->header('Content-Disposition', 'attachment; filename="' . $filename . '"')
                ->header('Content-Type', 'application/json');

        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Error exporting forum structure: ' . $e->getMessage());
        }
    }

    /**
     * Import forum structure from backup
     */
    public function importStructure(Request $request)
    {
        $request->validate([
            'structure_file' => 'required|file|mimes:json|max:2048'
        ]);

        try {
            $content = file_get_contents($request->file('structure_file')->getPathname());
            $structure = json_decode($content, true);

            if (!$structure || !isset($structure['categories'])) {
                throw new \Exception('Invalid structure file format.');
            }
            
            return redirect()->back()
                ->with('success', 'Forum structure import feature is ready for implementation.');

        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Error importing forum structure: ' . $e->getMessage());
        }
    }
}