<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\BaseModel;

class User extends BaseModel
{
    use HasFactory;

    protected $table = 'app_user';

    public function getRouteKeyName()
    {
        return 'uid';
    }

    public static function isLoggedIn($sessionKey)
    {

        if (!$sessionKey) {
            return false;
        }

        $appSession = AppSession::where('session_key', $sessionKey)->first();
        if (!$appSession) {
            return false;
        }

        if (!$appSession->is_active) {
            return false;
        }

        return true;
    }

    public static function getUserBySessionKey($sessionKey)
    {
        $appSession = AppSession::where('session_key', $sessionKey)->first();
        if (!$appSession) {
            return null;
        }

        if (!$appSession->is_active) {
            return null;
        }
        return $appSession->user;
    }

    public function paymentMethods()
    {
        return $this->hasMany(PaymentMethod::class, 'user_id', 'id')->orderBy('created_at', 'DESC');
    }

    public function defaultPaymentMethod()
    {
        return $this->hasOne(PaymentMethod::class, 'id', 'default_payment_method_id')->where('is_removed', false);
    }
   

    public function displayName()
    {
        if ($this->full_name) return $this->full_name;
        return $this->name_first . ' ' . $this->name_last;
    }

    public function getName()
    {
        if ($this->legal_first_name && $this->legal_last_name) return $this->legal_first_name . ' ' . $this->legal_last_name;
        return $this->displayName();
    }

    public function getEmail()
    {
        if ($this->email) return $this->email;
        if ($this->google_login_email) return $this->google_login_email;
        if ($this->facebook_login_email) return $this->facebook_login_email;
    }


    public function storeOrdersAsClient() {
        return $this->hasMany(StoreOrder::class, 'user_id', 'id')->orderBy('created_at', 'DESC');
    }
    
    public function memos()
    {
        return $this->hasMany(Memo::class, 'app_user_id', 'id')->orderBy('created_at', 'DESC');
    }

    public function detailJson($toArray = false)
    {
        if($toArray){
            return json_decode($this->detail_json ?? '{}', true);
        }
        return json_decode($this->detail_json ?? '{}');
    }

    public function getDetailJsonValue($field)
    {
        $parsed = $this->detailJson(true);
        if (isset($parsed[$field])) {
            return $parsed[$field];
        }
        return null;
    }
}
