<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * Class QuestionnaireConfig
 * @package App\Models
 *
 * @property string $id
 * @property string $name
 * @property string $slug
 * @property string $insurance_company
 * @property int $min_age
 * @property int $max_age
 * @property bool $is_active
 * @property array|null $step1_config
 * @property array|null $step2_config
 * @property array|null $step3_config
 * @property array|null $step4_config
 * @property float $rate_a_multiplier
 * @property float $rate_b_multiplier
 * @property float $rate_c_multiplier
 * @property float $smoking_surcharge_percent
 * @property string|null $description
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @property \Carbon\Carbon|null $deleted_at
 *
 * @property \Illuminate\Database\Eloquent\Collection|QuestionnaireAnswer[] $answers
 */
class QuestionnaireConfig extends Model
{
    use HasUlids, SoftDeletes;

    /**
     * The table associated with the model.
     * @var string
     */
    protected $table = 'questionnaire_configs';

    /**
     * The attributes that are mass assignable.
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'slug',
        'insurance_company',
        'min_age',
        'max_age',
        'is_active',
        'step1_config',
        'step2_config',
        'step3_config',
        'step4_config',
        'rate_a_multiplier',
        'rate_b_multiplier',
        'rate_c_multiplier',
        'smoking_surcharge_percent',
        'description',
    ];

    /**
     * The attributes that should be cast.
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'step1_config' => 'array',
            'step2_config' => 'array',
            'step3_config' => 'array',
            'step4_config' => 'array',
            'is_active' => 'boolean',
            'min_age' => 'integer',
            'max_age' => 'integer',
            'rate_a_multiplier' => 'decimal:2',
            'rate_b_multiplier' => 'decimal:2',
            'rate_c_multiplier' => 'decimal:2',
            'smoking_surcharge_percent' => 'decimal:2',
            'deleted_at' => 'datetime',
        ];
    }

    /**
     * Boot the model.
     * @return void
     */
    protected static function boot(): void
    {
        parent::boot();

        static::creating(function (QuestionnaireConfig $config) {
            if (empty($config->slug)) {
                $config->slug = \Illuminate\Support\Str::slug($config->name);
            }
            
            // Set default values
            if (empty($config->rate_a_multiplier)) {
                $config->rate_a_multiplier = 1.00;
            }
            if (empty($config->rate_b_multiplier)) {
                $config->rate_b_multiplier = 1.50;
            }
            if (empty($config->rate_c_multiplier)) {
                $config->rate_c_multiplier = 2.50;
            }
            if (empty($config->smoking_surcharge_percent)) {
                $config->smoking_surcharge_percent = 10.00;
            }
        });
    }

    /**
     * Relationship: Config has many questionnaire answers.
     * @return HasMany
     */
    public function answers(): HasMany
    {
        return $this->hasMany(QuestionnaireAnswer::class, 'questionnaire_config_id');
    }

