<?php

namespace App\Models;

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

class Forecast extends Model
{
    use HasFactory;

    protected $table = 't_forecasts';

    protected $fillable = [
        'store_id',
        'upload_date',
        'year',
        'month',
        'forecast_number',
        'status',
        'notes',
        'uploaded_file',
        'delete_flag',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'upload_date' => 'date',
        'delete_flag' => 'boolean',
    ];

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function modificator()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    public function store()
    {
        return $this->belongsTo(Store::class, 'store_id');
    }

    public function details()
    {
        return $this->hasMany(ForecastDetail::class, 'forecast_header_id');
    }

    public function activeDetails()
    {
        return $this->hasMany(ForecastDetail::class, 'forecast_header_id')
            ->where('delete_flag', 0);
    }

    // Generate forecast number
    public static function generateForecastNumber($storeId, $year, $month)
    {
        $store = Store::find($storeId);
        $storeCode = $store ? strtoupper(substr($store->name, 0, 3)) : 'STR';
        
        // Format: FC-STR-2025-01-001
        $prefix = "FC-{$storeCode}-{$year}-" . str_pad($month, 2, '0', STR_PAD_LEFT);
        
        // Get last number for this prefix
        $lastNumber = static::where('forecast_number', 'like', $prefix . '%')
            ->where('delete_flag', 0)
            ->orderBy('forecast_number', 'desc')
            ->value('forecast_number');
        
        if ($lastNumber) {
            $lastSequence = intval(substr($lastNumber, -3));
            $newSequence = $lastSequence + 1;
        } else {
            $newSequence = 1;
        }
        
        return $prefix . '-' . str_pad($newSequence, 3, '0', STR_PAD_LEFT);
    }

    // Check if forecast exists for store, year, month
    public static function existsForPeriod($storeId, $year, $month)
    {
        return static::where('store_id', $storeId)
            ->where('year', $year)
            ->where('month', $month)
            ->where('delete_flag', 0)
            ->exists();
    }

    // Get forecast for period
    public static function getForPeriod($storeId, $year, $month)
    {
        return static::where('store_id', $storeId)
            ->where('year', $year)
            ->where('month', $month)
            ->where('delete_flag', 0)
            ->first();
    }

    // Get period display
    public function getPeriodDisplayAttribute()
    {
        return $this->year . '-' . str_pad($this->month, 2, '0', STR_PAD_LEFT);
    }

    // Get month name
    public function getMonthNameAttribute()
    {
        return date('F', mktime(0, 0, 0, $this->month, 1));
    }

    // Get status badge class
    public function getStatusBadgeClassAttribute()
    {
        return match($this->status) {
            'Confirmed' => 'success',
            'Draft' => 'secondary',
            'Cancelled' => 'danger',
            default => 'secondary'
        };
    }

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

        static::creating(function ($model) {
            if (empty($model->forecast_number)) {
                $model->forecast_number = static::generateForecastNumber(
                    $model->store_id, 
                    $model->year, 
                    $model->month
                );
            }
            
            if (empty($model->upload_date)) {
                $model->upload_date = now()->toDateString();
            }
        });
    }
}
