<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;

class Nationality extends BaseModel
{
    use HasFactory, Notifiable;
    protected $table = 'nationality';
    protected $fillable = ['id','name', 'code', 'created_by', 'created_at', 'updated_by', 'updated_by', 'updated_at'];

    function processvalues($formvalues, $userid, $now){
        $status = []; $result = false;
        $id = $this->resolvePostedId($formvalues['id'] ?? null);
        $postModel = new Nationality();
        $duplicate = $postModel->findDuplicate(Nationality::class, 'name', $formvalues['name'], $id);
        $formData = [
            'id' => $id,
            'name' => $formvalues['name'],
            'code' => $formvalues['code']
        ];


        if(!$duplicate){
            $result = $postModel->processPost(Nationality::class, $formData, $userid, $now);
            if ($result) {
                $status['success_message'] = "Nationality saved or updated successfully.";
            } else {
                $status['error_message'] = "Failed to save or update the Nationality.";
            }
        }else{
            $status['error_message'] = "You have provided an Entry that is already exists";
        }

        return $status;
    }

    private function resolvePostedId($value)
    {
        if (empty($value)) {
            return null;
        }

        $candidates = [$value];
        try {
            $candidates[] = decrypt($value);
        } catch (\Throwable $e) {
            // Plain UUID/numeric value; continue.
        }

        foreach (array_unique($candidates) as $candidate) {
            if (is_numeric($candidate)) {
                return (int) $candidate;
            }

            $record = self::where('uuid', $candidate)->first();
            if ($record) {
                return (int) $record->id;
            }
        }

        return null;
    }
}
