<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\WHSQE_TableOfContent;
use App\Models\WHSQE_TableOfContentChild;
use App\Models\WHSQE_TableOfContentGrandChild;
use App\Models\WHSQE_TableOfContentSettingsMeta;
use App\Models\WHSQE_TableOfContentSettings;
use App\Models\WHSQETableOfContentMeta;
use Exception;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use App\Models\WHSQECustomerSelectedSettings;

class WhsqReportSettingController extends Controller
{

    public function index(Request $request)
    {
        $userTable = $this->getCustomerAndWorkspaceIds();
        $customer_id = $userTable['customer_id'];
        $workspace_id = $userTable['workspace_id'];
        
        $content_parents = WHSQE_TableOfContent::with([
            'children' => function ($query) use ($customer_id, $workspace_id) {
                $query->where('del', 0)
                    ->where('customer_id', $customer_id)
                    ->where('workspace_id', $workspace_id)
                    ->with([
                        'grandchildren' => function ($subQuery) use ($customer_id, $workspace_id) {
                            $subQuery->where('del', 0)
                                ->where('customer_id', $customer_id)
                                ->where('workspace_id', $workspace_id);
                        }
                    ]);
            }
        ])
            ->where('del', 0)
            ->where('customer_id', $customer_id)
            ->where('workspace_id', $workspace_id);
    
        // Apply search filter before get()
        if ($request->filled('search')) {
            $searchTerm = $request->search;
            $content_parents = $content_parents->where(function ($q) use ($searchTerm, $customer_id, $workspace_id) {
                $q->where('title', 'like', '%' . $searchTerm . '%')
                  ->orWhereHas('children', function ($subquery) use ($searchTerm, $customer_id, $workspace_id) {
                      $subquery->where('del', 0)
                          ->where('customer_id', $customer_id)
                          ->where('workspace_id', $workspace_id)
                          ->where('title', 'like', '%' . $searchTerm . '%');
                  })
                  ->orWhereHas('children.grandchildren', function ($subquery) use ($searchTerm, $customer_id, $workspace_id) {
                      $subquery->where('del', 0)
                          ->where('customer_id', $customer_id)
                          ->where('workspace_id', $workspace_id)
                          ->where('title', 'like', '%' . $searchTerm . '%');
                  });
            });
        }
        
        $content_parents = $content_parents->get();
        // Add static type parameter to each level
        $content_parents->each(function ($parent) {
            $parent->type = 'parent';
            
            if ($parent->children) {
                $parent->children->each(function ($child) {
                    $child->type = 'child';
                    
                    if ($child->grandchildren) {
                        $child->grandchildren->each(function ($grandchild) {
                            $grandchild->type = 'grandchild';
                        });
                    }
                });
            }
        });
    
        return $this->withCount($content_parents, 'WHSQE Report settings data retrieved successfully.');
    }

    /**
     * Get WHSQE report settings show data
     */
    public function show($id)
    {
        $userTable = $this->getCustomerAndWorkspaceIds();
        $content_parents = WHSQE_TableOfContent::find($id);
        if (!$content_parents) {
            return $this->error('Record not found.', 404);
        }
        $content_parents = $content_parents->with([
            'children' => function ($query) use ($userTable) {
                $query->where('del', 0)
                    ->where('customer_id', $userTable['customer_id'])
                    ->where('workspace_id', $userTable['workspace_id'])
                    ->with([
                        'grandchildren' => function ($subQuery) use ($userTable) {
                            $subQuery->where('del', 0)
                                ->where('customer_id', $userTable['customer_id'])
                                ->where('workspace_id', $userTable['workspace_id']);
                        }
                    ]);
            }
        ])
            ->where('del', 0)
            ->where('customer_id', $userTable['customer_id'])
            ->where('workspace_id', $userTable['workspace_id'])
            ->get();
        return $this->success($content_parents, 'WHSQE Report settings data retrieved successfully!');
    }

