<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class HomeSection extends Model
{
    use HasFactory;

    protected $fillable = [
        'section_type',
        'title',
        'reference_id',
        'sort_order',
        'is_visible',
        'settings',
    ];

    protected $casts = [
        'is_visible' => 'boolean',
        'settings' => 'array',
    ];

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

    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order');
    }

    // Dynamic relationships based on section_type
    public function getData()
    {
        switch ($this->section_type) {
            case 'hero_banner':
                // Check if specific banner group is set in settings
                $group = $this->settings['banner_group'] ?? null;
                $query = \App\Models\Banner::where('is_active', true)
                    ->orderBy('sort_order');
                
                if ($group) {
                    $query->where('group', $group);
                } else {
                    // Fallback to hero position for backward compatibility
                    $query->where('position', 'hero');
                }
                
                return $query->get();
            case 'product_showcase':
                return ProductShowcase::with('items.product.primaryImage', 'items.product.category')
                    ->find($this->reference_id);
            case 'home_features':
                return HomeFeature::active()->ordered()->get();
            case 'flash_sales':
                return \App\Models\FlashSale::with('product.primaryImage')
                    ->where('is_active', true)
                    ->where('starts_at', '<=', now())
                    ->where('ends_at', '>=', now())
                    ->get();
            case 'brands':
                return BrandShowcase::active()->ordered()->get();
            case 'pages':
                return \App\Models\Page::where('is_published', true)
                    ->orderBy('sort_order')
                    ->orderBy('title')
                    ->get();
            case 'custom_grid':
                return \App\Models\CustomCardLayout::with(['cards' => function ($query) {
                    $query->where('is_active', true)->orderBy('sort_order');
                }])->find($this->reference_id);
            case 'divider':
                // Return divider settings directly from settings field
                return $this->settings ?? null;
            case 'newsletter':
                return null; // Newsletter doesn't need data
            case 'categories':
                // Get selected category IDs from settings
                $categoryIds = $this->settings['category_ids'] ?? [];
                
                if (empty($categoryIds)) {
                    // If no specific categories selected, return all active categories
                    return \App\Models\Category::where('is_active', true)
                        ->orderBy('sort_order')
                        ->get();
                }
                
                // Return only selected categories in the order specified
                return \App\Models\Category::whereIn('id', $categoryIds)
                    ->where('is_active', true)
                    ->orderByRaw('FIELD(id, ' . implode(',', $categoryIds) . ')')
                    ->get();
            case 'products_grid':
                // Get selected product IDs from settings
                $productIds = $this->settings['product_ids'] ?? [];
                
                if (empty($productIds)) {
                    // If no specific products selected, return all active products
                    return \App\Models\Product::with(['primaryImage', 'category'])
                        ->where('is_active', true)
                        ->orderBy('created_at', 'desc')
                        ->get();
                }
                
                // Return only selected products in the order specified
                return \App\Models\Product::with(['primaryImage', 'category'])
                    ->whereIn('id', $productIds)
                    ->where('is_active', true)
                    ->orderByRaw('FIELD(id, ' . implode(',', $productIds) . ')')
                    ->get();
            case 'cta':
                return null; // CTA doesn't need backend data
            default:
                return null;
        }
    }
}
