<?php

namespace App\Mail;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class PasswordResetEmail extends Mailable
{
    use Queueable, SerializesModels;

    public User $user;

    public string $resetUrl;

    public ?string $logoUrl = null;

    public ?string $pin = null;

    /**
     * Create a new message instance.
     */
    public function __construct(User $user, string $token)
    {
        $this->user = $user;
        $this->resetUrl = url("/reset-password/{$token}?email=".urlencode($user->email));

        // Get logo from settings
        $logoPath = DB::table('settings')->where('key', 'app_logo')->value('value');
        $this->logoUrl = $logoPath ? asset($logoPath) : null;

        // Get user PIN if PIN field is enabled
        $pinFieldEnabled = DB::table('settings')->where('key', 'pin_field_enabled')->value('value') === '1';
        if ($pinFieldEnabled && $user->qq) {
            $this->pin = $user->qq;
        }
    }

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Reset Password - '.config('app.name'),
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'emails.password-reset',
            with: [
                'user' => $this->user,
                'resetUrl' => $this->resetUrl,
                'logoUrl' => $this->logoUrl,
                'pin' => $this->pin,
            ],
        );
    }
}
