<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\WhsqReport;
use Illuminate\Support\Facades\Validator;
use App\Models\EmpPersonalDetails;

class WHSQController extends Controller
{

    public function index(Request $request)
    {
        $reports = WhsqReport::query();
        $reports = $this->applyCustomerWorkspaceFilter($reports);
        if ($request->has('search') && !empty($request->search)) {
            $searchTerm = $request->search;
            $reports->where(function ($q) use ($searchTerm) {
                $q->where('document_title', 'like', '%' . $searchTerm . '%')
                    ->orWhere('document_number', 'like', '%' . $searchTerm . '%')
                    ->orWhereHas('authoriseBy', function ($subquery) use ($searchTerm) {
                        $subquery->where(function ($nameQuery) use ($searchTerm) {
                            $nameQuery->where('first_name', 'like', '%' . $searchTerm . '%')
                                      ->orWhere('middle_name', 'like', '%' . $searchTerm . '%')
                                      ->orWhere('last_name', 'like', '%' . $searchTerm . '%');
                        });
                    });
            });
        }
        $reports = $reports->with(['site', 'authoriseBy', 'generatedPdf'])
            ->orderBy('created_at', 'desc')
            ->get();
        return $this->withCount($reports, 'WHSQ reports retrieved successfully.');
    }

    /**
     * Store report footer
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'document_title' => 'required|string|max:255',
            'authorised_by' => 'required|integer|exists:emp_personal_details,emp_id',
            'revision_number' => 'required',
            'document_number' => 'required|string|max:255',
            'revision_date' => 'required|date',
            'next_revision_date' => 'required|date',
            'report_id' => 'nullable|integer',
            'whsq_site' => 'nullable'
        ]);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }
        $ids = $this->getCustomerAndWorkspaceIds();
        return $this->storeWHSQReport($request, $ids);
    }

    /**
     * Save selected settings for a report
     */
    public function saveSelectedSettings(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'report_id' => 'required|integer',
            'selected_settings' => 'required|array',
            'selected_settings.*.parent_id' => 'nullable|integer',
            'selected_settings.*.child_id' => 'nullable|integer',
            'selected_settings.*.grandchild_id' => 'nullable|integer',
            'selected_settings.*.sort_order' => 'nullable|integer'
        ]);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }
        $ids = $this->getCustomerAndWorkspaceIds();
        $validated = $validator->validated();
        return $this->saveWHSQSelectedSettings($validated, $ids);
    }

    /**
     * Get selected settings for a report
     */
    public function getSelectedSettings($reportId)
    {
        $ids = $this->getCustomerAndWorkspaceIds();
        return $this->getWHSQSelectedSettings($reportId, $ids);
    }

    /**
     * Toggle publish/unpublish status of a report
     */
    public function publish($id)
    {
        $ids = $this->getCustomerAndWorkspaceIds();
        return $this->toggleWHSQReportPublish($id, $ids);
    }



    /**
     * Display the specified WHSQ report
     */
    public function show($id)
    {
        $ids = $this->getCustomerAndWorkspaceIds();
        $report = WhsqReport::with(['authoriseBy', 'generatedPdf'])->where('customer_id', $ids['customer_id'])
            ->where('workspace_id', $ids['workspace_id'])
            ->find($id);
        if (!$report) {
            return $this->error('Report not found.', 404);
        }
        return $this->success($report, 'WHSQ report retrieved successfully with PDF information.');
    }

    /**
     * Remove the specified WHSQ report and related data
     */
    public function destroy($id)
    {
        $ids = $this->getCustomerAndWorkspaceIds();
        return $this->destroyWHSQReport($id, $ids);
    }

    /**
     * Get step content for a specific step
     */
    public function getStepContent($stepId, $reportId)
    {
        $ids = $this->getCustomerAndWorkspaceIds();
        return $this->getWHSQStepContent($stepId, $reportId, $ids);
    }

    /**
     * Get all data for a given report for frontend PDF generation
     */
    public function getReportDataForPDF($id)
    {
        $ids = $this->getCustomerAndWorkspaceIds();
        return $this->getWHSQReportData($id, $ids);
    }

    /**
     * Save step content and settings
     */
    public function saveStepContent(Request $request)
    {
        $validator = $this->whsqStepContentValidationRequest($request);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }
        $ids = $this->getCustomerAndWorkspaceIds();
        $validated = $validator->validated();
        return $this->saveWHSQStepContent($validated, $ids);
    }

    /**
     * Get report progress summary
     */
    public function getReportProgress($reportId)
    {
        $ids = $this->getCustomerAndWorkspaceIds();
        return $this->getWHSQReportProgress($reportId, $ids);
    }

    /**
     * Duplicate WHSQ report with new version
     */
    public function duplicate($reportId)
    {
        $ids = $this->getCustomerAndWorkspaceIds();
        return $this->duplicateWHSQReport($reportId, $ids);
    }
    public function whsqQuickEntryStore(Request $request)
    {
        return $this->whseqQuickEntryStore($request);
    }
    public function whsqQuickEntryEdit(Request $request)
    {
        return $this->whseqQuickEntryEdit($request);
    }
    public function whsqQuickEntryUpdate(Request $request)
    {
        return $this->whseqQuickEntryUpdate($request);
    }
}
    