<?php

namespace App\Http\Controllers;

use App\Models\FAQ;
use App\Models\FAQItem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use App\Models\PermissionsModules;

class FAQController extends Controller
{
    /**
     * Display a listing of FAQ groups with their items
     */
    public function index(Request $request)
    {
        $query = FAQ::with(['module', 'activeItems']);
        // Apply filters if provided
        if ($request->has('module_id') && $request->module_id) {
            $query->where('module_id', $request->module_id);
        }
        if ($request->has('page_slug') && $request->page_slug) {
            $query->where('page_slug', $request->page_slug);
        }
        if ($request->has('status') && $request->status !== '') {
            $query->where('status', $request->status);
        }
        if ($request->has('search') && $request->search) {
            $query->where(function ($q) use ($request) {
                $q->where('title', 'like', '%' . strtolower($request->search) . '%')
                    ->orWhere('description', 'like', '%' . strtolower($request->search) . '%')
                    ->orWhereHas('items', function ($itemQuery) use ($request) {
                        $itemQuery->where('question', 'like', '%' . strtolower($request->search) . '%')
                                  ->orWhere('answer', 'like', '%' . strtolower($request->search) . '%');
                    });
            });
        }
        $faqs = $query->ordered()->latest();
        if($request->filled('pagination') || !empty($request->filters)){
            return $this->searchFilter($faqs, $request);
        }
        return $this->withCount($faqs, 'FAQ groups retrieved successfully');
    }

    /**
     * Store a newly created FAQ group with items
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'module_id' => 'nullable|integer',
            'page_slug' => 'nullable|string|max:255',
            'sort_order' => 'nullable|integer',
            'status' => 'nullable|boolean',
            'items' => 'required|array|min:1',
            'items.*.question' => 'required|string',
            'items.*.answer' => 'required|string',
            'items.*.sort_order' => 'nullable|integer',
            'items.*.status' => 'nullable|boolean'
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors(), 422);
        }
        try {
            DB::beginTransaction();   
            $faqData = $validator->validated();
            $items = $faqData['items'];
            unset($faqData['items']);
            // Set defaults
            if (!isset($faqData['status'])) {
                $faqData['status'] = 1;
            }
            if (!isset($faqData['sort_order'])) {
                $faqData['sort_order'] = 0;
            }
            // Create FAQ group
            $faq = FAQ::create($faqData);
            // Create FAQ items
            foreach ($items as $index => $itemData) {
                $itemData['faq_id'] = $faq->id;
                if (!isset($itemData['status'])) {
                    $itemData['status'] = 1;
                }
                if (!isset($itemData['sort_order'])) {
                    $itemData['sort_order'] = $index + 1;
                }
                FAQItem::create($itemData);
            }
            DB::commit();
            $faq->load(['module', 'activeItems']);            
            return $this->success($faq, 'FAQ group created successfully');
            
        } catch (\Exception $e) {
            DB::rollback();
            Log::error('FAQ creation failed: ' . $e->getMessage());
            return $this->error('Failed to create FAQ group', 500);
        }
    }

    /**
     * Display the specified FAQ group with items
     */
    public function show($id)
    {
        $faq = FAQ::with(['module', 'activeItems'])->find($id);
        if (!$faq) {
            return $this->error('FAQ group not found', 404);
        }
        return $this->success($faq, 'FAQ group retrieved successfully');
    }

