<?php

namespace App\Http\Controllers;

use App\Models\InspectionPlan;
use Illuminate\Http\Request;
use App\Models\InspectionPlanMeta;
use App\Models\InspectionPlanTable;
use App\Models\InspectionPlanChecklist;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

class InspectionPlanSetttingsController extends Controller
{

    public function indexedit($id)
    {
        try {
            $userTable = $this->getUserTable();
            $inspection_plan_setting = InspectionPlanTable::orderBy('step_order', 'asc')->where('id', $id)->first();
            if (!$inspection_plan_setting) {
                return $this->message('Record not found.', 404);
            }
            if ($userTable === 'customer' && ($inspection_plan_setting->customer_id !== auth()->id() || $inspection_plan_setting->workspace_id !== auth()->user()->current_workspace_id)) {
                return $this->message('You do not have access to this record.', 403);
            }
            if ($userTable === 'emp' && ($inspection_plan_setting->customer_id !== auth()->user()->customer_id || $inspection_plan_setting->workspace_id !== auth()->user()->workspace_id)) {
                return $this->message('You do not have access to this record.', 403);
            }
            $first_title = $inspection_plan_setting->title ?? '';
            $step_order = $inspection_plan_setting->step_order ?? '';
            $id = $inspection_plan_setting->id ?? '';
            $related_values = InspectionPlanTable::where('title', $first_title)
                ->get(['id', 'value']);
            if ($related_values->isEmpty()) {
                return $this->message('No related values found.', 404);
            }
            return $this->success([
                'first_title' => $first_title,
                'step_order' => $step_order,
                'related_values' => $related_values,
                'id' => $id,
            ], 'Data retrieved successfully.');
        } catch (\Exception $e) {
            return $this->message('An error occurred: ' . $e->getMessage(), 500);
        }
    }

    public function settingsTableEditData($id)
    {
        try {
            $userTable = $this->getUserTable();
            $inspection_plan_setting = InspectionPlanTable::find($id);
            if (!$inspection_plan_setting) {
                return $this->message('Record not found.', 404);
            }
            if ($userTable === 'customer' && ($inspection_plan_setting->customer_id !== auth()->id() || $inspection_plan_setting->workspace_id !== auth()->user()->current_workspace_id)) {
                return $this->message('You do not have access to this record.', 403);
            }
            if ($userTable === 'emp' && ($inspection_plan_setting->customer_id !== auth()->user()->customer_id || $inspection_plan_setting->workspace_id !== auth()->user()->workspace_id)) {
                return $this->message('You do not have access to this record.', 403);
            }
            $first_title = $inspection_plan_setting->title;
            $related_values = InspectionPlanTable::where('title', $first_title)
                ->get(['id', 'value']);
            if ($related_values->isEmpty()) {
                return $this->message('No related values found.', 404);
            }
            return $this->success($related_values, 'Data retrieved successfully.');
        } catch (\Exception $e) {
            return $this->message('An error occurred: ' . $e->getMessage(), 500);
        }
    }

    public function inspectionPlanSettingGet(Request $request)
    {
        try {
            $userTable = $this->getUserTable();
            $inspectionPlanSettingsQuery = InspectionPlanTable::orderBy('step_order', 'asc');
            if ($userTable === 'customer') {
                $inspectionPlanSettingsQuery->where('customer_id', auth()->id())
                    ->where('workspace_id', auth()->user()->current_workspace_id);
            } elseif ($userTable === 'emp') {
                $inspectionPlanSettingsQuery->where('customer_id', auth()->user()->customer_id)
                    ->where('workspace_id', auth()->user()->workspace_id);
            }

            // Apply single search filter for title and values
            if ($request->has('search') && !empty($request->search)) {
                $searchTerm = $request->search;
                $inspectionPlanSettingsQuery->where(function ($q) use ($searchTerm) {
                    $q->where('title', 'like', '%' . $searchTerm . '%')
                      ->orWhere('value', 'like', '%' . $searchTerm . '%');
                });
            }
            
            $inspection_plan_settings = $inspectionPlanSettingsQuery->get()
                ->groupBy('title')
                ->map(function ($group) {
                    return [
                        'id' => $group->first()->id,
                        'title' => $group->first()->title,
                        'step_order' => $group->first()->step_order,
                        'values' => $group->pluck('value')->implode(', ')
                    ];
                })
                ->values();
            if ($inspection_plan_settings->isEmpty()) {
                return $this->message('No inspection plan settings found.', 404);
            }
            return $this->withCount($inspection_plan_settings, 'Data retrieved successfully.');
        } catch (\Exception $e) {
            return $this->message('An error occurred: ' . $e->getMessage(), 500);
        }
    }

