<?php

namespace App\Models\Tenant;

use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Purchase extends Model
{
    use BelongsToTenant, SoftDeletes;

    public const STATUSES = [
        'draft' => 'Ciornă',
        'ordered' => 'Comandată',
        'received' => 'Recepționată',
        'cancelled' => 'Anulată',
    ];

    protected $fillable = [
        'company_id', 'number', 'supplier_id',
        'order_date', 'expected_at', 'received_at', 'paid_at',
        'status', 'total', 'notes',
    ];

    protected $casts = [
        'order_date' => 'date',
        'expected_at' => 'date',
        'received_at' => 'date',
        'paid_at' => 'date',
        'total' => 'decimal:2',
    ];

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

    public function items(): HasMany
    {
        return $this->hasMany(PurchaseItem::class);
    }

    public function recalcTotal(): void
    {
        $this->total = (float) $this->items()->sum('total');
        $this->save();
    }

    public static function generateNumber(int $companyId): string
    {
        $year = date('y');
        $count = static::withoutGlobalScopes()
            ->where('company_id', $companyId)
            ->whereYear('created_at', date('Y'))
            ->count();
        return sprintf('P-%s-%04d', $year, $count + 1);
    }

    /**
     * Mark all items received and increment Part.qty for linked items.
     */
    public function markReceived(): void
    {
        \Illuminate\Support\Facades\DB::transaction(function () {
            foreach ($this->items as $item) {
                if (! $item->received) {
                    if ($item->part_id) {
                        $part = Part::find($item->part_id);
                        $part?->adjustStock((float) $item->qty);
                    }
                    $item->received = true;
                    $item->save();
                }
            }
            $this->status = 'received';
            $this->received_at = now();
            $this->save();
        });
    }
}
