<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Traits\Archivable;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, SoftDeletes, Archivable;

    /* Mass-assignable columns ------------------------------------------- */
    protected $fillable = [
        'franchisee_id',
        'name',
        'email',
        'password',
        'role',
        'email_verified_at',
        'remember_token',
    ];

    /* Hidden on serialisation ------------------------------------------- */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /* Casts -------------------------------------------------------------- */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];

    /* Primary key settings ---------------------------------------------- */
    // id is bigint auto-increment → keep Laravel defaults
    // public $incrementing = true;   // default
    // protected $keyType = 'int';    // default
    // No UUID generator needed

    /* Relationship: user → franchise ------------------------------------ */

    public static function boot()
    {
        parent::boot();

        static::saved(function ($model) {
            if ($model->role === 'franchise_admin' && $model->franchisee_id) {
                $globalPages = \App\Models\Page::where('is_global', true)
                    ->where('status', 'publish')
                    ->get();
                foreach ($globalPages as $page) {
                    $exists = \App\Models\PageTranslationSubmission::where('franchisee_id', $model->franchisee_id)
                        ->where('page_id', $page->id)
                        ->where('language_code', 'en')
                        ->exists();
                    if (!$exists) {
                        //$status = ($page->status == "Published") ? "approved" : $page->status;
                        \App\Models\PageTranslationSubmission::create([
                            'franchisee_id' => $model->franchisee_id,
                            'page_id' => $page->id,
                            'language_code' => 'en',
                            'translated_content' => $page->content,
                            'status' => 'approved'
                        ]);
                    }
                }
            }
        });
    }

    public function franchisee(): BelongsTo
    {
        return $this->belongsTo(Franchisee::class, 'franchisee_id');
    }
}