    /**
     * Store new WHSQE report setting
     */
    public function store(Request $request)
    {
        $userTable = $this->getCustomerAndWorkspaceIds();
        $validated = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'is_parent' => 'nullable|boolean',
            'parent_id' => 'nullable|exists:whsqe_table_of_content,id',
            'grand_parent_id' => 'nullable|exists:whsqe_table_of_content_child,id'
        ]);
        if ($validated->fails()) {
            return $this->handleValidationFailure($validated);
        }
        $validated = $validated->validated();
        if ($request->filled('parent_id') && !$request->filled('grand_parent_id')) {
            $whsq = new WHSQE_TableOfContentChild;
            $whsq->title = $validated['title'];
            $whsq->customer_id = $userTable['customer_id'];
            $whsq->workspace_id = $userTable['workspace_id'];
            $whsq->whsqe_table_of_content_id = $validated['parent_id'];
            $whsq->save();
        } elseif ($request->filled('grand_parent_id')) {
            $whsq = new WHSQE_TableOfContentGrandChild;
            $whsq->title = $validated['title'];
            $whsq->customer_id = $userTable['customer_id'];
            $whsq->workspace_id = $userTable['workspace_id'];
            $whsq->whsqe_table_of_content_id = $validated['parent_id'];
            $whsq->whsqe_table_of_content_child_id = $validated['grand_parent_id'];
            $whsq->save();
        } else {
            $whsq = new WHSQE_TableOfContent;
            $whsq->customer_id = $userTable['customer_id'];
            $whsq->workspace_id = $userTable['workspace_id'];
            $whsq->title = $validated['title'];
            $whsq->save();
        }
        return $this->success($whsq, 'WHSQ Report setting created successfully!');
    }

    public function edit($modelType, $id)
    {
        $content = match ($modelType) {
            'WHSQE_TableOfContent' => WHSQE_TableOfContent::find($id),
            'WHSQE_TableOfContentChild' => WHSQE_TableOfContentChild::with('parent')->find($id),
            'WHSQE_TableOfContentGrandChild' => WHSQE_TableOfContentGrandChild::with(['parent', 'grandparent'])->find($id),
            default => $this->error('Invalid model type', 400)
        };
        if (!$content) {
            return $this->error('Record not found.', 404);
        }
        $ids = $this->getCustomerAndWorkspaceIds();
        if ($content->customer_id !== $ids['customer_id'] || $content->workspace_id !== $ids['workspace_id']) {
            return $this->error('You do not have permission to access this.', 403);
        }
        $isParent = ($modelType === 'WHSQE_TableOfContent');
        $data = [
            'content' => $content,
            'modelType' => $modelType,
            'isParent' => $isParent,
        ];
        return $this->success($data, 'WHSQ Report setting retrieved successfully!');
    }

    /**
     * Get grand parents for a parent
     */
    public function getGrandParents($parentId)
    {
        try {
            $grandParents = WHSQE_TableOfContentChild::where('whsqe_table_of_content_id', $parentId)
                ->where('del', 0)
                ->get();
            return $this->success($grandParents->pluck('title', 'id'), 'Grand parents retrieved successfully.');
        } catch (Exception $e) {
            return $this->error('Error retrieving grand parents: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Update WHSQE report setting
     */
    public function update(Request $request, $modelType, $id)
    {
        $userTable = $this->getCustomerAndWorkspaceIds();
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'parent_id' => 'nullable|exists:whsqe_table_of_content,id',
            'grand_parent_id' => 'nullable|exists:whsqe_table_of_content_child,id'
        ]);
        $content = match ($modelType) {
            'WHSQE_TableOfContent' => WHSQE_TableOfContent::find($id),
            'WHSQE_TableOfContentChild' => WHSQE_TableOfContentChild::find($id),
            'WHSQE_TableOfContentGrandChild' => WHSQE_TableOfContentGrandChild::find($id),
            default => $this->error('Invalid model type', 400)
        };
        if (!$content) {
            return $this->error('Record not found.', 404);
        }
        if ($content->customer_id !== $userTable['customer_id'] || $content->workspace_id !== $userTable['workspace_id']) {
            return $this->error('You do not have permission to access this.', 403);
        }
        $updateData = [
            'title' => $validated['title'],
            'customer_id' => $userTable['customer_id'],
            'workspace_id' => $userTable['workspace_id']
        ];
        if ($modelType === 'WHSQE_TableOfContentChild' || $modelType === 'WHSQE_TableOfContentGrandChild') {
            $updateData['whsqe_table_of_content_id'] = $validated['parent_id'];
        }
        if ($modelType === 'WHSQE_TableOfContentGrandChild') {
            $updateData['whsqe_table_of_content_child_id'] = $validated['grand_parent_id'];
        }
        $content->update($updateData);
        return $this->success($content, 'Record updated successfully!');
    }

    /**
     * Delete WHSQE report setting
     */
    public function destroy($modelType, $id)
    {
        switch ($modelType) {
            case 'WHSQE_TableOfContent':
                $parent = WHSQE_TableOfContent::query();
                $parent = $this->applyCustomerWorkspaceFilter($parent);
                $parent = $parent->find($id);
                if (!$parent) {
                    return $this->error('Record not found.', 404);
                }
                WHSQE_TableOfContentGrandChild::whereIn(
                    'whsqe_table_of_content_child_id',
                    WHSQE_TableOfContentChild::where('whsqe_table_of_content_id', $id)->pluck('id')
                )->update(['del' => 1]);
                WHSQE_TableOfContentChild::where('whsqe_table_of_content_id', $id)->update(['del' => 1]);
                $parent->update(['del' => 1]);
                break;
            case 'WHSQE_TableOfContentChild':
                $child = WHSQE_TableOfContentChild::query();
                $child = $this->applyCustomerWorkspaceFilter($child);
                $child = $child->find($id);
                if (!$child) {
                    return $this->error('Record not found.', 404);
                }
                WHSQE_TableOfContentGrandChild::where('whsqe_table_of_content_child_id', $id)->update(['del' => 1]);
                $child->update(['del' => 1]);
                break;
            case 'WHSQE_TableOfContentGrandChild':
                $grandchild = WHSQE_TableOfContentGrandChild::query();
                $grandchild = $this->applyCustomerWorkspaceFilter($grandchild);
                $grandchild = $grandchild->find($id);
                if (!$grandchild) {
                    return $this->error('Record not found.', 404);
                }
                $grandchild->update(['del' => 1]);
                break;
            default:
                return $this->error('Invalid model type', 400);
        }
        return $this->message('Record marked as deleted successfully!');
    }

    /**
     * Get available settings for a specific step
     */
    public function getStepSettings($stepId, $reportId = null)
    {
        try {
            $userTable = $this->getCustomerAndWorkspaceIds();
            
            // Get all available settings for the step
            $settings = WHSQE_TableOfContent::with([
                'children' => function ($query) use ($userTable) {
                    $query->where('del', 0)
                        ->where('customer_id', $userTable['customer_id'])
                        ->where('workspace_id', $userTable['workspace_id'])
                        ->with([
                            'grandchildren' => function ($subQuery) use ($userTable) {
                                $subQuery->where('del', 0)
                                    ->where('customer_id', $userTable['customer_id'])
                                    ->where('workspace_id', $userTable['workspace_id']);
                            }
                        ]);
                }
            ])
            ->where('del', 0)
            ->where('customer_id', $userTable['customer_id'])
            ->where('workspace_id', $userTable['workspace_id'])
            ->get();

            // If report ID is provided, get selected settings
            $selectedSettings = null;
            if ($reportId) {
                $selectedSettings = WHSQETableOfContentMeta::byCustomerAndWorkspace($userTable['customer_id'], $userTable['workspace_id'])
                    ->byReport($reportId)
                    ->byStep($stepId)
                    ->active()
                    ->orderBy('sort_order')
                    ->get();
            }

            $data = [
                'available_settings' => $settings,
                'selected_settings' => $selectedSettings,
                'step_id' => $stepId,
                'report_id' => $reportId
            ];

            return $this->success($data, 'Step settings retrieved successfully.');
        } catch (Exception $e) {
            return $this->error('Error retrieving step settings: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Get available settings for a specific step (showing only selected settings for the customer)
     */
    public function getStepSettingsForCustomer($stepId, $reportId = null)
    {
        try {
            $userTable = $this->getCustomerAndWorkspaceIds();
            
            // If report ID is provided, get only the selected settings for this customer
            if ($reportId) {
                $selectedSettings = WHSQECustomerSelectedSettings::byCustomerAndWorkspace($userTable['customer_id'], $userTable['workspace_id'])
                    ->byReport($reportId)
                    ->selected()
                    ->orderBy('sort_order')
                    ->with(['parentContent', 'childContent', 'grandchildContent'])
                    ->get();

                // Filter settings to show only selected ones
                $filteredSettings = WHSQE_TableOfContent::with([
                    'children' => function ($query) use ($userTable, $selectedSettings) {
                        $query->where('del', 0)
                            ->where('customer_id', $userTable['customer_id'])
                            ->where('workspace_id', $userTable['workspace_id'])
                            ->whereIn('id', $selectedSettings->pluck('child_id')->filter())
                            ->with([
                                'grandchildren' => function ($subQuery) use ($userTable, $selectedSettings) {
                                    $subQuery->where('del', 0)
                                        ->where('customer_id', $userTable['customer_id'])
                                        ->where('workspace_id', $userTable['workspace_id'])
                                        ->whereIn('id', $selectedSettings->pluck('grandchild_id')->filter());
                                }
                            ]);
                    }
                ])
                ->where('del', 0)
                ->where('customer_id', $userTable['customer_id'])
                ->where('workspace_id', $userTable['workspace_id'])
                ->whereIn('id', $selectedSettings->pluck('parent_id')->filter())
                ->get();
            } else {
                // If no report ID, show all available settings
                $filteredSettings = WHSQE_TableOfContent::with([
                    'children' => function ($query) use ($userTable) {
                        $query->where('del', 0)
                            ->where('customer_id', $userTable['customer_id'])
                            ->where('workspace_id', $userTable['workspace_id'])
                            ->with([
                                'grandchildren' => function ($subQuery) use ($userTable) {
                                    $subQuery->where('del', 0)
                                        ->where('customer_id', $userTable['customer_id'])
                                        ->where('workspace_id', $userTable['workspace_id']);
                                }
                            ]);
                    }
                ])
                ->where('del', 0)
                ->where('customer_id', $userTable['customer_id'])
                ->where('workspace_id', $userTable['workspace_id'])
                ->get();
                
                $selectedSettings = null;
            }

            $data = [
                'available_settings' => $filteredSettings,
                'selected_settings' => $selectedSettings,
                'step_id' => $stepId,
                'report_id' => $reportId
            ];

            return $this->success($data, 'Step settings for customer retrieved successfully.');
        } catch (Exception $e) {
            return $this->error('Error retrieving step settings for customer: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Store step content and settings
     */
    public function storeStepContent(Request $request)
    {
        dd($request->all());
        try {
            $validator = Validator::make($request->all(), [
                'report_id' => 'required|integer',
                'step_id' => 'required|integer',
                'content_data' => 'required|array',
                'content_data.*.parent_id' => 'nullable|integer',
                'content_data.*.child_id' => 'nullable|integer',
                'content_data.*.grandchild_id' => 'nullable|integer',
                'content_data.*.content' => 'nullable|string',
                'content_data.*.dynamic_inputs' => 'nullable|array',
                'content_data.*.image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
                'content_data.*.image_alt' => 'nullable|string|max:255',
                'content_data.*.sort_order' => 'nullable|integer'
            ]);

            if ($validator->fails()) {
                return $this->handleValidationFailure($validator);
            }

            $userTable = $this->getCustomerAndWorkspaceIds();
            $validated = $validator->validated();

            DB::beginTransaction();

            // Delete existing content for this step and report
            WHSQETableOfContentMeta::byCustomerAndWorkspace($userTable['customer_id'], $userTable['workspace_id'])
                ->byReport($validated['report_id'])
                ->byStep($validated['step_id'])
                ->delete();

            // Store new content
            foreach ($validated['content_data'] as $index => $contentItem) {
                $imagePath = null;
                if (isset($contentItem['image']) && $contentItem['image']) {
                    $imagePath = WHSQETableOfContentMeta::storeImage($contentItem['image']);
                }

                WHSQETableOfContentMeta::create([
                    'whsq_report_id' => $validated['report_id'],
                    'step_id' => $validated['step_id'],
                    'parent_id' => $contentItem['parent_id'] ?? null,
                    'child_id' => $contentItem['child_id'] ?? null,
                    'grandchild_id' => $contentItem['grandchild_id'] ?? null,
                    'content' => $contentItem['content'] ?? null,
                    'dynamic_inputs' => $contentItem['dynamic_inputs'] ?? null,
                    'image_path' => $imagePath,
                    'image_alt' => $contentItem['image_alt'] ?? null,
                    'sort_order' => $contentItem['sort_order'] ?? $index,
                    'customer_id' => $userTable['customer_id'],
                    'workspace_id' => $userTable['workspace_id']
                ]);
            }

            DB::commit();

            return $this->success(null, 'Step content saved successfully.');
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error('Error saving step content: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Get step content for display
     */
    public function getStepContent($stepId, $reportId)
    {
        try {
            $userTable = $this->getCustomerAndWorkspaceIds();
            
            $content = WHSQETableOfContentMeta::byCustomerAndWorkspace($userTable['customer_id'], $userTable['workspace_id'])
                ->byReport($reportId)
                ->byStep($stepId)
                ->active()
                ->orderBy('sort_order')
                ->with(['parentContent', 'childContent', 'grandchildContent'])
                ->get();

            return $this->success($content, 'Step content retrieved successfully.');
        } catch (Exception $e) {
            return $this->error('Error retrieving step content: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Get all steps for a report
     */
    public function getReportSteps($reportId)
    {
        try {
            $userTable = $this->getCustomerAndWorkspaceIds();
            
            $steps = WHSQE_TableOfContent::byCustomerAndWorkspace($userTable['customer_id'], $userTable['workspace_id'])
                ->where('del', 0)
                ->orderBy('id')
                ->get(['id', 'title']);

            // Get completion status for each step
            $stepsWithStatus = $steps->map(function ($step) use ($reportId, $userTable) {
                $hasContent = WHSQETableOfContentMeta::byCustomerAndWorkspace($userTable['customer_id'], $userTable['workspace_id'])
                    ->byReport($reportId)
                    ->byStep($step->id)
                    ->exists();

                return [
                    'id' => $step->id,
                    'title' => $step->title,
                    'has_content' => $hasContent,
                    'step_number' => $step->id
                ];
            });

            return $this->success($stepsWithStatus, 'Report steps retrieved successfully.');
        } catch (Exception $e) {
            return $this->error('Error retrieving report steps: ' . $e->getMessage(), 500);
        }
    }
}
