<?php

namespace App\Models;

use App\Traits\HasTranslations;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Package extends Model
{
    use HasFactory, SoftDeletes, HasTranslations;

    protected $fillable = [
        'name',
        'name_translations',
        'slug',
        'description',
        'description_translations',
        'short_description',
        'short_description_translations',
        'price',
        'sale_price',
        'image',
        'icon',
        'features',
        'preparation_instructions',
        'preparation_instructions_translations',
        'estimated_time',
        'sample_type',
        'collection_method',
        'fasting_instructions',
        'fasting_instructions_translations',
        'is_active',
        'is_featured',
        'is_draft',
        'draft_content',
        'badge_text',
        'badge_text_translations',
        'sort_order',
        'meta_title',
        'meta_title_translations',
        'meta_description',
        'meta_description_translations',
        'meta_keywords',
        'non_saudi_price',
        'custom_form_id',
    ];

    /**
     * Get the custom form associated with this package.
     */
    public function customForm()
    {
        return $this->belongsTo(CustomForm::class, 'custom_form_id');
    }

    protected $casts = [
        'price' => 'decimal:2',
        'sale_price' => 'decimal:2',
        'features' => 'array',
        'is_active' => 'boolean',
        'is_featured' => 'boolean',
        'is_draft' => 'boolean',
        'draft_content' => 'array',
        'name_translations' => 'array',
        'description_translations' => 'array',
        'short_description_translations' => 'array',
        'preparation_instructions_translations' => 'array',
        'badge_text_translations' => 'array',
        'fasting_instructions_translations' => 'array',
        'meta_title_translations' => 'array',
        'meta_description_translations' => 'array',
        'meta_keywords' => 'array',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($package) {
            if (empty($package->slug)) {
                $package->slug = Str::slug($package->name);
            }
        });
    }

    public function sections()
    {
        return $this->hasMany(PackageSection::class)->orderBy('sort_order');
    }

    public function tests()
    {
        return $this->belongsToMany(Test::class, 'package_tests')
            ->withPivot('sort_order')
            ->orderByPivot('sort_order');
    }

    /**
     * Get tests grouped by their category for display.
     * Returns a collection of [category => TestCategory|null, tests => Collection<Test>] (Old)
     * OR a collection of package sections (New)
     */
    public function testsGroupedByCategory()
    {
        // 1. Check if we have sections defined
        if ($this->sections()->exists()) {
            return $this->sections()->with('tests')->get()->map(function ($section) {
                return [
                    'category' => (object) [
                        'name' => $section->name, // name is translatable
                        'translated_name' => $section->translated_name,
                        'icon' => 'fas fa-vial', // Default icon for custom sections
                        'sort_order' => $section->sort_order,
                    ],
                    'tests' => $section->tests,
                    'is_custom_section' => true,
                ];
            });
        }

        // 2. Fallback to old category logic
        $tests = $this->tests()->with('category')->get();

        $grouped = $tests->groupBy(function ($test) {
            return $test->test_category_id ?? 0;
        });

        return $grouped->map(function ($categoryTests, $categoryId) {
            return [
                'category' => $categoryId ? $categoryTests->first()->category : null,
                'tests' => $categoryTests,
                'is_custom_section' => false,
            ];
        })->sortBy(function ($group) {
            return $group['category'] ? $group['category']->sort_order : 9999;
        })->values();
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeFeatured($query)
    {
        return $query->where('is_featured', true);
    }

    public function scopePublished($query)
    {
        return $query->where('is_active', true)->where('is_draft', false);
    }

    public function getFinalPriceAttribute()
    {
        return $this->sale_price ?? $this->price;
    }

    public function getDiscountPercentageAttribute()
    {
        if ($this->sale_price && $this->price > 0) {
            return round((($this->price - $this->sale_price) / $this->price) * 100);
        }
        return 0;
    }

    /**
     * Get the total test count for display (from sections or direct relationship).
     */
    public function getTestsCountAttribute(): int
    {
        if ($this->sections()->exists()) {
            return $this->sections()->withCount('tests')->get()->sum('tests_count');
        }
        return $this->tests()->count();
    }

    /**
     * Get translated fasting instructions.
     */
    public function getTranslatedFastingInstructionsAttribute(): ?string
    {
        return $this->getTranslation('fasting_instructions');
    }

    /**
     * Get translated preparation instructions.
     */
    public function getTranslatedPreparationInstructionsAttribute(): ?string
    {
        return $this->getTranslation('preparation_instructions');
    }

    /**
     * Get translated badge text.
     */
    public function getTranslatedBadgeTextAttribute(): ?string
    {
        return $this->getTranslation('badge_text');
    }
}
