<?php

namespace App\Models;

use App\Enums\CommissionType;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;

class Partner extends Model
{
    use HasFactory;
    use SoftDeletes;
    use LogsActivity;

    protected $table = 'partners';

    protected $fillable = [
        'name',
        'phone',
        'address',
        'notes',
        'default_commission_type',
        'default_commission_value',
        'is_active',
        'logo',
        'open_time',
        'close_time',
    ];

    protected function casts(): array
    {
        return [
            'default_commission_type'  => CommissionType::class,
            'default_commission_value' => 'decimal:2',
            'is_active'                => 'boolean',
        ];
    }

    /**
     * Apakah mitra sedang buka sekarang.
     * Logic:
     *   - is_active = false → selalu tutup
     *   - open_time atau close_time null → dianggap selalu buka (jika is_active=true)
     *   - Keduanya ada → cek jam saat ini dalam rentang buka-tutup
     *   - Support lintas tengah malam: open > close (misal 22:00 – 02:00)
     */
    public function isOpenNow(): bool
    {
        if (! $this->is_active) {
            return false;
        }

        if ($this->open_time === null || $this->close_time === null) {
            return true; // jam tidak diatur → dianggap selalu buka
        }

        $now   = now()->format('H:i:s');
        $open  = $this->open_time;
        $close = $this->close_time;

        if ($open <= $close) {
            // Normal: 08:00 – 21:00
            return $now >= $open && $now < $close;
        }

        // Lintas tengah malam: 22:00 – 02:00
        return $now >= $open || $now < $close;
    }

    /**
     * Inisial nama mitra untuk avatar fallback.
     */
    public function getInitialAttribute(): string
    {
        return strtoupper(substr($this->name, 0, 1));
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['name', 'phone', 'is_active', 'default_commission_type', 'default_commission_value'])
            ->logOnlyDirty()
            ->useLogName('partner');
    }

    // ── Relationships ─────────────────────────────────────────────────────

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

    public function activeProducts(): HasMany
    {
        return $this->hasMany(Product::class)->where('is_active', true);
    }

    // ── Scopes ────────────────────────────────────────────────────────────

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }
}
