<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
        'timezone',
        'status',
        'trial_started_at',
        'trial_ends_at',
        'email_verified_at',
        
        'email_otp',
        'email_otp_expires_at',
        'email_otp_verified_at',
    ];

    protected $hidden = [
        'password',
        'remember_token',
        'email_otp',
        'email_otp_expires_at',
        'email_otp_verified_at',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'trial_started_at'  => 'datetime',
        'trial_ends_at'     => 'datetime',

        'email_otp_expires_at' => 'datetime',
        'email_otp_verified_at' => 'datetime',
    ];

    /**
     * Computed attributes exposed to frontend
     */
    protected $appends = [
        'plan',
        'is_trial',
        'trial_days_left',
    ];

    /* ================= RELATIONSHIPS ================= */

    public function subscription(): HasOne
    {
        return $this->hasOne(Subscription::class);
    }

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

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

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

    /* ================= PLAN & ACCESS LOGIC ================= */

    public function isPro(): bool
    {
        return $this->subscription &&
               $this->subscription->status === 'active';
    }

    public function isTrialActive(): bool
    {
        return $this->trial_ends_at &&
               Carbon::now()->lt($this->trial_ends_at);
    }

    public function hasProAccess(): bool
    {
        return $this->isPro() || $this->isTrialActive();
    }

    public function trialDaysLeft(): int
    {
        if (! $this->isTrialActive()) {
            return 0;
        }

        return Carbon::now()->diffInDays($this->trial_ends_at);
    }

    /* ================= ACCESSORS ================= */

    public function getPlanAttribute(): string
    {
        if ($this->isPro()) {
            return 'pro';
        }

        return 'free';
    }

    public function getIsTrialAttribute(): bool
    {
        return $this->isTrialActive();
    }

    public function getTrialDaysLeftAttribute(): int
    {
        return $this->trialDaysLeft();
    }
}
