<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\Assessment;
use App\Models\Answer;
use App\Models\QuestionGroup;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class AssessmentController extends Controller
{
    /* ---------- Helper: เติมฟิลด์บังคับให้ product ก่อน insert ---------- */
    private function fillProductMustHave(array $data): array
    {
        $cid = session('Customer_ID') ?? session('Customer_ID') ?? optional(Auth::user())->Customer_ID;
        $aid = session('selected_agency_id') ?? optional(Auth::user())->Agency_ID;
        $now = now();

        return array_merge([
            'Customer_ID' => $cid,
            'Agency_ID'   => $aid,
            'CusIns_ID'   => $cid,
            'CusUdp_ID'   => $cid,
            'DtmIns'      => $now,
            'DtmUpd'      => $now,
        ], $data);
    }

    public function create(Product $product)
    {
        // ตรวจสิทธิ์ด้วย Customer_ID
        if (Auth::user()->Customer_ID !== $product->Customer_ID && strtolower(Auth::user()->Level) !== 'admin') {
            abort(403, 'ไม่มีสิทธิ์เข้าถึงข้อมูลนี้');
        }

        $questionGroups = QuestionGroup::active()->with(['questions'])->get();
        return view('assessments.create', compact('product', 'questionGroups'));
    }

    public function store(Request $request)
    {
        Log::info('Assessment Store Request:', [
            'answers' => $request->answers,
            'session_pending_product' => session('pending_product')
        ]);

        $request->validate([
            'answers' => 'required|array',
            'answers.*.choice'  => 'nullable|string',
            'answers.*.details' => 'nullable|string',
            'answers.*.text'    => 'nullable|string',
        ]);

        // 1) สร้างผลิตภัณฑ์จาก session ก่อน
        $pendingProduct = session('pending_product');
        if (!$pendingProduct) {
            return redirect()->route('products.index')->with('error', 'กรุณากรอกข้อมูลผลิตภัณฑ์ก่อน');
        }

        $user = Auth::user();

        // ถ้าเป็น consult ให้เลือกบริษัทที่มีสิทธิ์
        if (strtolower($user->Level) === 'consult') {
            $selectedAgencyId = $request->get('selected_agency_id') ?? session('selected_agency_id');
            if ($selectedAgencyId) {
                $userAgencies = $this->getConsultUserAgencies($user);
                if ($userAgencies->where('Agency_ID', $selectedAgencyId)->isNotEmpty()) {
                    $pendingProduct['Agency_ID'] = $selectedAgencyId;
                }
            }
        } else {
            $pendingProduct['Agency_ID'] = $user->Agency_ID;
        }

        // เติมฟิลด์ที่ต้องมีให้ products
        $pendingProduct = $this->fillProductMustHave($pendingProduct);
        unset($pendingProduct['Customer_ID']); // กันค่าเก่าหลงมา

        $product = Product::create($pendingProduct);
        $request->session()->forget(['pending_product', 'selected_agency_id']);

        Log::info('Product created (store):', ['product_id' => $product->id, 'Agency_ID' => $product->Agency_ID]);

        try {
            // 2) สร้าง assessment — ใช้ Customer_ID แทน Customer_ID
            $assessment = Assessment::create([
                'product_id'        => $product->id,
                'question_group_id' => QuestionGroup::active()->first()->id,
                'Customer_ID'       => $user->Customer_ID,
                'CusIns_ID'         => $user->Customer_ID,
                'CusUdp_ID'         => $user->Customer_ID,
                'status'            => 'submitted',
                'started_at'        => now(),
                'submitted_at'      => now(),
            ]);

            Log::info('Assessment created:', ['assessment_id' => $assessment->id]);

            DB::statement('SET FOREIGN_KEY_CHECKS = 0');

            // 3) บันทึกคำตอบ
            foreach ($request->answers as $questionId => $answerData) {
                $questionId = (int) $questionId;
                $question = \App\Models\Question::find($questionId);
                if (!$question) {
                    Log::error('Question not found:', ['question_id' => $questionId]);
                    continue;
                }

                $answerText = null;
                $comment = null;

                if (isset($answerData['choice'])) {
                    if ($answerData['choice'] === 'yes')      $answerText = 'ใช่';
                    elseif ($answerData['choice'] === 'no')    $answerText = 'ไม่ใช่';
                    else                                       $answerText = $answerData['choice']; // multiple
                } elseif (isset($answerData['text'])) {
                    $answerText = $answerData['text'];
                }

                if (isset($answerData['details'])) $comment = $answerData['details'];

                if ($answerText && $question->question_type !== null) {
                    Answer::create([
                        'assessment_id' => $assessment->id,
                        'question_id'   => $questionId,
                        'answer_text'   => $answerText,
                        'image_path'    => null,
                        'comment'       => $comment,
                        'CusIns_ID'     => $user->Customer_ID,
                        'CusUdp_ID'     => $user->Customer_ID,
                    ]);
                }
            }

            // 4) คำถามแม่ (question_type = null) ที่ใช้ประเมิน
            $parentQuestions = \App\Models\Question::whereNull('question_type')
                ->where('use_in_evaluation', 1)
                ->whereHas('questionGroup', fn($q) => $q->where('is_active', true))
                ->get();

            $calculateParentResult = function($parentQuestionId) use ($assessment, &$calculateParentResult) {
                $childQuestions = \App\Models\Question::where('parent_id', $parentQuestionId)
                    ->where('use_in_evaluation', 1)->get();

                if ($childQuestions->isEmpty()) return false;

                $childAnswers = [];
                foreach ($childQuestions as $child) {
                    if ($child->question_type === 'yes_no') {
                        $childAnswer = $assessment->answers()->where('question_id', $child->id)->first();
                        $childAnswers[] = $childAnswer ? $childAnswer->answer_text === 'ใช่' : false;
                    } elseif (is_null($child->question_type)) {
                        $childAnswers[] = $calculateParentResult($child->id);
                    }
                }

                $parent = \App\Models\Question::find($parentQuestionId);
                return $parent && $parent->logic_operator === 'AND'
                    ? !in_array(false, $childAnswers, true)
                    : in_array(true, $childAnswers, true);
            };

            foreach ($parentQuestions as $parent) {
                $result = $calculateParentResult($parent->id);
                Answer::create([
                    'assessment_id' => $assessment->id,
                    'question_id'   => $parent->id,
                    'answer_text'   => $result ? 'ใช่' : 'ไม่ใช่',
                    'image_path'    => null,
                    'comment'       => null,
                    'CusIns_ID'     => $user->Customer_ID,
                    'CusUdp_ID'     => $user->Customer_ID,
                ]);
            }

            DB::statement('SET FOREIGN_KEY_CHECKS = 1');

            return redirect()->route('products.report', $product)
                ->with('success', 'บันทึกการประเมินเรียบร้อยแล้ว');

        } catch (\Exception $e) {
            DB::statement('SET FOREIGN_KEY_CHECKS = 1');
            Log::error('Assessment store error:', ['message' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
            return back()->with('error', 'เกิดข้อผิดพลาดในการบันทึกการประเมิน: ' . $e->getMessage())->withInput();
        }
    }

    /** ส่งแบบประเมินจากฉบับร่าง */
    public function submitDraft(Request $request)
    {
        if (!$request->has('product_id')) {
            return back()->with('error', 'ไม่พบข้อมูลผลิตภัณฑ์');
        }

        $productId = (int) $request->product_id;

        $assessment = Assessment::where('product_id', $productId)
            ->where('status', 'draft')
            ->where('Customer_ID', Auth::user()->Customer_ID)
            ->first();

        if (!$assessment) {
            return back()->with('error', 'ไม่พบฉบับร่างหรือไม่มีสิทธิ์เข้าถึง');
        }

        if (Auth::user()->Customer_ID !== $assessment->Customer_ID && strtolower(Auth::user()->Level) !== 'admin') {
            abort(403, 'ไม่มีสิทธิ์เข้าถึงข้อมูลนี้');
        }

        if ($assessment->status !== 'draft') {
            return back()->with('error', 'ไม่สามารถส่งแบบประเมินได้');
        }

        $request->validate([
            'answers' => 'required|array',
            'answers.*.choice'  => 'nullable|string',
            'answers.*.details' => 'nullable|string',
            'answers.*.text'    => 'nullable|string',
        ]);

        try {
            DB::beginTransaction();

            $assessment->update([
                'status'       => 'submitted',
                'submitted_at' => now(),
                'CusUdp_ID'    => Auth::user()->Customer_ID,
                'DtmUpd'       => now(),
            ]);

            $assessment->answers()->delete();

            foreach ($request->answers as $questionId => $answerData) {
                $questionId = (int) $questionId;
                $question = \App\Models\Question::find($questionId);
                if (!$question) continue;

                $answerText = null;
                $comment = null;

                if (isset($answerData['choice'])) {
                    if ($answerData['choice'] === 'yes')      $answerText = 'ใช่';
                    elseif ($answerData['choice'] === 'no')    $answerText = 'ไม่ใช่';
                    else                                       $answerText = $answerData['choice'];
                } elseif (isset($answerData['text'])) {
                    $answerText = $answerData['text'];
                }

                if (isset($answerData['details'])) $comment = $answerData['details'];

                if ($answerText && $question->question_type !== null) {
                    Answer::create([
                        'assessment_id' => $assessment->id,
                        'question_id'   => $questionId,
                        'answer_text'   => $answerText,
                        'image_path'    => null,
                        'comment'       => $comment,
                        'CusIns_ID'     => Auth::user()->Customer_ID,
                        'CusUdp_ID'     => Auth::user()->Customer_ID,
                    ]);
                }
            }

            // Parent questions
            $parentQuestions = \App\Models\Question::whereNull('question_type')
                ->where('use_in_evaluation', 1)
                ->whereHas('questionGroup', fn($q) => $q->where('is_active', true))
                ->get();

            $calculateParentResult = function($parentQuestionId) use ($assessment, &$calculateParentResult) {
                $childQuestions = \App\Models\Question::where('parent_id', $parentQuestionId)
                    ->where('use_in_evaluation', 1)->get();

                if ($childQuestions->isEmpty()) return false;

                $childAnswers = [];
                foreach ($childQuestions as $child) {
                    if ($child->question_type === 'yes_no') {
                        $childAnswer = $assessment->answers()->where('question_id', $child->id)->first();
                        $childAnswers[] = $childAnswer ? $childAnswer->answer_text === 'ใช่' : false;
                    } elseif (is_null($child->question_type)) {
                        $childAnswers[] = $calculateParentResult($child->id);
                    }
                }

                $parent = \App\Models\Question::find($parentQuestionId);
                return $parent && $parent->logic_operator === 'AND'
                    ? !in_array(false, $childAnswers, true)
                    : in_array(true, $childAnswers, true);
            };

            foreach ($parentQuestions as $parent) {
                $result = $calculateParentResult($parent->id);
                Answer::create([
                    'assessment_id' => $assessment->id,
                    'question_id'   => $parent->id,
                    'answer_text'   => $result ? 'ใช่' : 'ไม่ใช่',
                    'image_path'    => null,
                    'comment'       => null,
                    'CusIns_ID'     => Auth::user()->Customer_ID,
                    'CusUdp_ID'     => Auth::user()->Customer_ID,
                ]);
            }

            DB::commit();

            session()->forget('pending_product');

            $product = Product::find($productId);
            if (!$product) {
                $user = Auth::user();
                if (strtolower($user->Level) === 'consult') {
                    $selectedAgencyId = $request->get('selected_agency_id');
                    if ($selectedAgencyId) {
                        return redirect()->route('products.index', ['agency_id' => $selectedAgencyId])
                            ->with('error', 'ไม่พบข้อมูลผลิตภัณฑ์');
                    }
                }
                return redirect()->route('products.index')->with('error', 'ไม่พบข้อมูลผลิตภัณฑ์');
            }

            return redirect()->route('products.report', $product)
                ->with('success', 'ส่งแบบประเมินเรียบร้อยแล้ว');

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Error submitting draft assessment: ' . $e->getMessage());
            return back()->with('error', 'เกิดข้อผิดพลาดในการส่งแบบประเมิน: ' . $e->getMessage());
        }
    }

    /** บันทึกฉบับร่างการประเมิน */
    public function storeDraft(Request $request)
    {
        Log::info('Assessment Draft Store Request:', [
            'answers' => $request->answers,
            'session_pending_product' => session('pending_product')
        ]);

        $request->validate([
            'answers' => 'nullable|array',
            'answers.*.choice'  => 'nullable|string',
            'answers.*.details' => 'nullable|string',
            'answers.*.text'    => 'nullable|string',
        ]);

        $assessment = null;
        $product = null;

        if (session('pending_product')) {
            $user = Auth::user();
            $pendingProduct = session('pending_product');

            if (strtolower($user->Level) === 'consult') {
                $selectedAgencyId = $request->get('selected_agency_id') ?? session('selected_agency_id');
                if ($selectedAgencyId) {
                    $userAgencies = $this->getConsultUserAgencies($user);
                    if ($userAgencies->where('Agency_ID', $selectedAgencyId)->isNotEmpty()) {
                        $pendingProduct['Agency_ID'] = $selectedAgencyId;
                    }
                }
            } else {
                $pendingProduct['Agency_ID'] = $user->Agency_ID;
            }

            // เติมฟิลด์บังคับให้ครบ + ลบ Customer_ID ถ้ามี
            $pendingProduct = $this->fillProductMustHave($pendingProduct);
            unset($pendingProduct['Customer_ID']);

            $product = Product::create($pendingProduct);
            $request->session()->forget('pending_product');

            Log::info('Product created for draft:', ['product_id' => $product->id, 'Agency_ID' => $product->Agency_ID]);
        } else {
            $productId = (int) $request->input('product_id');
            if ($productId) {
                $product = Product::find($productId);
                if ($product) {
                    $assessment = Assessment::where('product_id', $product->id)
                        ->where('status', 'draft')->first();
                }
            }
        }

        if (!$product) {
            return redirect()->route('products.create')->with('error', 'กรุณากรอกข้อมูลผลิตภัณฑ์ก่อน');
        }

        try {
            if (!$assessment) {
                $assessment = Assessment::create([
                    'product_id'        => $product->id,
                    'question_group_id' => QuestionGroup::active()->first()->id,
                    'Customer_ID'       => Auth::user()->Customer_ID, // ใช้ Customer_ID
                    'CusIns_ID'         => Auth::user()->Customer_ID,
                    'CusUdp_ID'         => Auth::user()->Customer_ID,
                    'status'            => 'draft',
                    'started_at'        => now(),
                    'submitted_at'      => null,
                    'DtmUpd'            => now(),
                ]);
                Log::info('New assessment draft created:', ['assessment_id' => $assessment->id]);
            } else {
                $assessment->CusUdp_ID = Auth::user()->Customer_ID;
                $assessment->DtmUpd    = now();
                $assessment->save();
                Log::info('Existing assessment draft updated:', [
                    'assessment_id' => $assessment->id,
                    'new_DtmUpd'    => $assessment->DtmUpd
                ]);
            }

            DB::statement('SET FOREIGN_KEY_CHECKS = 0');

            $assessment->answers()->delete();

            if ($request->has('answers') && is_array($request->answers)) {
                foreach ($request->answers as $questionId => $answerData) {
                    $questionId = (int) $questionId;
                    $question = \App\Models\Question::find($questionId);
                    if (!$question) {
                        Log::error('Question not found for draft:', ['question_id' => $questionId]);
                        continue;
                    }

                    $answerText = null;
                    $comment = null;

                    if (isset($answerData['choice'])) {
                        if ($answerData['choice'] === 'yes')      $answerText = 'ใช่';
                        elseif ($answerData['choice'] === 'no')    $answerText = 'ไม่ใช่';
                        else                                       $answerText = $answerData['choice'];
                    } elseif (isset($answerData['text'])) {
                        $answerText = $answerData['text'];
                    }

                    if (isset($answerData['details'])) $comment = $answerData['details'];

                    if ($answerText && $question->question_type !== null) {
                        Answer::create([
                            'assessment_id' => $assessment->id,
                            'question_id'   => $questionId,
                            'answer_text'   => $answerText,
                            'image_path'    => null,
                            'comment'       => $comment,
                            'CusIns_ID'     => Auth::user()->Customer_ID,
                            'CusUdp_ID'     => Auth::user()->Customer_ID,
                        ]);
                    }
                }
            }

            $parentQuestions = \App\Models\Question::whereNull('question_type')
                ->where('use_in_evaluation', 1)
                ->whereHas('questionGroup', fn($q) => $q->where('is_active', true))
                ->get();

            $calculateParentResult = function($parentQuestionId) use ($assessment, &$calculateParentResult) {
                $childQuestions = \App\Models\Question::where('parent_id', $parentQuestionId)
                    ->where('use_in_evaluation', 1)->get();

                if ($childQuestions->isEmpty()) return false;

                $childAnswers = [];
                foreach ($childQuestions as $child) {
                    if ($child->question_type === 'yes_no') {
                        $childAnswer = $assessment->answers()->where('question_id', $child->id)->first();
                        $childAnswers[] = $childAnswer ? $childAnswer->answer_text === 'ใช่' : false;
                    } elseif (is_null($child->question_type)) {
                        $childAnswers[] = $calculateParentResult($child->id);
                    }
                }

                $parent = \App\Models\Question::find($parentQuestionId);
                return $parent && $parent->logic_operator === 'AND'
                    ? !in_array(false, $childAnswers, true)
                    : in_array(true, $childAnswers, true);
            };

            foreach ($parentQuestions as $parent) {
                $result = $calculateParentResult($parent->id);
                $parentAnswer = Answer::create([
                    'assessment_id' => $assessment->id,
                    'question_id'   => $parent->id,
                    'answer_text'   => $result ? 'ใช่' : 'ไม่ใช่',
                    'image_path'    => null,
                    'comment'       => null,
                    'CusIns_ID'     => Auth::user()->Customer_ID,
                    'CusUdp_ID'     => Auth::user()->Customer_ID,
                ]);

                Log::info('Parent draft answer created:', [
                    'answer_id' => $parentAnswer->id,
                    'question_id' => $parent->id,
                    'answer_text' => $result ? 'ใช่' : 'ไม่ใช่',
                    'logic_operator' => $parent->logic_operator
                ]);
            }

            DB::statement('SET FOREIGN_KEY_CHECKS = 1');

            return redirect()->route('products.index')
                ->with('success', 'บันทึกฉบับร่างเรียบร้อยแล้ว คุณสามารถกดปุ่ม "ทำต่อ" เพื่อทำแบบประเมินต่อได้');

        } catch (\Exception $e) {
            DB::statement('SET FOREIGN_KEY_CHECKS = 1');
            Log::error('Assessment draft store error:', ['message' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
            return back()->with('error', 'เกิดข้อผิดพลาดในการบันทึกฉบับร่าง: ' . $e->getMessage())->withInput();
        }
    }

    /** แสดงฟอร์มทำต่อจากฉบับร่าง */
    public function continueDraft(Product $product)
    {
        $user = Auth::user();
        $hasAccess = false;

        if ($user->Customer_ID === $product->Customer_ID) {
            $hasAccess = true;
        } elseif (in_array(strtolower($user->Level), ['admin','superadmin'], true)) {
            $hasAccess = true;
        } elseif ($user->Agency_ID && $product->user && $product->user->Agency_ID && $user->Agency_ID === $product->user->Agency_ID) {
            $hasAccess = true;
        }

        if (!$hasAccess) abort(403, 'ไม่มีสิทธิ์เข้าถึงข้อมูลนี้');

        $assessment = Assessment::where('product_id', $product->id)
            ->where('status', 'draft')
            ->first();

        if (!$assessment) {
            return redirect()->route('products.index')->with('error', 'ไม่พบฉบับร่างสำหรับผลิตภัณฑ์นี้');
        }

        $questionGroups = QuestionGroup::active()->with(['questions'])->get();
        $assessment->load(['answers' => fn($q) => $q->orderBy('question_id')]);

        $validated = [
            'name'               => $product->name,
            'model'              => $product->model,
            'product_type'       => $product->product_type,
            'log_receive_method' => $product->log_receive_method,
            'description'        => $product->description
        ];

        $existingAnswers = [];
        foreach ($assessment->answers as $answer) {
            $existingAnswers[$answer->question_id] = [
                'choice'  => $answer->answer_text,
                'details' => $answer->comment,
                'text'    => $answer->answer_text
            ];
        }

        return view('assessments.manual', compact('assessment', 'questionGroups', 'validated', 'existingAnswers'));
    }

    public function edit(Assessment $assessment)
    {
        if (Auth::user()->Customer_ID !== $assessment->Customer_ID && strtolower(Auth::user()->Level) !== 'admin') {
            abort(403, 'ไม่มีสิทธิ์เข้าถึงข้อมูลนี้');
        }

        $questionGroups = QuestionGroup::active()->with(['questions'])->get();
        return view('assessments.edit', compact('assessment', 'questionGroups'));
    }

    public function manual(Assessment $assessment)
    {
        if (Auth::user()->Customer_ID !== $assessment->Customer_ID && strtolower(Auth::user()->Level) !== 'admin') {
            abort(403, 'ไม่มีสิทธิ์เข้าถึงข้อมูลนี้');
        }

        if ($assessment->status !== 'draft') {
            return redirect()->route('assessments.edit', $assessment)->with('error', 'ไม่สามารถเข้าถึงหน้าแบบประเมินคู่มือได้');
        }

        $questionGroups = QuestionGroup::active()->with(['questions'])->get();
        $assessment->load('answers');

        return view('assessments.manual', compact('assessment', 'questionGroups'));
    }

    public function update(Request $request, Assessment $assessment)
    {
        if (Auth::user()->Customer_ID !== $assessment->Customer_ID && strtolower(Auth::user()->Level) !== 'admin') {
            abort(403, 'ไม่มีสิทธิ์เข้าถึงข้อมูลนี้');
        }

        $request->validate([
            'answers' => 'nullable|array',
            'answers.*.choice'  => 'nullable|string',
            'answers.*.details' => 'nullable|string',
            'answers.*.text'    => 'nullable|string',
        ]);

        try {
            DB::statement('SET FOREIGN_KEY_CHECKS = 0');

            $assessment->update([
                'status'       => 'submitted',
                'submitted_at' => now(),
                'CusUdp_ID'    => Auth::user()->Customer_ID,
            ]);

            $assessment->answers()->delete();

            if ($request->has('answers') && is_array($request->answers)) {
                foreach ($request->answers as $questionId => $answerData) {
                    $questionId = (int) $questionId;
                    $question = \App\Models\Question::find($questionId);
                    if (!$question) continue;

                    $answerText = null;
                    $comment = null;

                    if (isset($answerData['choice'])) {
                        if ($answerData['choice'] === 'yes')      $answerText = 'ใช่';
                        elseif ($answerData['choice'] === 'no')    $answerText = 'ไม่ใช่';
                        else                                       $answerText = $answerData['choice'];
                    } elseif (isset($answerData['text'])) {
                        $answerText = $answerData['text'];
                    }

                    if (isset($answerData['details'])) $comment = $answerData['details'];

                    if ($answerText && $question->question_type !== null) {
                        Answer::create([
                            'assessment_id' => $assessment->id,
                            'question_id'   => $questionId,
                            'answer_text'   => $answerText,
                            'image_path'    => null,
                            'comment'       => $comment,
                            'CusIns_ID'     => Auth::user()->Customer_ID,
                            'CusUdp_ID'     => Auth::user()->Customer_ID,
                        ]);
                    }
                }
            }

            $parentQuestions = \App\Models\Question::whereNull('question_type')
                ->where('use_in_evaluation', 1)
                ->whereHas('questionGroup', fn($q) => $q->where('is_active', true))
                ->get();

            $calculateParentResult = function($parentQuestionId) use ($assessment, &$calculateParentResult) {
                $childQuestions = \App\Models\Question::where('parent_id', $parentQuestionId)
                    ->where('use_in_evaluation', 1)->get();

                if ($childQuestions->isEmpty()) return false;

                $childAnswers = [];
                foreach ($childQuestions as $child) {
                    if ($child->question_type === 'yes_no') {
                        $childAnswer = $assessment->answers()->where('question_id', $child->id)->first();
                        $childAnswers[] = $childAnswer ? $childAnswer->answer_text === 'ใช่' : false;
                    } elseif (is_null($child->question_type)) {
                        $childAnswers[] = $calculateParentResult($child->id);
                    }
                }

                $parent = \App\Models\Question::find($parentQuestionId);
                return $parent && $parent->logic_operator === 'AND'
                    ? !in_array(false, $childAnswers, true)
                    : in_array(true, $childAnswers, true);
            };

            foreach ($parentQuestions as $parent) {
                $result = $calculateParentResult($parent->id);
                Answer::create([
                    'assessment_id' => $assessment->id,
                    'question_id'   => $parent->id,
                    'answer_text'   => $result ? 'ใช่' : 'ไม่ใช่',
                    'image_path'    => null,
                    'comment'       => null,
                    'CusIns_ID'     => Auth::user()->Customer_ID,
                    'CusUdp_ID'     => Auth::user()->Customer_ID,
                ]);
            }

            DB::statement('SET FOREIGN_KEY_CHECKS = 1');

            return redirect()->route('products.report', $assessment->product)
                ->with('success', 'ส่งแบบประเมินเรียบร้อยแล้ว');

        } catch (\Exception $e) {
            DB::statement('SET FOREIGN_KEY_CHECKS = 1');
            return back()->with('error', 'เกิดข้อผิดพลาดในการส่งแบบประเมิน: ' . $e->getMessage())->withInput();
        }
    }

    /** ดึงรายการบริษัทที่ consult user เข้าถึงได้ */
    private function getConsultUserAgencies($user)
    {
        $agencyIds = \App\Models\AgencyCustomer::where('Customer_ID', $user->Customer_ID)
            ->pluck('Agency_ID')->toArray();

        if ($user->Agency_ID && !in_array($user->Agency_ID, $agencyIds)) {
            $agencyIds[] = $user->Agency_ID;
        }

        return \App\Models\Agency::whereIn('Agency_ID', $agencyIds)->get();
    }
}
