<?php
// app/Models/InvoiceDay.php

namespace App\Models;

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

class InvoiceDay extends Model
{
    use HasFactory;

    protected $fillable = [
        'invoice_id',
        'day_number',
        'day_date',
        'seasonal_hike_percentage',
        'seasonal_sessions',
    ];

    protected $casts = [
        'day_date' => 'date',
        'seasonal_hike_percentage' => 'decimal:2',
        'seasonal_sessions' => 'array',
    ];

    public function invoice()
    {
        return $this->belongsTo(Invoice::class);
    }

    public function services()
    {
        return $this->hasMany(InvoiceDayService::class);
    }

    public function hotels()
    {
        return $this->hasMany(InvoiceDayHotel::class);
    }

    public function extraServices()
    {
        return $this->hasMany(InvoiceDayExtraService::class);
    }

    public function dayDescriptions()
    {
        return $this->belongsToMany(DayDescription::class, 'invoice_day_descriptions')
                    ->withTimestamps();
    }

    // NEW: Helper method to get seasonal sessions as formatted string
    public function getSeasonalSessionsDisplayAttribute()
    {
        if (empty($this->seasonal_sessions)) {
            return 'No seasonal sessions';
        }

        return collect($this->seasonal_sessions)
            ->map(fn($session) => "{$session['name']} (+{$session['percentage']}%)")
            ->join(', ');
    }

    // NEW: Helper method to check if day has seasonal pricing
    public function hasSeasonalPricing()
    {
        return $this->seasonal_hike_percentage > 0 && !empty($this->seasonal_sessions);
    }

    // NEW: Calculate total base amount for this day (without seasonal)
    public function calculateBaseAmount(): float
    {
        $total = 0;
        
        foreach ($this->services as $service) {
            $total += ($service->unit_price ?? 0) * ($service->qty ?? 1);
        }
        
        foreach ($this->hotels as $hotel) {
            $total += ($hotel->price ?? 0) * ($hotel->qty ?? 1);
        }
        
        foreach ($this->extraServices as $extra) {
            $total += ($extra->price ?? 0) * ($extra->quantity ?? 1);
        }
        
        return $total;
    }

    // NEW: Calculate seasonal amount for this day
    public function calculateSeasonalAmount(): float
    {
        $baseAmount = $this->calculateBaseAmount();
        return $baseAmount * ($this->seasonal_hike_percentage / 100);
    }

    // NEW: Get total amount for this day (base + seasonal)
    public function getTotalAmount(): float
    {
        $baseAmount = $this->calculateBaseAmount();
        $seasonalAmount = $this->calculateSeasonalAmount();
        return $baseAmount + $seasonalAmount;
    }

    // NEW: Get seasonal sessions as formatted array
    public function getFormattedSessions(): array
    {
        if (empty($this->seasonal_sessions)) {
            return [];
        }
        
        return collect($this->seasonal_sessions)->map(function($session) {
            return [
                'name' => $session['name'] ?? 'Unknown',
                'type' => $session['type'] ?? 'regular',
                'percentage' => $session['percentage'] ?? 0,
                'description' => $session['description'] ?? null,
                'color_code' => $session['color_code'] ?? '#FF6B6B'
            ];
        })->toArray();
    }

    // NEW: Check if this day has specific seasonal session
    public function hasSession(string $sessionName): bool
    {
        if (empty($this->seasonal_sessions)) {
            return false;
        }
        
        return collect($this->seasonal_sessions)->contains(function($session) use ($sessionName) {
            return ($session['name'] ?? '') === $sessionName;
        });
    }
}