<?php

namespace App\Models;

use App\Enums\ProductType;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasUuids, HasFactory;

    protected $guarded = [];

    protected $casts = [
        'product_type' => ProductType::class,
        'custom_data' => 'array',
        'infrastructure_status' => 'array',
        'area' => 'decimal:2',
        'price_per_unit' => 'decimal:2',
        'total_price' => 'decimal:2',
        'building_density' => 'decimal:2',
    ];

    public function project()
    {
        return $this->belongsTo(Project::class);
    }

    public function contracts()
    {
        return $this->hasMany(Contract::class);
    }

    public function settlements()
    {
        return $this->hasMany(Settlement::class);
    }

    public function appendices()
    {
        return $this->hasMany(Appendix::class);
    }

    public function salesPhases()
    {
        return $this->belongsToMany(SalesPhase::class, 'sales_phase_products')
                    ->using(SalesPhaseProduct::class)
                    ->withPivot('id', 'sale_price', 'land_value', 'foundation_value', 'discount_details', 'status')
                    ->withTimestamps();
    }

    public function activeSalesPhase()
    {
        return $this->salesPhases()
                    ->wherePivot('status', 'Còn hàng')
                    ->where('sales_phases.status', 'Đang mở bán')
                    ->whereDate('sales_phases.start_date', '<=', now())
                    ->where(function ($q) {
                        $q->whereNull('sales_phases.end_date')
                          ->orWhereDate('sales_phases.end_date', '>=', now());
                    })
                    ->first();
    }
}
