<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Carbon;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
        'business_name',
        'business_type',
        'phone',
        'logo_path',
        'address',
        'bank_name',
        'account_number',
        'account_name',
        'invoice_prefix',
        'invoice_counter',
        'payment_terms',
        'default_invoice_notes',
        'plan',
        'plan_expires_at',
        'notify_invoice_sent',
        'notify_payment_received',
        'notify_payment_reminder',
        'notify_overdue',
        'onboarding_complete',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected function casts(): array
    {
        return [
            'email_verified_at'    => 'datetime',
            'plan_expires_at'      => 'datetime',
            'password'             => 'hashed',
            'onboarding_complete'  => 'boolean',
            'notify_invoice_sent'  => 'boolean',
            'notify_payment_received' => 'boolean',
            'notify_payment_reminder' => 'boolean',
            'notify_overdue'       => 'boolean',
        ];
    }

    // ─────────────────────────────────────────
    // RELATIONSHIPS
    // ─────────────────────────────────────────

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

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

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

    // ─────────────────────────────────────────
    // PLAN HELPERS
    // ─────────────────────────────────────────

    public function isFreePlan(): bool
    {
        return $this->plan === 'free';
    }

    public function isProPlan(): bool
    {
        return $this->plan === 'pro';
    }

    public function isBusinessPlan(): bool
    {
        return $this->plan === 'business';
    }

    public function canAccessReports(): bool
    {
        return in_array($this->plan, ['business']);
    }

    public function canExportCsv(): bool
    {
        return in_array($this->plan, ['business']);
    }

    public function canUseReminders(): bool
    {
        return in_array($this->plan, ['pro', 'business']);
    }

    /**
     * Check if a free-plan user has hit the monthly invoice limit.
     */
    public function hasReachedInvoiceLimit(): bool
    {
        if (! $this->isFreePlan()) {
            return false;
        }

        $limit = (int) config('invotrack.free_invoice_limit', 5);
        $count = $this->invoices()
            ->whereYear('created_at', Carbon::now()->year)
            ->whereMonth('created_at', Carbon::now()->month)
            ->count();

        return $count >= $limit;
    }

    public function monthlyInvoiceCount(): int
    {
        return $this->invoices()
            ->whereYear('created_at', Carbon::now()->year)
            ->whereMonth('created_at', Carbon::now()->month)
            ->count();
    }

    // ─────────────────────────────────────────
    // INVOICE NUMBER GENERATOR
    // ─────────────────────────────────────────

    /**
     * Generate the next invoice number for this user and increment the counter.
     * Returns e.g. "INV-0001", "INV-0042"
     */
    public function generateInvoiceNumber(): string
    {
        $this->increment('invoice_counter');
        $this->refresh();

        return sprintf(
            '%s-%04d',
            $this->invoice_prefix ?: 'INV',
            $this->invoice_counter
        );
    }

    // ─────────────────────────────────────────
    // DISPLAY HELPERS
    // ─────────────────────────────────────────

    public function getLogoUrlAttribute(): ?string
    {
        if ($this->logo_path) {
            return asset('storage/' . $this->logo_path);
        }
        return null;
    }

    public function getDisplayNameAttribute(): string
    {
        return $this->business_name ?: $this->name;
    }

    public function getPlanLabelAttribute(): string
    {
        return match ($this->plan) {
            'pro'      => 'Pro',
            'business' => 'Business',
            default    => 'Free',
        };
    }

    public function subscriptions(): HasMany{
        return $this->hasMany(\App\Models\Subscription::class);
    }

     public function activeSubscription(): ?\App\Models\Subscription
     {
           return $this->subscriptions()
           ->where('status', 'active')
           ->where('expires_at', '>', now())
           ->latest()
           ->first();
     }
    
}