    /**
     * Get the default configuration for Manulife.
     * @return array
     */
    public static function getDefaultManulifeConfig(): array
    {
        return [
            'name' => 'Manulife Medical Questionnaire',
            'slug' => 'manulife-medical-questionnaire',
            'insurance_company' => 'Manulife',
            'min_age' => 60,
            'max_age' => 120,
            'is_active' => true,
            'step1_config' => [
                'title' => 'Eligibility Check',
                'description' => 'Step 1: Determine if applicant is eligible for insurance',
                'questions' => [
                    [
                        'code' => 'heart_surgery_10y',
                        'text' => 'Have you had a heart bypass, coronary angioplasty, or heart valve surgery more than 10 years ago?',
                        'type' => 'yes_no',
                        'help_text' => 'If unsure, consult your doctor before completing this application.',
                        'is_required' => true,
                    ],
                    [
                        'code' => 'multiple_conditions',
                        'text' => 'In the last 3 years, have you been diagnosed with, prescribed medication for, or treated for ANY TWO of the following?',
                        'type' => 'yes_no',
                        'help_text' => 'Heart condition, Lung condition, Stroke/CVA or mini-stroke/TIA, Diabetes, Narrowed or blocked artery in the legs',
                        'is_required' => true,
                    ],
                    [
                        'code' => 'heart_failure_2y',
                        'text' => 'In the last 2 years, have you been diagnosed with, prescribed medication for, or treated for heart failure/congestive heart failure?',
                        'type' => 'yes_no',
                        'help_text' => 'Includes use of Lasix, furosemide, or other water pill for ankle/leg swelling or fluid in the lungs',
                        'is_required' => true,
                    ],
                    [
                        'code' => 'recent_health_issues',
                        'text' => 'In the last 12 months, have you had any of the following?',
                        'type' => 'yes_no',
                        'help_text' => 'New heart condition or change in medication/hospitalization for existing heart condition; Shortness of breath or chest pain requiring medical treatment; Lung condition with hospitalization or prednisone prescription; Cancer treatment with chemotherapy, radiotherapy, or other active treatment',
                        'is_required' => true,
                    ],
                    [
                        'code' => 'multiple_medications',
                        'text' => 'In the last 4 months, have you taken 6 or more prescription medications?',
                        'type' => 'yes_no',
                        'help_text' => 'Excludes hormone replacement therapy, osteoporosis medication, traveler\'s diarrhea treatment, immunizations, and most topical medications',
                        'is_required' => true,
                    ],
                ],
                'failure_message' => 'You cannot purchase this plan. Please contact us.',
                'instructions' => 'Any "Yes" answer in this step makes you ineligible for Manulife insurance.',
            ],
            'step2_config' => [
                'title' => 'Rate Category C Triggers',
                'description' => 'Step 2: Automatic triggers for highest rate category',
                'questions' => [
                    [
                        'code' => 'serious_conditions',
                        'text' => 'Have you ever been diagnosed with or treated for: a) Heart condition; b) Any of: aortic aneurysm, cirrhosis of the liver, Parkinson\'s disease, Alzheimer\'s/dementia?',
                        'type' => 'yes_no',
                        'is_required' => true,
                    ],
                    [
                        'code' => 'high_bp_meds',
                        'text' => 'In the last 3 months, have you been prescribed or taken 3 or more medications for high blood pressure?',
                        'type' => 'yes_no',
                        'is_required' => true,
                    ],
                    [
                        'code' => 'recent_conditions',
                        'text' => 'In the last 5 years, have you been diagnosed with, prescribed medication for, or treated for any of: Lung condition, Stroke/CVA or mini-stroke/TIA, Diabetes (treated with medication/insulin), Narrowed or blocked artery in the legs or neck?',
                        'type' => 'yes_no',
                        'is_required' => true,
                    ],
                ],
                'trigger_message' => 'Rate Category C will be applied (highest premium).',
                'instructions' => 'Any "Yes" answer automatically places you in Rate Category C.',
            ],
            'step3_config' => [
                'title' => 'Rate Category B Triggers',
                'description' => 'Step 3: Triggers for medium rate category',
                'questions' => [
                    [
                        'code' => 'gastrointestinal',
                        'text' => 'In the last 2 years, have you been diagnosed with, prescribed medication for, or treated for any of: Gastrointestinal bleeding, bowel obstruction, or bowel surgery; Chronic bowel disorder; Kidney disorder; Liver disorder; Pancreatitis; Gallbladder disorder?',
                        'type' => 'yes_no',
                        'is_required' => true,
                    ],
                    [
                        'code' => 'blood_disorder',
                        'text' => 'In the last 2 years, have you been diagnosed with and/or treated by a hematologist or internist for a blood disorder?',
                        'type' => 'yes_no',
                        'is_required' => true,
                    ],
                    [
                        'code' => 'recent_falls',
                        'text' => 'Are you age 70 or older, and have you had a fall requiring medical attention in the last 6 months?',
                        'type' => 'yes_no',
                        'is_required' => true,
                    ],
                    [
                        'code' => 'er_visits',
                        'text' => 'In the last 6 months, have you received medical advice/treatment in an ER more than twice?',
                        'type' => 'yes_no',
                        'is_required' => true,
                    ],
                ],
                'trigger_message' => 'Rate Category B will be applied (medium premium).',
                'instructions' => 'All "No" answers keep you in Rate Category A.',
            ],
            'step4_config' => [
                'title' => 'Smoking Surcharge',
                'description' => 'Step 4: Smoking and vaping information',
                'questions' => [
                    [
                        'code' => 'smoking_2y',
                        'text' => 'In the last 2 years, have you smoked cigarettes and/or used vaping products and/or e-cigarettes?',
                        'type' => 'yes_no',
                        'is_required' => true,
                    ],
                    [
                        'code' => 'years_smoking',
                        'text' => 'How many years have you been smoking?',
                        'type' => 'number',
                        'min' => 0,
                        'max' => 100,
                        'conditional_on' => 'smoking_2y',
                        'conditional_value' => 'yes',
                        'is_required' => false,
                    ],
                    [
                        'code' => 'uses_vaping',
                        'text' => 'Do you currently use vaping products or e-cigarettes?',
                        'type' => 'yes_no',
                        'conditional_on' => 'smoking_2y',
                        'conditional_value' => 'yes',
                        'is_required' => false,
                    ],
                ],
                'surcharge_message' => '10% smoking surcharge will be applied to your premium.',
                'instructions' => 'Honest disclosure is required for accurate premium calculation.',
            ],
            'rate_a_multiplier' => 1.00,
            'rate_b_multiplier' => 1.50,
            'rate_c_multiplier' => 2.50,
            'smoking_surcharge_percent' => 10.00,
            'description' => 'Default Manulife medical questionnaire for applicants aged 60+. Based on Manulife Single-Trip Emergency Medical requirements.',
        ];
    }

