<?php

require_once 'vendor/autoload.php';

use Illuminate\Support\Facades\DB;
use App\Models\Assessment;
use App\Models\Answer;
use App\Models\Question;

// Bootstrap Laravel
$app = require_once 'bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

echo "=== ทดสอบ Recursive Function ===\n\n";

try {
    $assessment = Assessment::find(70);
    if (!$assessment) {
        echo "ไม่พบ Assessment ID 70\n";
        exit;
    }

    echo "Assessment ID: {$assessment->id}\n";
    echo "Question Group ID: {$assessment->question_group_id}\n\n";

    // ฟังก์ชันสำหรับคำนวณผลลัพธ์ของ parent question
    $calculateParentResult = function($parentQuestionId) use ($assessment, &$calculateParentResult) {
        // หา Child Questions ของ Parent นี้
        $childQuestions = Question::where('parent_id', $parentQuestionId)
            ->where('use_in_evaluation', true)
            ->orderBy('sort_order')
            ->get();

        if ($childQuestions->count() == 0) {
            echo "  ไม่มี Child Questions\n";
            return;
        }

        echo "  Child Questions: " . $childQuestions->count() . " ข้อ\n";

        foreach ($childQuestions as $childQuestion) {
            echo "    - " . $childQuestion->question_text . "\n";
            
            // สำหรับ yes_no questions
            if ($childQuestion->question_type === 'yes_no') {
                echo "      (ใช้ในการประเมิน: ใช่/ไม่ใช่)\n";
            }
            
            // สำหรับ nested parent questions - เรียก recursive
            if ($childQuestion->hasChildren()) {
                echo "      (มีคำถามย่อย - เรียก recursive)\n";
                // เรียก recursive function อีกครั้ง
                $calculateParentResult($childQuestion->id);
            }
        }
    };

    // ทดสอบกับ parent questions หลัก
    $parentQuestions = Question::where('question_type', null)
        ->where('use_in_evaluation', 1)
        ->where('question_group_id', $assessment->question_group_id)
        ->get();

    echo "พบ Parent Questions: " . $parentQuestions->count() . " ข้อ\n\n";

    foreach ($parentQuestions as $parentQuestion) {
        echo "=== Parent Question ID: {$parentQuestion->id} ===\n";
        echo "คำถาม: {$parentQuestion->question_text}\n";
        echo "Logic Operator: {$parentQuestion->logic_operator}\n\n";
        
        $result = $calculateParentResult($parentQuestion->id);
        
        echo "Final Result: " . ($result ? 'ใช่' : 'ไม่ใช่') . "\n\n";
    }
    
    echo "=== เสร็จสิ้นการทดสอบ ===\n";

} catch (Exception $e) {
    echo "เกิดข้อผิดพลาด: " . $e->getMessage() . "\n";
    echo "Trace: " . $e->getTraceAsString() . "\n";
} 