    public function inspectionPlanFormOptions()
    {
        try {
            $userTable = $this->getUserTable();
            $inspectionPlanSettingsQuery = InspectionPlanTable::orderBy('title', 'asc');
            if ($userTable === 'customer') {
                $inspectionPlanSettingsQuery->where('customer_id', auth()->id())
                    ->where('workspace_id', auth()->user()->current_workspace_id);
            } elseif ($userTable === 'emp') {
                $inspectionPlanSettingsQuery->where('customer_id', auth()->user()->customer_id)
                    ->where('workspace_id', auth()->user()->workspace_id);
            }
            $inspectionPlanSettings = $inspectionPlanSettingsQuery->get();
            if ($inspectionPlanSettings->isEmpty()) {
                return $this->message('Please create form steps in settings to proceed after.', 422);
            }
            return $this->success($inspectionPlanSettings, 'Fetched successfully.');
        } catch (\Exception $e) {
            return $this->error('An error occurred: ' . $e->getMessage(), 500);
        }
    }

    public function indexDelete($id)
    {
        if (!$id) {
            return $this->message('ID is required. Please refresh the page.', 422);
        }
        $record = InspectionPlanTable::find($id);
        if (!$record) {
            return $this->message('Record not found. Please refresh the page.', 404);
        }
        $userTable = $this->getUserTable();
        if ($userTable === 'customer' && ($record->customer_id !== auth()->id() || $record->workspace_id !== auth()->user()->current_workspace_id)) {
            return $this->message('You do not have access to this inspection plan.', 403);
        }
        if ($userTable === 'emp' && ($record->customer_id !== auth()->user()->customer_id || $record->workspace_id !== auth()->user()->workspace_id)) {
            return $this->message('You do not have access to this inspection plan.', 403);
        }
        $status = InspectionPlanTable::where('title', $record->title)->delete();
        InspectionPlanMeta::where('name', $record->title)->delete();
        InspectionPlanChecklist::where('name', $record->title)->delete();
        if (!$status) {
            return $this->message('Delete Failed.', 500);
        }
        return $this->message('Deleted Successfully.', 200);
    }

