<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;

class ProductionCycle extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'farm_id', 'pond_id', 'cycle_number', 'start_date', 'end_date',
        'status', 'harvest_id', 'notes',
    ];

    protected function casts(): array
    {
        return [
            'start_date' => 'date',
            'end_date' => 'date',
        ];
    }

    public function pond(): BelongsTo
    {
        return $this->belongsTo(Pond::class);
    }

    public function stockingRecords(): HasMany
    {
        return $this->hasMany(StockingRecord::class, 'cycle_id');
    }

    public function feedingLogs(): HasMany
    {
        return $this->hasMany(FeedingLog::class, 'cycle_id');
    }

    public function waterQualityLogs(): HasMany
    {
        return $this->hasMany(WaterQualityLog::class, 'cycle_id');
    }

    public function mortalityLogs(): HasMany
    {
        return $this->hasMany(MortalityLog::class, 'cycle_id');
    }

    public function treatmentLogs(): HasMany
    {
        return $this->hasMany(TreatmentLog::class, 'cycle_id');
    }

    public function samplingRecords(): HasMany
    {
        return $this->hasMany(SamplingRecord::class, 'cycle_id');
    }

    public function harvestRecord(): HasOne
    {
        return $this->hasOne(HarvestRecord::class, 'cycle_id');
    }

    public function expenseRecords(): HasMany
    {
        return $this->hasMany(ExpenseRecord::class, 'cycle_id');
    }

    public function getDaysElapsedAttribute(): int
    {
        $end = $this->end_date ?? now();

        return (int) $this->start_date->diffInDays($end);
    }

    public function getTotalFedKgAttribute(): float
    {
        return (float) $this->feedingLogs()->sum('quantity_kg');
    }

    public function getTotalMortalityAttribute(): int
    {
        return (int) $this->mortalityLogs()->sum('dead_count');
    }

    public function getTotalStockedAttribute(): int
    {
        return (int) $this->stockingRecords()->sum('quantity');
    }

    public function getEstimatedLiveCountAttribute(): int
    {
        return max(0, $this->total_stocked - $this->total_mortality);
    }

    public function getActiveWithdrawalAttribute(): ?TreatmentLog
    {
        return $this->treatmentLogs()
            ->whereNotNull('harvest_safe_after')
            ->where('harvest_safe_after', '>', now()->toDateString())
            ->latest('treatment_date')
            ->first();
    }

    public function isOpen(): bool
    {
        return $this->status === 'open';
    }
}
