<?php

namespace App\Traits;

use App\Models\Pesanan;
use App\Models\Toko;
use App\Mail\InvoiceMail;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

trait SendsInvoice
{
    /**
     * Generate PDF and send Invoice via Email.
     *
     * @param Pesanan $pesanan
     * @return bool
     */
    public function generateAndSendInvoice(Pesanan $pesanan)
    {
        try {
            // Re-load relationships to be sure
            $pesanan->load(['user', 'detail.produk', 'alamat']);

            if ($pesanan->invoice_sent_at) {
                Log::info('Invoice already sent for order: ' . $pesanan->kode_pesanan);
                return true;
            }

            // Get the seller's store info based on the first product
            $produkPertama = $pesanan->detail->first()?->produk;
            $toko = $produkPertama 
                ? Toko::with('province')->where('user_id', $produkPertama->user_id)->first()
                : null;

            $subtotalProduk = $pesanan->detail->sum(fn($d) => $d->harga * $d->qty);

            $diskon                = 0;
            $keteranganDiskon      = null;
            $subtotalSetelahDiskon = $subtotalProduk;
            $jarakKm               = 0;
            $totalBerat            = 0;
            $kategoriProvinsi      = '-';
            $ongkirDetail          = null;
            $biayaJarak            = 0;
            $biayaBerat            = 0;
            $biayaProvinsi         = 0;

            if ($pesanan->catatan) {
                $catatan = json_decode($pesanan->catatan, true);
                if (isset($catatan['diskon'])) {
                    $diskon                = $catatan['diskon'];
                    $keteranganDiskon      = $catatan['keterangan'] ?? null;
                    $subtotalSetelahDiskon = $catatan['subtotal_setelah_diskon'] ?? $subtotalProduk;
                }
                $jarakKm          = $catatan['jarak_km'] ?? $catatan['jarak'] ?? 0;
                $totalBerat       = $catatan['rincian']['berat_gram'] ?? $catatan['berat_gram'] ?? $catatan['total_berat'] ?? $catatan['berat'] ?? 0;
                $kategoriProvinsi = $catatan['kategori_provinsi'] ?? $catatan['kategori'] ?? '-';
                $ongkirDetail     = $catatan['detail'] ?? null;
                $biayaJarak       = $catatan['biaya_jarak'] ?? 0;
                $biayaBerat       = $catatan['biaya_berat'] ?? 0;
                $biayaProvinsi    = $catatan['biaya_provinsi'] ?? 0;
            }

            $ongkir = $pesanan->total_harga - $subtotalSetelahDiskon;

            $invoiceDir = storage_path('app/public/invoices');
            if (!file_exists($invoiceDir)) {
                mkdir($invoiceDir, 0755, true);
            }

            $pdfPath = $invoiceDir . '/invoice-' . $pesanan->kode_pesanan . '.pdf';

            // Generate PDF
            $pdf = Pdf::loadView('pesanan.invoice', compact(
                'pesanan', 'toko', 'subtotalProduk', 'ongkir',
                'diskon', 'keteranganDiskon', 'subtotalSetelahDiskon',
                'jarakKm', 'totalBerat', 'kategoriProvinsi', 'ongkirDetail',
                'biayaJarak', 'biayaBerat', 'biayaProvinsi'
            ))
            ->setPaper('A4', 'portrait')
            ->setOptions([
                'defaultFont'          => 'Arial, sans-serif',
                'isRemoteEnabled'      => true,
                'isHtml5ParserEnabled' => true,
                'dpi'                  => 96,
            ]);

            $pdf->save($pdfPath);

            // Send Email
            Mail::to($pesanan->user->email)->send(new InvoiceMail(
                $pesanan, 
                $pdfPath,
                compact(
                    'toko', 'subtotalProduk', 'ongkir', 'diskon', 
                    'jarakKm', 'totalBerat', 'kategoriProvinsi',
                    'biayaJarak', 'biayaBerat', 'biayaProvinsi'
                )
            ));

            // Mark as sent
            $pesanan->invoice_sent_at = now();
            $pesanan->save();

            Log::info('Invoice automated email sent successfully', [
                'pesanan_id' => $pesanan->id,
                'email' => $pesanan->user->email
            ]);

            return true;

        } catch (\Exception $e) {
            Log::error('Failed to generate or send invoice: ' . $e->getMessage(), [
                'pesanan_id' => $pesanan->id,
                'trace' => $e->getTraceAsString()
            ]);
            return false;
        }
    }
}