    /**
     * Get the default configuration for JF Insurance.
     * @return array
     */
    public static function getDefaultJfConfig(): array
    {
        return [
            'name' => 'JF TOP Travel Insurance Questionnaire',
            'slug' => 'jf-top-questionnaire',
            'insurance_company' => 'JF',
            'min_age' => 60,
            'max_age' => 120,
            'is_active' => true,
            'step1_config' => [
                'title' => 'Basic Health Declaration',
                'description' => 'Step 1: Basic health information for JF TOP plan',
                'questions' => [
                    [
                        'code' => 'pre_existing_conditions',
                        'text' => 'Do you have any pre-existing medical conditions that require regular treatment or medication?',
                        'type' => 'yes_no',
                        'is_required' => true,
                    ],
                    [
                        'code' => 'recent_hospitalization',
                        'text' => 'Have you been hospitalized or had surgery in the last 12 months?',
                        'type' => 'yes_no',
                        'is_required' => true,
                    ],
                ],
                'failure_message' => 'For complex medical conditions, please contact us for alternative options.',
                'instructions' => 'JF TOP plan may have limitations for pre-existing conditions.',
            ],
            'step2_config' => null, // JF doesn't have complex steps
            'step3_config' => null,
            'step4_config' => [
                'title' => 'Lifestyle Information',
                'description' => 'Step 4: Smoking and general health',
                'questions' => [
                    [
                        'code' => 'smoking_status',
                        'text' => 'Do you smoke cigarettes?',
                        'type' => 'yes_no',
                        'is_required' => true,
                    ],
                    [
                        'code' => 'general_health',
                        'text' => 'Would you describe your general health as good, fair, or poor?',
                        'type' => 'select',
                        'options' => ['good', 'fair', 'poor'],
                        'is_required' => true,
                    ],
                ],
                'instructions' => 'This information helps determine appropriate coverage.',
            ],
            'rate_a_multiplier' => 1.00,
            'rate_b_multiplier' => 1.25,
            'rate_c_multiplier' => 1.75,
            'smoking_surcharge_percent' => 15.00,
            'description' => 'Simplified questionnaire for JF TOP Travel Insurance.',
        ];
    }

    /**
     * Get active configuration for a specific company and age.
     * @param string $company
     * @param int $age
     * @return self|null
     */
    public static function getActiveConfig(string $company, int $age): ?self
    {
        return self::where('insurance_company', $company)
            ->where('is_active', true)
            ->where('min_age', '<=', $age)
            ->where('max_age', '>=', $age)
            ->orderBy('created_at', 'desc')
            ->first();
    }

    /**
     * Create default configurations if none exist.
     * @return void
     */
    public static function seedDefaultConfigs(): void
    {
        $manulifeExists = self::where('slug', 'manulife-medical-questionnaire')->exists();
        $jfExists = self::where('slug', 'jf-top-questionnaire')->exists();

        if (!$manulifeExists) {
            $manulifeConfig = self::getDefaultManulifeConfig();
            self::create($manulifeConfig);
        }

        if (!$jfExists) {
            $jfConfig = self::getDefaultJfConfig();
            self::create($jfConfig);
        }
    }

    /**
     * Get questions for a specific step.
     * @param int $step
     * @return array
     */
    public function getStepQuestions(int $step): array
    {
        $configField = "step{$step}_config";
        $config = $this->$configField;
        
        return $config['questions'] ?? [];
    }

    /**
     * Get step configuration.
     * @param int $step
     * @return array|null
     */
    public function getStepConfig(int $step): ?array
    {
        $configField = "step{$step}_config";
        return $this->$configField;
    }

    /**
     * Check if step is enabled/configured.
     * @param int $step
     * @return bool
     */
    public function isStepEnabled(int $step): bool
    {
        $configField = "step{$step}_config";
        return !empty($this->$configField);
    }

    /**
     * Get total number of enabled steps.
     * @return int
     */
    public function getTotalSteps(): int
    {
        $steps = 0;
        for ($i = 1; $i <= 4; $i++) {
            if ($this->isStepEnabled($i)) {
                $steps++;
            }
        }
        return $steps;
    }

    /**
     * Get premium multiplier for a rate category.
     * @param string $rateCategory
     * @return float
     */
    public function getRateMultiplier(string $rateCategory): float
    {
        $field = "rate_" . strtolower($rateCategory) . "_multiplier";
        return (float) ($this->$field ?? 1.00);
    }

    /**
     * Get the display name with company.
     * @return string
     */
    public function getDisplayName(): string
    {
        return "{$this->name} ({$this->insurance_company})";
    }

    /**
     * Scope: Active configurations.
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope: Configurations for specific company.
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param string $company
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeForCompany($query, string $company)
    {
        return $query->where('insurance_company', $company);
    }

    /**
     * Scope: Configurations applicable for age.
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param int $age
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeForAge($query, int $age)
    {
        return $query->where('min_age', '<=', $age)
                     ->where('max_age', '>=', $age);
    }
}