<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class Profile extends Model
{
    use HasFactory;
    const STATUS_ACTIVE = 'active';
    const STATUS_SUSPENDED = 'suspended';

    /**
     * Mass assignable attributes.
     */
    protected $fillable = [
        'user_id',
        'focused_account_id',
        'username',
        'phone',
        'dial_code',
        'gender',
        'marital_status',
        'date_of_birth',
        'country',
        'state',
        'city',
        'address_1',
        'address_2',
        'occupation',
        'status',
        'profile_photo',
        'zip_code',
        'agreement_accepted',
        'client_id',
        'transaction_pin',
        'currency',
    ];

    /**
     * Attribute casting
     */
    protected $casts = [
        'status' => 'string',
        'gender' => 'string',
        'agreement_accepted' => 'boolean',
        'date_of_birth' => 'date',
    ];

    /**
     * Relationships
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }


    // All accounts for this profile
    public function accounts(): HasMany
    {
        return $this->hasMany(Account::class);
    }

    protected $cascadeDeletes = [
        'accounts',
    ];


    // The currently focused account
    public function focusedAccount(): BelongsTo
    {
        return $this->belongsTo(Account::class, 'focused_account_id');
    }
    public function primaryAccount()
    {
        return $this->hasOne(Account::class)->where('is_primary', true);
    }
    /**
     * Boot method to handle defaults like client_id
     */
    protected static function booted()
    {
        // Keep the existing creating logic
        static::creating(function ($profile) {
            if (empty($profile->client_id)) {
                $profile->client_id = self::generateUniqueClientId();
            }
        });

        // Add deleting logic to remove related accounts
        static::deleting(function ($profile) {
            // Delete all accounts belonging to this profile
            $profile->accounts()->get()->each(function ($account) {
                $account->delete(); // triggers Account's deleting event if you have one
            });
        });
    }
    /**
     * Generate unique client ID
     */
    private static function generateUniqueClientId(): string
    {
        do {
            // Example: 8-character uppercase alphanumeric
            $clientId = 'C' . strtoupper(Str::random(7));
        } while (self::clientIdExists($clientId));

        return $clientId;
    }


    private static function clientIdExists(string $clientId): bool
    {
        return self::where('client_id', $clientId)->exists();
    }

    /**
     * Formatted phone accessor
     */
    public function getFormattedPhoneAttribute(): string
    {
        $clean = preg_replace('/[^0-9]/', '', $this->phone);

        return "+{$this->dial_code} ("
            . substr($clean, 0, 3) . ") "
            . substr($clean, 3, 3) . "-"
            . substr($clean, 6);
    }
}
