<?php

namespace Yas\Member\Mail;

use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Yas\Member\Contracts\Member;
use Yas\User\Models\Admin;
use Yas\FrontTheme\Mail\Mailable;
use Illuminate\Support\Facades\DB;
use Yas\Member\Repositories\ConsignmentEnquiryRepository;
use Webkul\Attribute\Repositories\AttributeOptionRepository;
use Webkul\Attribute\Repositories\AttributeRepository;
use Yas\Member\Models\ConsignmentEnquiry;
use Webkul\Theme\Repositories\ThemeCustomizationRepository;
use Illuminate\Mail\Mailables\Attachment;
use Barryvdh\DomPDF\Facade\Pdf;

class ConsignmentFormApprovedNotification extends Mailable
{
    /**
     * Cache so we don't rebuild the data twice (content() + attachments() both run).
     *
     * Note: named $builtViewData (not $viewData) because the base
     * Illuminate\Mail\Mailable class already declares a public $viewData
     * property — re-declaring it as protected/private causes a fatal error.
     */
    protected ?array $builtViewData = null;

    /**
     * Create a new mailable instance.
     *
     * @return void
     */
    public function __construct(public Admin $admin, public ConsignmentEnquiry $consignment, public array $bccEmails = []) {}

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            to: [
                new Address($this->admin->email),
            ],
            bcc: $this->bccEmails,
            subject: trans('member::app.member.emails.consignment-approved.subject'),
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'yas_member::emails.consignment-form-approved',
            with: $this->buildViewData(),
        );
    }

    /**
     * Get the attachments for the message.
     */
    public function attachments(): array
    {
        $pdf = Pdf::loadView(
            'yas_member::emails.consignment-form-approved',
            $this->buildViewData()+ ['isPdf' => true]
        );

        return [
            Attachment::fromData(fn () => $pdf->output(), 'consignment-details.pdf')
                ->withMime('application/pdf'),
        ];
    }

    /**
     * Build the data array used by both the email body and the PDF attachment.
     */
    public function buildViewData(): array
    {
        if ($this->builtViewData !== null) {
            return $this->builtViewData;
        }

        $brandLabel = null;

        if ($this->consignment->brand) {
            $brandOption = app(AttributeOptionRepository::class)
                ->find($this->consignment->brand);

            $brandLabel = $brandOption?->admin_name ?? $brandOption?->label;
        }
        $this->consignment->brand_label = $brandLabel;

        $attributeGroupId = DB::table('attribute_groups')
            ->where('code', 'custom')
            ->value('id');

        $attributeIds = DB::table('attribute_group_mappings')
            ->where('attribute_group_id', $attributeGroupId)
            ->pluck('attribute_id')
            ->toArray();

        $attributes = app(AttributeRepository::class)
            ->whereIn('id', $attributeIds)
            ->pluck('admin_name', 'code')
            ->toArray();

        $consignmentAddressText = app(ThemeCustomizationRepository::class)->findWhere([
            'name' => 'consignment-form-address'
        ]);

        return $this->builtViewData = [
            'attributes' => $attributes,
            'consignment' => $this->consignment,
            'consignmentAddressText' => $consignmentAddressText,
        ];
    }
}