<?php

namespace App\Services;

use Illuminate\Support\Facades\Mail;
use App\Mail\OrderCreated;
use App\Mail\PaymentSuccess;
use App\Mail\OrderComplete;
use Illuminate\Support\Facades\Log;

class EmailNotificationService
{
    /**
     * Send order created notification
     */
public function sendOrderCreated($transaction)
{
    try {
        Mail::send('emails.order-created', [
            'transaction' => $transaction, // ⭐ Pass as $transaction
            'order' => $transaction,       // ⭐ ALSO as $order for backwards compatibility
        ], function ($message) use ($transaction) {
            $message->to($transaction->customer_email)
                ->subject('Pesanan Berhasil Dibuat - ' . $transaction->invoice_number);
        });
        
        return true;
    } catch (\Exception $e) {
        \Log::error('Send Order Created Email Failed', [
            'transaction_id' => $transaction->id,
            'error' => $e->getMessage(),
        ]);
        return false;
    }
}

    /**
     * Send payment success notification
     */
    public function sendPaymentSuccess($transaction)
    {
        try {
            if (!$transaction->customer_email) {
                Log::warning('No email provided for transaction: ' . $transaction->invoice_number);
                return false;
            }

            Mail::to($transaction->customer_email)
                ->send(new PaymentSuccess($transaction));

            Log::info('Payment success email sent to: ' . $transaction->customer_email);
            return true;
        } catch (\Exception $e) {
            Log::error('Failed to send payment success email: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Send order complete notification
     */
    public function sendOrderComplete($transaction)
    {
        try {
            if (!$transaction->customer_email) {
                Log::warning('No email provided for transaction: ' . $transaction->invoice_number);
                return false;
            }

            Mail::to($transaction->customer_email)
                ->send(new OrderComplete($transaction));

            Log::info('Order complete email sent to: ' . $transaction->customer_email);
            return true;
        } catch (\Exception $e) {
            Log::error('Failed to send order complete email: ' . $e->getMessage());
            return false;
        }
    }
}