    public function inspectionPlanSettingStore(Request $request)
    {
        $ids = $this->getCustomerAndWorkspaceIds();
        $customerId = $ids['customer_id'];
        $workspaceId = $ids['workspace_id'];
        $validator = Validator::make($request->all(), [
            'step_name' => 'required|string',
            'step_order' => 'required|integer|unique:inspection_plan_tables,step_order,NULL,id,customer_id,' . $customerId . ',workspace_id,' . $workspaceId,
            'table_title' => 'nullable|array',
            'table_title.*' => 'nullable|string'
        ], [
            'step_name.required' => 'Checklist is required',
            'step_order.unique' => 'The step order must be unique for each inspection plan.',
        ]);
        if ($validator->fails()) {
            return $this->message($validator->errors()->first(), 422);
        }
        $step_name = $request->input('step_name');
        $step_order = $request->input('step_order');
        $updated_name = str_replace(' ', '_', $step_name);
        try {
            if ($request->table_title) {
                foreach ($request->table_title as $title) {
                    InspectionPlanTable::create([
                        'title' => $updated_name,
                        'step_order' => $step_order,
                        'customer_id' => $customerId,
                        'workspace_id' => $workspaceId,
                        'value' => $title,
                    ]);
                    InspectionPlanMeta::create([
                        'name' => $updated_name,
                        'title' => $title,
                        'customer_id' => $customerId,
                        'workspace_id' => $workspaceId,
                        'is_table' => 1,

                    ]);
                }
            } else {
                InspectionPlanTable::create([
                    'title' => $updated_name,
                    'step_order' => $step_order,
                    'customer_id' => $customerId,
                    'workspace_id' => $workspaceId,
                ]);
                InspectionPlanMeta::create([
                    'name' => $updated_name,
                    'customer_id' => $customerId,
                    'workspace_id' => $workspaceId,
                    'is_table' => 1,
                ]);
            }
            return $this->message('Created Successfully');
        } catch (\Exception $e) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Error creating inspection plan setting: ' . $e->getMessage(),
                'report_type' => 'inspection_plan',
                'error_type' => 'Exception error',
            ];
            storeReportsLogs($log);
            return $this->message('An error occurred while saving the inspection plan setting.', 500);
        }
    }

    public function inspectionPlanSettingUpdate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|integer',
            'table_name' => 'required|string|max:255',
            'step_order' => 'required|integer',
            'table_title' => 'required|array',
            'new_titles' => 'nullable|array',
        ]);
        if ($validator->fails()) {
            return $this->message($validator->errors()->first(), 422);
        }
        $existingRecord = InspectionPlanTable::find($request->id);
        if (!$existingRecord) {
            return $this->message('Record not found.', 404);
        }
        $customerId = null;
        $workspaceId = null;
        $ids = $this->getCustomerAndWorkspaceIds();
        $customerId = $ids['customer_id'];
        $workspaceId = $ids['workspace_id'];
        $table_name = $request->table_name;
        $existing_title = $existingRecord->title;
        $step_order = $request->step_order;
        $newTitle = str_replace(' ', '_', $table_name);
        
        // Update InspectionPlanMeta with proper scoping to customer and workspace
        InspectionPlanMeta::where('name', $existing_title)
            ->where('customer_id', $customerId)
            ->where('workspace_id', $workspaceId)
            ->update(['name' => $newTitle]);
            
        // Update InspectionPlanChecklist with proper scoping to customer and workspace
        InspectionPlanChecklist::where('name', $existing_title)
            ->where('customer_id', $customerId)
            ->where('workspace_id', $workspaceId)
            ->update(['name' => $newTitle]);
            
        foreach ($request->table_title as $recordId => $newValue) {
            $relatedRecord = InspectionPlanTable::find($recordId);
            if ($relatedRecord) {
                // Store the old value for meta update
                $oldValue = $relatedRecord->value;
                
                $relatedRecord->title = $newTitle;
                $relatedRecord->step_order = $step_order;
                $relatedRecord->value = $newValue;
                $relatedRecord->save();
                
                // Update InspectionPlanMeta with proper scoping
                InspectionPlanMeta::where('name', $newTitle)
                    ->where('title', $oldValue)
                    ->where('is_table', 1)
                    ->where('customer_id', $customerId)
                    ->where('workspace_id', $workspaceId)
                    ->update([
                        'title' => $newValue,
                    ]);
            }
        }
        if (!empty($request->new_titles)) {
            foreach ($request->new_titles as $newTitleValue) {
                // Check if the value exists for this specific customer and workspace
                if (!InspectionPlanTable::where('value', $newTitleValue)
                    ->where('customer_id', $customerId)
                    ->where('workspace_id', $workspaceId)
                    ->exists()) {
                    InspectionPlanMeta::create([
                        'title' => $newTitleValue,
                        'name' => $newTitle,
                        'is_table' => '1',
                        'customer_id' => $customerId,
                        'workspace_id' => $workspaceId,
                    ]);
                    InspectionPlanTable::create([
                        'title' => $newTitle,
                        'value' => $newTitleValue,
                        'step_order' => $step_order,
                        'customer_id' => $customerId,
                        'workspace_id' => $workspaceId,
                    ]);
                }
            }
        }
        return $this->message('Updated successfully.', 200);
    }

    public function inspectionPlanSettingMetaTable(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'inspection_plan_id' => 'required|integer',
        ]);
        if ($validator->fails()) {
            return $this->message($validator->errors()->first(), 422);
        }
        $name = $request->name;
        $inspection_plan_id = $request->inspection_plan_id;
        $userTable = $this->getUserTable();
        $inspectionPlan = InspectionPlan::find($inspection_plan_id);
        if (!$inspectionPlan) {
            return $this->message('Inspection plan not found.', 404);
        }
        $customerId = null;
        $workspaceId = null;
        if ($userTable === 'customer') {
            $customerId = auth()->id();
            $workspaceId = auth()->user()->current_workspace_id;
            if ($inspectionPlan->customer_id !== $customerId || $inspectionPlan->workspace_id !== $workspaceId) {
                return $this->message('You do not have access to this project', 403);
            }
        }
        if ($userTable === 'emp') {
            $customerId = auth()->user()->customer_id;
            $workspaceId = auth()->user()->workspace_id;
            if ($inspectionPlan->customer_id !== $customerId || $inspectionPlan->workspace_id !== $workspaceId) {
                return $this->message('You do not have access to this project', 403);
            }
        }
        $inspection_plan_checklist = InspectionPlanChecklist::where('customer_id', $customerId)
            ->where('workspace_id', $workspaceId)
            ->where('inspection_plan_id', $inspection_plan_id)
            ->first();
        if (!$inspection_plan_checklist) {
            return $this->message('Checklist not found.', 404);
        }
        $data = [
            'inspection_plan_table_heads' => InspectionPlanMeta::where('customer_id', $customerId)
                ->where('workspace_id', $workspaceId)
                ->where('is_table', 1)
                ->pluck('title'),
            'inspection_plan_table_form_data' => InspectionPlanMeta::where('inspection_plan_id', $inspection_plan_id)
                ->where('itpc_id', $inspection_plan_checklist->id)
                ->where('customer_id', $customerId)
                ->where('workspace_id', $workspaceId)
                ->where('is_table', 0)
                ->select('id', 'title', 'value') // Select relevant columns
                ->get(),
        ];
        return $this->success($data, 'Data retrieved successfully.');
    }

    public function inspectionPlanSettingMetaTableSave(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'thead' => 'required|array',             // Headers of the table
            'table_values' => 'required|array',     // Table values
            'row_ids' => 'nullable|array',          // Row IDs
            'name' => 'required|string|max:255',    // Name for identification
            'inspection_plan_id' => 'required|integer',
        ]);
        if ($validator->fails()) {
            return $this->message($validator->errors()->first(), 422);
        }
        $thead = $request->input('thead');
        $table_values = $request->input('table_values');
        $row_ids = $request->input('row_ids');
        $name = $request->input('name');
        $inspection_plan_id = $request->input('inspection_plan_id');
        $userTable = $this->getUserTable();
        $inspectionPlan = InspectionPlan::find($inspection_plan_id);
        if (!$inspectionPlan) {
            return $this->message('Inspection plan not found.', 404);
        }
        $customerId = null;
        $workspaceId = null;
        if ($userTable === 'customer') {
            $customerId = auth()->id();
            $workspaceId = auth()->user()->current_workspace_id;
            if ($inspectionPlan->customer_id !== $customerId || $inspectionPlan->workspace_id !== $workspaceId) {
                return $this->message('You do not have access to this project', 403);
            }
        }
        if ($userTable === 'emp') {
            $customerId = auth()->user()->customer_id;
            $workspaceId = auth()->user()->workspace_id;
            if ($inspectionPlan->customer_id !== $customerId || $inspectionPlan->workspace_id !== $workspaceId) {
                return $this->message('You do not have access to this project', 403);
            }
        }
        $inspection_plan_checklist = InspectionPlanChecklist::where('inspection_plan_id', $inspection_plan_id)
            ->where('customer_id', $customerId)
            ->where('workspace_id', $workspaceId)
            ->first();
        if (!$inspection_plan_checklist) {
            return $this->message('Checklist not found.', 404);
        }
        
        // Delete only the meta data for this specific inspection plan, checklist, and name
        InspectionPlanMeta::where('inspection_plan_id', $inspection_plan_id)
            ->where('itpc_id', $inspection_plan_checklist->id)
            ->where('name', $name)
            ->where('customer_id', $customerId)
            ->where('workspace_id', $workspaceId)
            ->where('is_table', 0)
            ->delete();
        
        // Insert new meta data
        foreach ($table_values as $rowIndex => $values) {
            if (!is_array($values)) {
                continue;
            }
            foreach ($values as $colIndex => $value) {
                $title = $thead[$colIndex] ?? '';
                $inspection_plan_meta = new InspectionPlanMeta();
                $inspection_plan_meta->inspection_plan_id = $inspection_plan_id;
                $inspection_plan_meta->itpc_id = $inspection_plan_checklist->id;
                $inspection_plan_meta->title = $title;
                $inspection_plan_meta->value = $value;
                $inspection_plan_meta->name = $name;
                $inspection_plan_meta->customer_id = $customerId;
                $inspection_plan_meta->workspace_id = $workspaceId;
                $inspection_plan_meta->save();
            }
        }
        return $this->success([
            'thead' => $thead,
            'table_values' => $table_values,
            'row_ids' => $row_ids,
            'name' => $name,
        ], 'Table record submitted and saved successfully.');
    }

    public function inspectionPlanSettingMetaTableFormDataDelete(Request $request)
    {
        $ids = $request->input('ids'); // Expecting an array of IDs
        if (!is_array($ids)) {
            return $this->message('Invalid data format', 400);
        }
        $deletedCount = InspectionPlanMeta::whereIn('id', $ids)->delete();
        if ($deletedCount === 0) {
            return $this->message('No records found for deletion', 404);
        }
        return $this->success($deletedCount, 'Deleted successfully');
    }

    public function inspectionPlanChecklistGet(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'inspection_plan_id' => 'required',
            ]);

            if ($validator->fails()) {
                return $this->message($validator->errors()->first(), 422);
            }
            
            $inspection_plan_id = $request->inspection_plan_id;
            
            // Get all selected checklist steps for this inspection plan
            $selected_steps = InspectionPlanChecklist::where('inspection_plan_id', $inspection_plan_id)
                ->where('status', "1")
                ->get();

            if ($selected_steps->isEmpty()) {
                return $this->message('No previous form was selected.', 404);
            }
            
            // Verify inspection plan exists and user has access
            $inspectionPlan = InspectionPlan::find($inspection_plan_id);
            if (!$inspectionPlan) {
                return $this->message('Inspection plan not found.', 404);
            }
            
            $userTable = $this->getUserTable();
            $customer_id = null;
            $workspace_id = null;
            
            if ($userTable === 'customer') {
                $customer_id = auth()->id();
                $workspace_id = auth()->user()->current_workspace_id;
                if ($inspectionPlan->customer_id !== $customer_id || $inspectionPlan->workspace_id !== $workspace_id) {
                    return $this->message('You do not have access to this project', 403);
                }
            }
            
            if ($userTable === 'emp') {
                $customer_id = auth()->user()->customer_id;
                $workspace_id = auth()->user()->workspace_id;
                if ($inspectionPlan->customer_id !== $customer_id || $inspectionPlan->workspace_id !== $workspace_id) {
                    return $this->message('You do not have access to this project', 403);
                }
            }
            
            // Transform each step to include its specific meta data
            $selected_steps->transform(function ($step) use ($customer_id, $workspace_id, $inspection_plan_id) {
                // Get table heads specific to this checklist step by filtering by title (checklist name)
                $inspection_plan_table_heads = InspectionPlanTable::where('customer_id', $customer_id)
                    ->where('workspace_id', $workspace_id)
                    ->where('title', $step->name)  // Filter by the specific checklist name
                    ->select('id', 'title', 'value')
                    ->get();
                
                // Get form data specific to this inspection plan and checklist step
                $inspection_plan_table_form_data = InspectionPlanMeta::where('inspection_plan_id', $inspection_plan_id)
                    ->where('itpc_id', $step->id)  // This is the key - filter by specific checklist step ID
                    ->where('customer_id', $customer_id)
                    ->where('workspace_id', $workspace_id)
                    ->where('is_table', 0)
                    ->select('id', 'title', 'value', 'name')
                    ->get();
                
                // Add meta data specific to this step
                $step->meta = [
                    'inspection_plan_table_heads' => $inspection_plan_table_heads,
                    'inspection_plan_table_form_data' => $inspection_plan_table_form_data,
                ];
                
                return $step;
            });
            
            return $this->withCount($selected_steps, 'Steps retrieved successfully');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    public function inspectionPlanSettingsDelete($id)
    {
        $deletedItem = InspectionPlanTable::find($id);
        if (!$deletedItem) {
            return $this->message('Record not found.', 404);
        }
        $userTable = $this->getUserTable();
        if ($userTable === 'customer' && ($deletedItem->customer_id !== auth()->id() || $deletedItem->workspace_id !== auth()->user()->current_workspace_id)) {
            return $this->message('You do not have access.', 403);
        }
        if ($userTable === 'emp' && ($deletedItem->customer_id !== auth()->user()->customer_id || $deletedItem->workspace_id !== auth()->user()->workspace_id)) {
            return $this->message('You do not have access .', 403);
        }
        $deletedCount = InspectionPlanMeta::where('title', $deletedItem->value)->delete();
        $deletedItem->delete();
        return $this->success($deletedCount, 'Deleted successfully.', 200);
    }
}
