<?php

namespace App\Models;

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

class Reseller extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'company',
        'commission_percentage',
        'balance',
        'status',
        'phone',
        'settings',
    ];

    protected $casts = [
        'commission_percentage' => 'decimal:2',
        'balance' => 'decimal:2',
        'settings' => 'array',
    ];

    /**
     * Get a reseller setting with default fallback value.
     */
    public function getSetting(string $key, $default = null)
    {
        $settings = $this->settings ?? [];
        return $settings[$key] ?? $default;
    }

    /**
     * Get the user that owns the reseller account.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the commissions earned by the reseller.
     */
    public function commissions()
    {
        return $this->hasMany(ResellerCommission::class);
    }

    /**
     * Get the wallet transactions for the reseller.
     */
    public function transactions()
    {
        return $this->hasMany(ResellerWalletTransaction::class)->orderBy('created_at', 'desc');
    }

    /**
     * Get the vouchers generated by the reseller.
     */
    public function vouchers()
    {
        return $this->hasMany(Voucher::class);
    }

    /**
     * Get the customers associated with this reseller.
     */
    public function customers()
    {
        return $this->hasMany(CustomersInfo::class, 'reseller_id');
    }

    /**
     * Get the collections from this reseller's customers.
     */
    public function collections()
    {
        return $this->hasManyThrough(
            \App\Models\CollectionSummary::class,
            \App\Models\CustomersInfo::class,
            'reseller_id',
            'customer_collection_unique_id',
            'id',
            'customer_unique_id'
        );
    }

    /**
     * Get the packages assigned to this reseller by the admin.
     */
    public function assignedPackages()
    {
        return $this->belongsToMany(PackageList::class, 'reseller_packages', 'reseller_id', 'package_id');
    }

    /**
     * Get the custom packages created specifically by/for this reseller.
     */
    public function customPackages()
    {
        return $this->hasMany(PackageList::class, 'reseller_id');
    }

    /**
     * Check if the reseller is active.
     */
    public function isActive(): bool
    {
        return $this->status === 'active';
    }

    /**
     * Get the total collections from this reseller's customers.
     */
    public function totalCollections(): float
    {
        if (array_key_exists('total_collected', $this->getAttributes())) {
            return (float) ($this->total_collected ?? 0.00);
        }
        return (float) $this->collections()->sum('collection_amount');
    }

    /**
     * Get the total commission profit earned by this reseller.
     */
    public function totalProfit(): float
    {
        if (array_key_exists('total_profit', $this->getAttributes())) {
            return (float) ($this->total_profit ?? 0.00);
        }
        return (float) $this->commissions()->sum('amount');
    }
}