    /**
     * Update the specified FAQ group and its items
     */
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|integer|exists:faqs,id',
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'module_id' => 'nullable|integer',
            'page_slug' => 'nullable|string|max:255',
            'sort_order' => 'nullable|integer',
            'status' => 'nullable|boolean',
            'items' => 'required|array|min:1',
            'items.*.id' => 'nullable|integer|exists:faq_items,id',
            'items.*.question' => 'required|string',
            'items.*.answer' => 'required|string',
            'items.*.sort_order' => 'nullable|integer',
            'items.*.status' => 'nullable|boolean',
            'deleted_item_ids' => 'nullable|array',
            'deleted_item_ids.*' => 'integer|exists:faq_items,id'
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors(), 422);
        }
        try {
            DB::beginTransaction();   
            $validatedData = $validator->validated();
            $faq = FAQ::find($validatedData['id']);
            if (!$faq) {
                return $this->error('FAQ group not found', 404);
            }
            $items = $validatedData['items'];
            if(!$request->module_id){
                $faq->module_id = null;
                $faq->save();
             }
            $deletedItemIds = $validatedData['deleted_item_ids'] ?? [];
            // Remove items data and id from FAQ update data
            unset($validatedData['items'], $validatedData['deleted_item_ids'], $validatedData['id']);
            // Update FAQ group
            $faq->update($validatedData);
            // Delete removed items
            if (!empty($deletedItemIds)) {
                FAQItem::whereIn('id', $deletedItemIds)
                       ->where('faq_id', $faq->id)
                       ->delete();
            }
            // Update or create items
            foreach ($items as $index => $itemData) {
                $itemData['faq_id'] = $faq->id;
                if (!isset($itemData['status'])) {
                    $itemData['status'] = 1;
                }
                if (!isset($itemData['sort_order'])) {
                    $itemData['sort_order'] = $index + 1;
                }
                if (isset($itemData['id']) && $itemData['id']) {
                    // Update existing item
                    $item = FAQItem::find($itemData['id']);
                    if ($item && $item->faq_id == $faq->id) {
                        $item->update($itemData);
                    }
                } else {
                    // Create new item
                    unset($itemData['id']);
                    FAQItem::create($itemData);
                }
            }
            DB::commit();
            // Load with relationships
            $faq->load(['module', 'activeItems']);
            return $this->success($faq, 'FAQ group updated successfully');
            
        } catch (\Exception $e) {
            DB::rollback();
            Log::error('FAQ update failed: ' . $e->getMessage());
            return $this->error('Failed to update FAQ group', 500);
        }
    }

    /**
     * Remove the specified FAQ group and all its items
     */
    public function destroy($id)
    {
            DB::beginTransaction();
            $faq = FAQ::find($id);
            if (!$faq) {
                return $this->error('FAQ group not found', 404);
            }
            // Delete all items (cascade should handle this, but explicit is better)
            FAQItem::where('faq_id', $id)->delete();
            // Delete the FAQ group
            $faq->delete();
            DB::commit();
            return $this->message('FAQ group and all items deleted successfully');
        
    }

    /**
     * Toggle FAQ group status
     */
    public function updateStatus($id)
    {
        $faq = FAQ::find($id);
        if (!$faq) {
            return $this->error('FAQ group not found', 404);
        }
        $newStatus = !$faq->status;  // Flip the status
        $faq->update(['status' => $newStatus]);
        // Load with relationships
        $faq->load(['module', 'activeItems']);
        
        return $this->success($faq, "FAQ group status updated successfully to " . ($newStatus ? 'enabled' : 'disabled'));
    }
    

    /**
     * Get FAQ groups by module ID
     */
    public function getByModule($moduleId)
    {
        $faqs = FAQ::with(['module', 'activeItems'])
            ->where('module_id', $moduleId)
            ->active()
            ->ordered()
            ->get();
        return $this->success($faqs, 'Module FAQ groups retrieved successfully');
    }

    /**
     * Get FAQ groups by page slug
     */
    public function getByPageSlug($pageSlug = null)
    {
        // If no pageSlug provided, default to home page slug '/'
        if ($pageSlug === null) {
            $pageSlug = '/';
        }
        
        $faqs = FAQ::with(['module', 'activeItems'])
            ->where('page_slug', $pageSlug)
            ->active()
            ->ordered()
            ->get();
        return $this->success($faqs, 'Page FAQ groups retrieved successfully');
    }

    /**
     * Get all modules with their FAQ groups (optional filtering by module_id)
     */
    public function getGroupedByModules(Request $request)
    {
        $query = PermissionsModules::with(['faqs' => function ($query) {
            $query->with('activeItems')->active()->ordered();
        }]);
        // Check for module_id from request body
        if ($request->has('module_id') && $request->module_id) {
            $query->where('id', $request->module_id);
        }
        $modules = $query->orderBy('title', 'asc')->get();
        return $this->success($modules, 'Modules with FAQ groups retrieved successfully');
    }

    // ================= FAQ ITEM MANAGEMENT METHODS =================

    /**
     * Add a new item to an existing FAQ group
     */
    public function addItem(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'faq_id' => 'required|integer|exists:faqs,id',
            'question' => 'required|string',
            'answer' => 'required|string',
            'sort_order' => 'nullable|integer',
            'status' => 'nullable|boolean'
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors(), 422);
        }

        $validatedData = $validator->validated();
        
        // Set defaults
        if (!isset($validatedData['status'])) {
            $validatedData['status'] = 1;
        }
        if (!isset($validatedData['sort_order'])) {
            $maxOrder = FAQItem::where('faq_id', $validatedData['faq_id'])->max('sort_order');
            $validatedData['sort_order'] = $maxOrder ? $maxOrder + 1 : 1;
        }

        $item = FAQItem::create($validatedData);
        $item->load('faq');

        return $this->success($item, 'FAQ item added successfully');
    }

    /**
     * Update a specific FAQ item
     */
    public function updateItem(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|integer|exists:faq_items,id',
            'question' => 'required|string',
            'answer' => 'required|string',
            'sort_order' => 'nullable|integer',
            'status' => 'nullable|boolean'
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors(), 422);
        }
        $validatedData = $validator->validated();
        $item = FAQItem::find($validatedData['id']);
        
        if (!$item) {
            return $this->error('FAQ item not found', 404);
        }
        unset($validatedData['id']);
        $item->update($validatedData);
        $item->load('faq');
        return $this->success($item, 'FAQ item updated successfully');
    }

    /**
     * Delete a specific FAQ item
     */
    public function deleteItem($id)
    {
        $item = FAQItem::find($id);
        if (!$item) {
            return $this->error('FAQ item not found', 404);
        }
        $item->delete();
        return $this->message('FAQ item deleted successfully');
    }

    /**
     * Toggle FAQ item status
     */
    public function updateItemStatus($id)
    {
        $item = FAQItem::find($id);
        if (!$item) {
            return $this->error('FAQ item not found', 404);
        }

        $newStatus = !$item->status;
        $item->update(['status' => $newStatus]);
        $item->load('faq');

        return $this->success($item, "FAQ item status updated successfully to " . ($newStatus ? 'enabled' : 'disabled'));
    }

    /**
     * Reorder FAQ items within a group
     */
    public function reorderItems(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'faq_id' => 'required|integer|exists:faqs,id',
            'items' => 'required|array',
            'items.*.id' => 'required|integer|exists:faq_items,id',
            'items.*.sort_order' => 'required|integer'
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors(), 422);
        }

        try {
            DB::beginTransaction();
            
            $faqId = $request->faq_id;
            $items = $request->items;

            foreach ($items as $itemData) {
                FAQItem::where('id', $itemData['id'])
                       ->where('faq_id', $faqId)
                       ->update(['sort_order' => $itemData['sort_order']]);
            }

            DB::commit();
            
            $faq = FAQ::with(['module', 'activeItems'])->find($faqId);
            return $this->success($faq, 'FAQ items reordered successfully');
            
        } catch (\Exception $e) {
            DB::rollback();
            Log::error('FAQ items reordering failed: ' . $e->getMessage());
            return $this->error('Failed to reorder FAQ items', 500);
        }
    }
}
