<?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 Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Mail\ResetPasswordMail;
use App\Mail\VerifyEmailMail;
use App\Traits\BelongsToOrganization;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;

class User extends Authenticatable implements MustVerifyEmail
{
    use HasFactory, Notifiable, HasApiTokens, HasRoles, SoftDeletes, BelongsToOrganization;

    protected $fillable = [
        'name',
        'email',
        'password',
        'phone',
        'is_active',
        'organization_id',
        'branch_id',
        'can_switch_branches',
        'allowed_nav',
        // is_platform_admin and platform_role_id intentionally excluded from fillable
        // to prevent privilege escalation via mass-assignment on user update endpoints.
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected function casts(): array
    {
        return [
            'email_verified_at'  => 'datetime',
            'password'           => 'hashed',
            'is_active'          => 'boolean',
            'is_platform_admin'  => 'boolean',
            'allowed_nav'        => 'array',
        ];
    }

    // Relationships
    public function sales()
    {
        return $this->hasMany(Sale::class);
    }

    public function purchases()
    {
        return $this->hasMany(Purchase::class);
    }

    public function inventoryAdjustments()
    {
        return $this->hasMany(InventoryAdjustment::class);
    }

    public function systemLogs()
    {
        return $this->hasMany(SystemLog::class);
    }

    public function platformRole()
    {
        return $this->belongsTo(PlatformRole::class, 'platform_role_id');
    }

    public function branch()
    {
        return $this->belongsTo(Branch::class);
    }

    /**
     * Check whether this platform user has a specific platform-level permission.
     * Users with the super_admin role automatically have all permissions.
     */
    public function hasPlatformPermission(string $permission): bool
    {
        if (! $this->is_platform_admin) {
            return false;
        }
        $role = $this->platformRole;
        // No role assigned — treat as super admin (defensive fallback for
        // the initial platform admin account or misconfigured users).
        if (! $role) {
            return true;
        }
        if ($role->name === 'super_admin') {
            return true;
        }
        return in_array($permission, $role->permissions ?? []);
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Override to send a SPA-compatible reset link instead of the default
     * Laravel reset route.
     */
    public function sendPasswordResetNotification($token): void
    {
        $url = rtrim(config('app.url'), '/') . '/reset-password'
             . '?token=' . $token
             . '&email=' . urlencode($this->email);

        Mail::to($this->email)->send(new ResetPasswordMail($this->name, $url));
    }

    /**
     * Override to send a branded, SPA-compatible email verification link.
     * The signed URL points to /verify-email/{id}/{hash} in the SPA.
     */
    public function sendEmailVerificationNotification(): void
    {
        $id   = $this->getKey();
        $hash = sha1($this->getEmailForVerification());

        $signedUrl = URL::temporarySignedRoute(
            'api.email.verify',
            now()->addHours(24),
            ['id' => $id, 'hash' => $hash]
        );

        // Rewrite to SPA URL: /verify-email/{id}/{hash}?expires=...&signature=...
        $parsed = parse_url($signedUrl);
        $spaUrl = rtrim(config('app.url'), '/') . '/verify-email/' . $id . '/' . $hash;
        if (! empty($parsed['query'])) {
            $spaUrl .= '?' . $parsed['query'];
        }

        Mail::to($this->email)->send(new VerifyEmailMail($this->name, $spaUrl));
    }
}
