<?php

namespace App\Mail;

use App\Models\Job;
use App\Models\Payment;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class PaymentReceiptMail extends Mailable
{
    use Queueable, SerializesModels;

    public ?Job $job = null;
    public ?Payment $payment = null;

    // Accept either (Payment, Job) or (Job, Payment)
    public function __construct($a, $b = null)
    {
        if ($a instanceof Payment) {
            $this->payment = $a;
            $this->job     = $b instanceof Job ? $b : null;
        } elseif ($a instanceof Job) {
            $this->job     = $a;
            $this->payment = $b instanceof Payment ? $b : null;
        } else {
            throw new \InvalidArgumentException('PaymentReceiptMail expects (Job, ?Payment) or (Payment, ?Job).');
        }
    }

    public function build()
    {
        $job     = $this->job;
        $payment = $this->payment;

        // Amount & currency for the view
        $amountCents = (int)($payment->amount_cents ?? $payment->amount ?? 0);
        $currency    = strtoupper($payment->currency ?? $job->currency ?? 'NZD');

        // ✅ Booking / job reference (use external_reference first)
        $bookingRef = $job->external_reference
            ?? $job->booking_ref
            ?? $job->booking_reference
            ?? $job->job_reference
            ?? $job->reference
            ?? $job->ref
            ?? $job->code
            ?? null;

        // Hire dates (adjust names here if your schema differs)
        $startAt = $job->start_at   ?? $job->pickup_at  ?? $job->start   ?? null;
        $endAt   = $job->end_at     ?? $job->dropoff_at ?? $job->end     ?? null;

        // Friendly greeting
        $firstName = $job->customer_name ? strtok($job->customer_name, ' ') : 'there';

        // Subject line with booking number
        $subject = $bookingRef
            ? "Payment receipt – Rental Reservation {$bookingRef}"
            : "Payment receipt";

        return $this->subject($subject)->view('mail.payment-receipt', [
            'job'         => $job,
            'payment'     => $payment,
            'amountCents' => $amountCents,
            'currency'    => $currency,
            'bookingRef'  => $bookingRef,   // shown in the email body
            'startAt'     => $startAt,
            'endAt'       => $endAt,
            'firstName'   => $firstName,
        ]);
    }
}
