<?php

namespace App\Services;

use App\Models\Notification;
use App\Models\Order;
use App\Models\ProductInquiry;
use App\Models\Contact;
use App\Models\Production;
use App\Models\Receivable;
use App\Models\User;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;

class NotificationService
{
    /**
     * =========================
     * ORDER
     * =========================
     */
    public function notifyNewOrder(Order $order, $sendEmail = true)
    {
        $productTitle = $order->product?->product_title ?? 'N/A';

        // Admin
        $this->createNotification([
            'type' => 'order',
            'subtype' => 'new_order',
            'title' => 'Pesanan Baru',
            'message' => "Pesanan baru dari {$order->customer_name} untuk produk {$productTitle}",
            'data' => [
                'order_id' => $order->id,
                'customer_name' => $order->customer_name,
                'customer_email' => $order->customer_email,
                'product_title' => $productTitle,
                'total_price' => $order->total_price,
                'payment_method' => $order->payment_method,
            ],
            'role' => 'admin',
            'related_order_id' => $order->id,
        ], $sendEmail);

        // User
        if ($order->user_id) {
            $this->createNotification([
                'type' => 'order',
                'subtype' => 'order_created',
                'title' => 'Pesanan Anda Telah Diterima',
                'message' => "Pesanan Anda untuk {$productTitle} telah diterima dan sedang diproses",
                'data' => [
                    'order_id' => $order->id,
                    'product_title' => $productTitle,
                    'total_price' => $order->total_price,
                ],
                'user_id' => $order->user_id,
                'related_order_id' => $order->id,
            ], false);
        }
    }

    public function notifyPaymentReceived(Order $order)
    {
        $productTitle = $order->product?->product_title ?? 'N/A';
        
        // Admin
        $this->createNotification([
            'type' => 'order',
            'subtype' => 'payment_received',
            'title' => 'Pembayaran Diterima',
            'message' => "Pembayaran untuk pesanan #{$order->id} dari {$order->customer_name} untuk produk {$productTitle} telah diterima",
            'data' => [
                'order_id' => $order->id,
                'customer_name' => $order->customer_name,
                'customer_email' => $order->customer_email,
                'product_title' => $productTitle,
                'total_price' => $order->total_price,
                'payment_method' => $order->payment_method,
            ],
            'role' => 'admin',
            'related_order_id' => $order->id,
        ], true);
        
        // User
        $targetUserId = null;
        if ($order->user_id) {
            $targetUserId = $order->user_id;
        } elseif ($order->customer_email) {
            $user = User::where('email', $order->customer_email)->first();
            if ($user) {
                $targetUserId = $user->id;
            }
        }
        
        if ($targetUserId) {
            $this->createNotification([
                'type' => 'order',
                'subtype' => 'payment_received',
                'title' => 'Pembayaran Anda Diterima! ✅',
                'message' => "Pembayaran untuk pesanan #{$order->id} ({$productTitle}) telah diterima dan diverifikasi. Terima kasih!",
                'data' => [
                    'order_id' => $order->id,
                    'product_title' => $productTitle,
                    'total_price' => $order->total_price,
                    'payment_method' => $order->payment_method,
                ],
                'user_id' => $targetUserId,
                'related_order_id' => $order->id,
            ], false);
        }
    }

    public function notifyOrderStatusChanged(Order $order, $oldStatus, $newStatus)
    {
        $productTitle = $order->product?->product_title ?? 'N/A';
        $statusLabels = [
            'menunggu' => 'Menunggu',
            'diterima' => 'Diterima',
            'ditolak' => 'Ditolak',
        ];

        // Tentukan user yang akan menerima notifikasi
        $targetUserId = null;
        
        // Prioritas 1: Jika order punya user_id, gunakan itu
        if ($order->user_id) {
            $targetUserId = $order->user_id;
        } 
        // Prioritas 2: Jika tidak ada user_id, cari user berdasarkan email
        elseif ($order->customer_email) {
            $user = User::where('email', $order->customer_email)->first();
            if ($user) {
                $targetUserId = $user->id;
            }
        }

        // Kirim notifikasi jika ada target user
        if ($targetUserId) {
            // Buat pesan yang lebih informatif berdasarkan status
            $title = 'Status Pesanan Diubah';
            $message = "Status pesanan #{$order->id} untuk produk {$productTitle} telah diubah menjadi: " . ($statusLabels[$newStatus] ?? ucfirst($newStatus));
            
            // Pesan khusus untuk status "diterima"
            if ($newStatus === 'diterima') {
                $title = 'Pesanan Anda Diterima! 🎉';
                $message = "Pesanan Anda #{$order->id} untuk produk {$productTitle} telah diterima dan akan segera diproses. Terima kasih atas kepercayaan Anda!";
            }
            // Pesan khusus untuk status "ditolak"
            elseif ($newStatus === 'ditolak') {
                $title = 'Pesanan Ditolak';
                $message = "Maaf, pesanan Anda #{$order->id} untuk produk {$productTitle} telah ditolak. Silakan hubungi admin untuk informasi lebih lanjut.";
            }

            $this->createNotification([
                'type' => 'order',
                'subtype' => 'order_status_changed',
                'title' => $title,
                'message' => $message,
                'data' => [
                    'order_id' => $order->id,
                    'product_title' => $productTitle,
                    'old_status' => $oldStatus,
                    'new_status' => $newStatus,
                ],
                'user_id' => $targetUserId,
                'related_order_id' => $order->id,
            ], false);
        } else {
            // Log jika tidak ada user yang ditemukan
            Log::warning('Cannot send order status notification: No user found', [
                'order_id' => $order->id,
                'customer_email' => $order->customer_email,
                'user_id' => $order->user_id,
                'new_status' => $newStatus
            ]);
        }
    }

    public function notifyPaymentStatusChanged(Order $order, $oldStatus, $newStatus)
    {
        $productTitle = $order->product?->product_title ?? 'N/A';
        $statusLabels = [
            'menunggu' => 'Menunggu',
            'menunggu_verifikasi' => 'Menunggu Verifikasi',
            'diproses' => 'Diproses',
            'selesai' => 'Selesai',
            'gagal' => 'Gagal',
            'dibatalkan' => 'Dibatalkan',
        ];

        // Tentukan user yang akan menerima notifikasi
        $targetUserId = null;
        if ($order->user_id) {
            $targetUserId = $order->user_id;
        } elseif ($order->customer_email) {
            $user = User::where('email', $order->customer_email)->first();
            if ($user) {
                $targetUserId = $user->id;
            }
        }

        // Kirim notifikasi jika ada target user
        if ($targetUserId) {
            // Buat pesan yang lebih informatif untuk status penting
            $title = 'Status Pembayaran Diubah';
            $message = "Status pembayaran pesanan #{$order->id} untuk produk {$productTitle} telah diubah menjadi: " . ($statusLabels[$newStatus] ?? ucfirst($newStatus));
            
            // Pesan khusus untuk status "selesai"
            if ($newStatus === 'selesai') {
                $title = 'Pembayaran Lunas! ✅';
                $message = "Pembayaran untuk pesanan #{$order->id} ({$productTitle}) telah lunas. Terima kasih!";
            }
            // Pesan khusus untuk status "menunggu_verifikasi"
            elseif ($newStatus === 'menunggu_verifikasi') {
                $title = 'Bukti Pembayaran Sedang Diverifikasi';
                $message = "Bukti pembayaran untuk pesanan #{$order->id} ({$productTitle}) sedang dalam proses verifikasi. Kami akan menginformasikan hasilnya segera.";
            }
            // Pesan khusus untuk status "gagal"
            elseif ($newStatus === 'gagal') {
                $title = 'Pembayaran Gagal';
                $message = "Pembayaran untuk pesanan #{$order->id} ({$productTitle}) gagal. Silakan hubungi admin untuk informasi lebih lanjut.";
            }

            $this->createNotification([
                'type' => 'order',
                'subtype' => 'payment_status_changed',
                'title' => $title,
                'message' => $message,
                'data' => [
                    'order_id' => $order->id,
                    'product_title' => $productTitle,
                    'old_status' => $oldStatus,
                    'new_status' => $newStatus,
                ],
                'user_id' => $targetUserId,
                'related_order_id' => $order->id,
            ], false);
        }
    }

    public function notifyPaymentProofUploaded(Order $order)
    {
        $productTitle = $order->product?->product_title ?? 'N/A';

        // Admin
        $this->createNotification([
            'type' => 'order',
            'subtype' => 'payment_proof_uploaded',
            'title' => 'Bukti Pembayaran Diupload',
            'message' => "Bukti pembayaran untuk pesanan #{$order->id} dari {$order->customer_name} telah diupload dan menunggu verifikasi",
            'data' => [
                'order_id' => $order->id,
                'customer_name' => $order->customer_name,
                'customer_email' => $order->customer_email,
                'product_title' => $productTitle,
                'total_price' => $order->total_price,
                'payment_method' => $order->payment_method,
            ],
            'role' => 'admin',
            'related_order_id' => $order->id,
        ], true);
    }

    /**
     * @deprecated Notifikasi ini sudah ditangani oleh notifyOrderStatusChanged dengan pesan khusus
     * untuk status 'ditolak'. Method ini tetap ada untuk backward compatibility tapi sebaiknya
     * tidak digunakan lagi untuk menghindari duplikasi notifikasi.
     */
    public function notifyOrderRejected(Order $order)
    {
        // Method ini sudah tidak digunakan karena notifyOrderStatusChanged sudah menangani
        // notifikasi untuk status 'ditolak' dengan pesan yang lebih informatif.
        // Tetap ada untuk backward compatibility.
        Log::info('notifyOrderRejected called but should use notifyOrderStatusChanged instead', [
            'order_id' => $order->id
        ]);
    }

    /**
     * =========================
     * INQUIRY
     * =========================
     */
    public function notifyNewInquiry(ProductInquiry $inquiry, $sendEmail = true)
    {
        $productTitle = $inquiry->product?->product_title ?? 'N/A';

        // Admin notification
        $this->createNotification([
            'type' => 'inquiry',
            'subtype' => 'new_inquiry',
            'title' => 'Penawaran Baru',
            'message' => "Penawaran baru dari {$inquiry->name} untuk produk {$productTitle}",
            'data' => [
                'inquiry_id' => $inquiry->id,
                'name' => $inquiry->name,
                'email' => $inquiry->email,
                'product_title' => $productTitle,
                'status' => $inquiry->status,
            ],
            'role' => 'admin',
            'related_inquiry_id' => $inquiry->id,
        ], $sendEmail);

        // User notification - cari user berdasarkan email
        if ($inquiry->email) {
            $user = User::where('email', $inquiry->email)->first();
            if ($user) {
                $this->createNotification([
                    'type' => 'inquiry',
                    'subtype' => 'inquiry_created',
                    'title' => 'Penawaran Anda Diterima! ✅',
                    'message' => "Penawaran Anda untuk produk {$productTitle} telah diterima dan sedang ditinjau oleh admin. Kami akan menghubungi Anda segera.",
                    'data' => [
                        'inquiry_id' => $inquiry->id,
                        'product_title' => $productTitle,
                        'status' => $inquiry->status,
                        'tracking_code' => $inquiry->tracking_code,
                    ],
                    'user_id' => $user->id,
                    'related_inquiry_id' => $inquiry->id,
                ], false);
            } else {
                // Log jika user tidak ditemukan
                Log::info('Cannot send inquiry created notification to user: User not found', [
                    'inquiry_id' => $inquiry->id,
                    'email' => $inquiry->email,
                ]);
            }
        }
    }

    public function notifyInquiryForwardedToTeknisi(ProductInquiry $inquiry, $teknisiId = null)
    {
        $productTitle = $inquiry->product?->product_title ?? 'N/A';

        if ($teknisiId) {
            $this->createNotification([
                'type' => 'inquiry',
                'subtype' => 'inquiry_forwarded_teknisi',
                'title' => 'Penawaran Diteruskan ke Anda',
                'message' => "Penawaran dari {$inquiry->name} untuk produk {$productTitle} telah diteruskan ke Anda untuk estimasi",
                'data' => [
                    'inquiry_id' => $inquiry->id,
                    'name' => $inquiry->name,
                    'product_title' => $productTitle,
                ],
                'user_id' => $teknisiId,
                'related_inquiry_id' => $inquiry->id,
            ], false);
        } else {
            $teknisiUsers = User::where('user_type', 'teknisi')->get();
            foreach ($teknisiUsers as $teknisi) {
                $this->createNotification([
                    'type' => 'inquiry',
                    'subtype' => 'inquiry_forwarded_teknisi',
                    'title' => 'Penawaran Diteruskan ke Anda',
                    'message' => "Penawaran dari {$inquiry->name} untuk produk {$productTitle} telah diteruskan ke Anda untuk estimasi",
                    'data' => [
                        'inquiry_id' => $inquiry->id,
                        'name' => $inquiry->name,
                        'product_title' => $productTitle,
                    ],
                    'user_id' => $teknisi->id,
                    'related_inquiry_id' => $inquiry->id,
                ], false);
            }
        }
    }

    public function notifyInquiryForwardedToSupervisor(ProductInquiry $inquiry)
    {
        $productTitle = $inquiry->product?->product_title ?? 'N/A';

        $this->createNotification([
            'type' => 'inquiry',
            'subtype' => 'inquiry_forwarded_supervisor',
            'title' => 'Penawaran Perlu Review',
            'message' => "Penawaran dari {$inquiry->name} untuk produk {$productTitle} memerlukan review dan penentuan koridor harga",
            'data' => [
                'inquiry_id' => $inquiry->id,
                'name' => $inquiry->name,
                'product_title' => $productTitle,
            ],
            'role' => 'supervisor',
            'related_inquiry_id' => $inquiry->id,
        ], false);
    }

    public function notifyFinalOfferSent(ProductInquiry $inquiry)
    {
        $productTitle = $inquiry->product?->product_title ?? 'N/A';
        $user = User::where('email', $inquiry->email)->first();

        if ($user) {
            $finalPrice = $inquiry->final_offer_price ?? 0;
            $validityDate = $inquiry->validity_until ? $inquiry->validity_until->format('d/m/Y') : 'Tidak ditentukan';
            $leadTime = $inquiry->lead_time_days ? $inquiry->lead_time_days . ' hari' : 'Tidak ditentukan';
            
            // Buat pesan yang lebih informatif
            $message = "Penawaran harga final untuk produk {$productTitle} telah dikirim.\n";
            $message .= "Harga: Rp " . number_format($finalPrice, 0, ',', '.') . "\n";
            $message .= "Berlaku hingga: {$validityDate}\n";
            $message .= "Waktu pengerjaan: {$leadTime}";
            
            $this->createNotification([
                'type' => 'inquiry',
                'subtype' => 'final_offer_sent',
                'title' => 'Penawaran Harga Final! 🎯',
                'message' => $message,
                'data' => [
                    'inquiry_id' => $inquiry->id,
                    'product_title' => $productTitle,
                    'final_price' => $finalPrice,
                    'final_offer_price' => $finalPrice,
                    'status' => 'approved',
                    'admin_replied_at' => $inquiry->admin_replied_at?->toISOString(),
                    'validity_until' => $inquiry->validity_until?->toISOString(),
                    'lead_time_days' => $inquiry->lead_time_days,
                ],
                'user_id' => $user->id,
                'related_inquiry_id' => $inquiry->id,
            ], false);
        } else {
            // Log jika user tidak ditemukan
            Log::warning('Cannot send final offer notification: User not found', [
                'inquiry_id' => $inquiry->id,
                'email' => $inquiry->email,
            ]);
        }
    }

    public function notifySupervisorPriceCorridorSet(ProductInquiry $inquiry)
    {
        $productTitle = $inquiry->product?->product_title ?? 'N/A';

        // Admin
        $this->createNotification([
            'type' => 'inquiry',
            'subtype' => 'supervisor_price_corridor_set',
            'title' => 'Koridor Harga Diset Supervisor',
            'message' => "Supervisor telah menetapkan koridor harga untuk penawaran produk {$productTitle}",
            'data' => [
                'inquiry_id' => $inquiry->id,
                'product_title' => $productTitle,
                'floor_price' => $inquiry->supervisor_floor_price,
                'target_price' => $inquiry->supervisor_target_price,
                'ceiling_price' => $inquiry->supervisor_ceiling_price,
                'validity_until' => $inquiry->validity_until,
            ],
            'role' => 'admin',
            'related_inquiry_id' => $inquiry->id,
        ], true);
    }

    public function notifyInquiryStatusChanged(ProductInquiry $inquiry, $oldStatus, $newStatus)
    {
        $productTitle = $inquiry->product?->product_title ?? 'N/A';
        $statusLabels = [
            'menunggu' => 'Menunggu',
            'teknisi_review' => 'Review Teknisi',
            'supervisor_review' => 'Review Supervisor',
            'sent_to_admin' => 'Dikirim ke Admin',
            'approved' => 'Disetujui',
            'rejected' => 'Ditolak',
            'customer_accepted' => 'Diterima Customer',
        ];

        // User (jika user terdaftar)
        $user = User::where('email', $inquiry->email)->first();
        if ($user) {
            $this->createNotification([
                'type' => 'inquiry',
                'subtype' => 'inquiry_status_changed',
                'title' => 'Status Penawaran Diubah',
                'message' => "Status penawaran untuk produk {$productTitle} telah diubah menjadi: " . ($statusLabels[$newStatus] ?? ucfirst($newStatus)),
                'data' => [
                    'inquiry_id' => $inquiry->id,
                    'product_title' => $productTitle,
                    'old_status' => $oldStatus,
                    'new_status' => $newStatus,
                ],
                'user_id' => $user->id,
                'related_inquiry_id' => $inquiry->id,
            ], false);
        }
    }

    public function notifyCustomerAcceptedFinalOffer(ProductInquiry $inquiry)
    {
        $productTitle = $inquiry->product?->product_title ?? 'N/A';
        $finalPrice = $inquiry->final_offer_price ?? 0;

        // Admin
        $this->createNotification([
            'type' => 'inquiry',
            'subtype' => 'customer_accepted_final_offer',
            'title' => 'Customer Menyetujui Penawaran! ✅',
            'message' => "Customer {$inquiry->name} telah menyetujui penawaran harga final untuk produk {$productTitle}. Harga: Rp " . number_format($finalPrice, 0, ',', '.'),
            'data' => [
                'inquiry_id' => $inquiry->id,
                'product_title' => $productTitle,
                'customer_name' => $inquiry->name,
                'customer_email' => $inquiry->email,
                'final_price' => $finalPrice,
                'tracking_code' => $inquiry->tracking_code,
                'status' => 'customer_accepted',
            ],
            'role' => 'admin',
            'related_inquiry_id' => $inquiry->id,
        ], true); // Kirim email juga ke admin
    }

    public function notifyInquiryConvertedToOrder(ProductInquiry $inquiry, Order $order)
    {
        $productTitle = $inquiry->product?->product_title ?? 'N/A';

        // Admin
        $this->createNotification([
            'type' => 'inquiry',
            'subtype' => 'inquiry_converted_to_order',
            'title' => 'Penawaran Diubah Menjadi Pesanan',
            'message' => "Penawaran untuk produk {$productTitle} telah diubah menjadi pesanan #{$order->id}",
            'data' => [
                'inquiry_id' => $inquiry->id,
                'order_id' => $order->id,
                'product_title' => $productTitle,
                'customer_name' => $order->customer_name,
            ],
            'role' => 'admin',
            'related_inquiry_id' => $inquiry->id,
            'related_order_id' => $order->id,
        ], false);

        // User
        if ($order->user_id) {
            $this->createNotification([
                'type' => 'inquiry',
                'subtype' => 'inquiry_converted_to_order',
                'title' => 'Penawaran Anda Menjadi Pesanan',
                'message' => "Penawaran Anda untuk produk {$productTitle} telah diubah menjadi pesanan #{$order->id}",
                'data' => [
                    'inquiry_id' => $inquiry->id,
                    'order_id' => $order->id,
                    'product_title' => $productTitle,
                ],
                'user_id' => $order->user_id,
                'related_inquiry_id' => $inquiry->id,
                'related_order_id' => $order->id,
            ], false);
        }
    }

    public function notifyInquiryRejected(ProductInquiry $inquiry)
    {
        $productTitle = $inquiry->product?->product_title ?? 'N/A';

        // User (jika user terdaftar)
        $user = User::where('email', $inquiry->email)->first();
        if ($user) {
            $this->createNotification([
                'type' => 'inquiry',
                'subtype' => 'inquiry_rejected',
                'title' => 'Penawaran Ditolak',
                'message' => "Penawaran Anda untuk produk {$productTitle} telah ditolak",
                'data' => [
                    'inquiry_id' => $inquiry->id,
                    'product_title' => $productTitle,
                ],
                'user_id' => $user->id,
                'related_inquiry_id' => $inquiry->id,
            ], false);
        }
    }

    public function notifyTeknisiEstimateSubmitted(ProductInquiry $inquiry)
    {
        $productTitle = $inquiry->product?->product_title ?? 'N/A';

        // Admin - Admin perlu tahu bahwa teknisi sudah selesai estimasi dan inquiry siap untuk review
        $this->createNotification([
            'type' => 'inquiry',
            'subtype' => 'teknisi_estimate_submitted',
            'title' => 'Estimasi Teknisi Siap Ditinjau',
            'message' => "Teknisi telah mengirim estimasi untuk penawaran produk {$productTitle}. Silakan review dan tentukan langkah selanjutnya.",
            'data' => [
                'inquiry_id' => $inquiry->id,
                'product_title' => $productTitle,
                'status' => $inquiry->status,
            ],
            'role' => 'admin',
            'related_inquiry_id' => $inquiry->id,
        ], true); // Kirim email juga ke admin

        // Supervisor - Supervisor juga perlu tahu jika inquiry akan dikirim ke mereka untuk set koridor harga
        $this->createNotification([
            'type' => 'inquiry',
            'subtype' => 'teknisi_estimate_submitted',
            'title' => 'Estimasi Teknisi Disubmit',
            'message' => "Teknisi telah mengirim estimasi untuk penawaran produk {$productTitle}",
            'data' => [
                'inquiry_id' => $inquiry->id,
                'product_title' => $productTitle,
            ],
            'role' => 'supervisor',
            'related_inquiry_id' => $inquiry->id,
        ], false);
    }

    /**
     * =========================
     * CONTACT
     * =========================
     */
    public function notifyNewContact(Contact $contact, $sendEmail = true)
    {
        $this->createNotification([
            'type' => 'contact',
            'subtype' => 'new_contact',
            'title' => 'Pesan Kontak Baru',
            'message' => "Pesan baru dari {$contact->nama} ({$contact->email})",
            'data' => [
                'contact_id' => $contact->id,
                'nama' => $contact->nama,
                'email' => $contact->email,
                'subject' => $contact->subject ?? 'Tidak ada subjek',
            ],
            'role' => 'admin',
            'related_contact_id' => $contact->id,
        ], $sendEmail);
    }

    public function notifyContactReplied(Contact $contact)
    {
        // User (jika user terdaftar)
        $user = User::where('email', $contact->email)->first();
        if ($user) {
            $this->createNotification([
                'type' => 'contact',
                'subtype' => 'contact_replied',
                'title' => 'Balasan Pesan Kontak',
                'message' => "Admin telah membalas pesan kontak Anda: " . ($contact->subject ?? 'Tanpa subjek'),
                'data' => [
                    'contact_id' => $contact->id,
                    'subject' => $contact->subject ?? 'Tidak ada subjek',
                ],
                'user_id' => $user->id,
                'related_contact_id' => $contact->id,
            ], false);
        }
    }

    /**
     * =========================
     * PRODUCTION
     * =========================
     */
    public function notifyProductionAssigned(Production $production, $teknisiId)
    {
        $productTitle = $production->product?->product_title ?? 'N/A';
        $customerName = $production->order?->customer_name ?? 'N/A';

        $this->createNotification([
            'type' => 'production',
            'subtype' => 'production_assigned',
            'title' => 'Produksi Ditugaskan ke Anda',
            'message' => "Produksi untuk order #{$production->order_id} telah ditugaskan ke Anda",
            'data' => [
                'production_id' => $production->id,
                'order_id' => $production->order_id,
                'product_title' => $productTitle,
                'customer_name' => $customerName,
            ],
            'user_id' => $teknisiId,
            'related_production_id' => $production->id,
        ], false);
    }

    public function notifyProductionPlanningSubmitted(Production $production)
    {
        $productTitle = $production->product?->product_title ?? 'N/A';

        $this->createNotification([
            'type' => 'production',
            'subtype' => 'planning_submitted',
            'title' => 'Planning Produksi Disubmit',
            'message' => "Planning produksi untuk order #{$production->order_id} telah disubmit dan menunggu approval",
            'data' => [
                'production_id' => $production->id,
                'order_id' => $production->order_id,
                'product_title' => $productTitle,
            ],
            'role' => 'supervisor',
            'related_production_id' => $production->id,
        ], false);
    }

    public function notifyProductionCompletionSubmitted(Production $production)
    {
        $productTitle = $production->product?->product_title ?? 'N/A';

        $this->createNotification([
            'type' => 'production',
            'subtype' => 'completion_submitted',
            'title' => 'Completion Produksi Disubmit',
            'message' => "Completion produksi untuk order #{$production->order_id} telah disubmit dan menunggu approval",
            'data' => [
                'production_id' => $production->id,
                'order_id' => $production->order_id,
                'product_title' => $productTitle,
            ],
            'role' => 'supervisor',
            'related_production_id' => $production->id,
        ], false);
    }

    public function notifyProductionCompletedAndSold(Production $production)
    {
        $productTitle = $production->product?->product_title ?? 'N/A';

        $this->createNotification([
            'type' => 'production',
            'subtype' => 'completed_and_sold',
            'title' => 'Produksi Selesai & Jadi Sale',
            'message' => "Produksi untuk order #{$production->order_id} telah selesai dan menjadi penjualan",
            'data' => [
                'production_id' => $production->id,
                'order_id' => $production->order_id,
                'product_title' => $productTitle,
            ],
            'role' => 'admin',
            'related_production_id' => $production->id,
        ], false);
    }

    public function notifyProductionRevised(Production $production)
    {
        if ($production->teknisi_id) {
            $productTitle = $production->product?->product_title ?? 'N/A';

            $this->createNotification([
                'type' => 'production',
                'subtype' => 'production_revised',
                'title' => 'Bahan/Sparepart Direvisi',
                'message' => "Bahan atau sparepart untuk produksi order #{$production->order_id} telah direvisi",
                'data' => [
                    'production_id' => $production->id,
                    'order_id' => $production->order_id,
                    'product_title' => $productTitle,
                ],
                'user_id' => $production->teknisi_id,
                'related_production_id' => $production->id,
            ], false);
        }
    }

    public function notifyPlanningApproved(Production $production)
    {
        $productTitle = $production->product?->product_title ?? 'N/A';

        // Teknisi
        if ($production->teknisi_id) {
            $this->createNotification([
                'type' => 'production',
                'subtype' => 'planning_approved',
                'title' => 'Planning Produksi Disetujui',
                'message' => "Planning produksi untuk order #{$production->order_id} telah disetujui supervisor. Anda dapat mulai produksi.",
                'data' => [
                    'production_id' => $production->id,
                    'order_id' => $production->order_id,
                    'product_title' => $productTitle,
                ],
                'user_id' => $production->teknisi_id,
                'related_production_id' => $production->id,
            ], false);
        }
    }

    public function notifyPlanningRejected(Production $production)
    {
        $productTitle = $production->product?->product_title ?? 'N/A';

        // Teknisi
        if ($production->teknisi_id) {
            $this->createNotification([
                'type' => 'production',
                'subtype' => 'planning_rejected',
                'title' => 'Planning Produksi Ditolak',
                'message' => "Planning produksi untuk order #{$production->order_id} ditolak supervisor. Silakan perbaiki dan submit ulang.",
                'data' => [
                    'production_id' => $production->id,
                    'order_id' => $production->order_id,
                    'product_title' => $productTitle,
                    'feedback' => $production->supervisor_feedback,
                ],
                'user_id' => $production->teknisi_id,
                'related_production_id' => $production->id,
            ], false);
        }
    }

    public function notifyCompletionApproved(Production $production)
    {
        $productTitle = $production->product?->product_title ?? 'N/A';

        // Teknisi
        if ($production->teknisi_id) {
            $this->createNotification([
                'type' => 'production',
                'subtype' => 'completion_approved',
                'title' => 'Completion Produksi Disetujui',
                'message' => "Completion produksi untuk order #{$production->order_id} telah disetujui supervisor.",
                'data' => [
                    'production_id' => $production->id,
                    'order_id' => $production->order_id,
                    'product_title' => $productTitle,
                ],
                'user_id' => $production->teknisi_id,
                'related_production_id' => $production->id,
            ], false);
        }

        // Admin
        $this->createNotification([
            'type' => 'production',
            'subtype' => 'completion_approved',
            'title' => 'Produksi Selesai',
            'message' => "Produksi untuk order #{$production->order_id} telah selesai dan disetujui supervisor",
            'data' => [
                'production_id' => $production->id,
                'order_id' => $production->order_id,
                'product_title' => $productTitle,
            ],
            'role' => 'admin',
            'related_production_id' => $production->id,
        ], false);
    }

    public function notifyCompletionRejected(Production $production)
    {
        $productTitle = $production->product?->product_title ?? 'N/A';

        // Teknisi
        if ($production->teknisi_id) {
            $this->createNotification([
                'type' => 'production',
                'subtype' => 'completion_rejected',
                'title' => 'Completion Produksi Ditolak',
                'message' => "Completion produksi untuk order #{$production->order_id} ditolak supervisor. Silakan perbaiki dan submit ulang.",
                'data' => [
                    'production_id' => $production->id,
                    'order_id' => $production->order_id,
                    'product_title' => $productTitle,
                    'feedback' => $production->supervisor_feedback,
                ],
                'user_id' => $production->teknisi_id,
                'related_production_id' => $production->id,
            ], false);
        }
    }

    public function notifyProductionStarted(Production $production)
    {
        $productTitle = $production->product?->product_title ?? 'N/A';

        // Admin
        $this->createNotification([
            'type' => 'production',
            'subtype' => 'production_started',
            'title' => 'Produksi Dimulai',
            'message' => "Produksi untuk order #{$production->order_id} telah dimulai oleh teknisi",
            'data' => [
                'production_id' => $production->id,
                'order_id' => $production->order_id,
                'product_title' => $productTitle,
            ],
            'role' => 'admin',
            'related_production_id' => $production->id,
        ], false);

        // Supervisor
        $this->createNotification([
            'type' => 'production',
            'subtype' => 'production_started',
            'title' => 'Produksi Dimulai',
            'message' => "Produksi untuk order #{$production->order_id} telah dimulai oleh teknisi",
            'data' => [
                'production_id' => $production->id,
                'order_id' => $production->order_id,
                'product_title' => $productTitle,
            ],
            'role' => 'supervisor',
            'related_production_id' => $production->id,
        ], false);
    }

    public function notifyMaterialsReceived(Production $production)
    {
        $productTitle = $production->product?->product_title ?? 'N/A';

        // Admin
        $this->createNotification([
            'type' => 'production',
            'subtype' => 'materials_received',
            'title' => 'Bahan Diterima Teknisi',
            'message' => "Bahan untuk produksi order #{$production->order_id} telah dikonfirmasi diterima oleh teknisi",
            'data' => [
                'production_id' => $production->id,
                'order_id' => $production->order_id,
                'product_title' => $productTitle,
            ],
            'role' => 'admin',
            'related_production_id' => $production->id,
        ], false);
    }

    public function notifySparepartsReceived(Production $production)
    {
        $productTitle = $production->product?->product_title ?? 'N/A';

        // Admin
        $this->createNotification([
            'type' => 'production',
            'subtype' => 'spareparts_received',
            'title' => 'Spareparts Diterima Teknisi',
            'message' => "Spareparts untuk produksi order #{$production->order_id} telah dikonfirmasi diterima oleh teknisi",
            'data' => [
                'production_id' => $production->id,
                'order_id' => $production->order_id,
                'product_title' => $productTitle,
            ],
            'role' => 'admin',
            'related_production_id' => $production->id,
        ], false);
    }

    public function notifyItemRequestSubmitted(Production $production, $itemType = 'material')
    {
        $productTitle = $production->product?->product_title ?? 'N/A';
        $itemLabel = $itemType === 'material' ? 'Bahan' : 'Sparepart';

        // Admin
        $this->createNotification([
            'type' => 'production',
            'subtype' => 'item_request_submitted',
            'title' => 'Request ' . $itemLabel . ' Tambahan',
            'message' => "Teknisi meminta {$itemLabel} tambahan untuk produksi order #{$production->order_id}",
            'data' => [
                'production_id' => $production->id,
                'order_id' => $production->order_id,
                'product_title' => $productTitle,
                'item_type' => $itemType,
            ],
            'role' => 'admin',
            'related_production_id' => $production->id,
        ], false);
    }

    public function notifyItemRequestApproved(Production $production, $teknisiId, $itemType = 'material')
    {
        $productTitle = $production->product?->product_title ?? 'N/A';
        $itemLabel = $itemType === 'material' ? 'Bahan' : 'Sparepart';

        // Teknisi
        $this->createNotification([
            'type' => 'production',
            'subtype' => 'item_request_approved',
            'title' => 'Request ' . $itemLabel . ' Disetujui',
            'message' => "Request {$itemLabel} tambahan untuk produksi order #{$production->order_id} telah disetujui admin",
            'data' => [
                'production_id' => $production->id,
                'order_id' => $production->order_id,
                'product_title' => $productTitle,
                'item_type' => $itemType,
            ],
            'user_id' => $teknisiId,
            'related_production_id' => $production->id,
        ], false);
    }

    public function notifyItemRequestRejected(Production $production, $teknisiId, $itemType = 'material')
    {
        $productTitle = $production->product?->product_title ?? 'N/A';
        $itemLabel = $itemType === 'material' ? 'Bahan' : 'Sparepart';

        // Teknisi
        $this->createNotification([
            'type' => 'production',
            'subtype' => 'item_request_rejected',
            'title' => 'Request ' . $itemLabel . ' Ditolak',
            'message' => "Request {$itemLabel} tambahan untuk produksi order #{$production->order_id} ditolak admin",
            'data' => [
                'production_id' => $production->id,
                'order_id' => $production->order_id,
                'product_title' => $productTitle,
                'item_type' => $itemType,
            ],
            'user_id' => $teknisiId,
            'related_production_id' => $production->id,
        ], false);
    }

    /**
     * =========================
     * HANDOVER
     * =========================
     */
    public function notifyHandoverReady(Order $order)
    {
        $productTitle = $order->product?->product_title ?? 'N/A';

        // User
        if ($order->user_id) {
            $this->createNotification([
                'type' => 'order',
                'subtype' => 'handover_ready',
                'title' => 'Produk Siap Diserahkan',
                'message' => "Produk pesanan #{$order->id} ({$productTitle}) sudah siap untuk diserahkan",
                'data' => [
                    'order_id' => $order->id,
                    'product_title' => $productTitle,
                ],
                'user_id' => $order->user_id,
                'related_order_id' => $order->id,
            ], false);
        }

        // Teknisi - Notifikasi bahwa produk yang dibuatnya sudah siap diserahkan
        if ($order->production && $order->production->teknisi_id) {
            $this->createNotification([
                'type' => 'production',
                'subtype' => 'handover_ready',
                'title' => 'Produk Siap Diserahkan',
                'message' => "Produk yang Anda buat untuk order #{$order->id} ({$productTitle}) sudah siap untuk diserahkan ke customer",
                'data' => [
                    'order_id' => $order->id,
                    'production_id' => $order->production->id,
                    'product_title' => $productTitle,
                    'customer_name' => $order->customer_name,
                ],
                'user_id' => $order->production->teknisi_id,
                'related_production_id' => $order->production->id,
            ], false);
        }
    }

    public function notifyHandoverDelivered(Order $order)
    {
        $productTitle = $order->product?->product_title ?? 'N/A';
        $confirmationLink = route('user.orders.confirm-delivery', $order);

        // User - Create notification
        if ($order->user_id) {
            $this->createNotification([
                'type' => 'order',
                'subtype' => 'handover_delivered',
                'title' => 'Produk Telah Diserahkan',
                'message' => "Produk pesanan #{$order->id} ({$productTitle}) telah diserahkan. Silakan konfirmasi penerimaan melalui link yang telah dikirim ke email Anda.",
                'data' => [
                    'order_id' => $order->id,
                    'product_title' => $productTitle,
                    'confirmation_link' => $confirmationLink,
                ],
                'user_id' => $order->user_id,
                'related_order_id' => $order->id,
            ], false);
        }

        // Teknisi - Notifikasi bahwa produk yang dibuatnya sudah diserahkan ke customer
        if ($order->production && $order->production->teknisi_id) {
            $this->createNotification([
                'type' => 'production',
                'subtype' => 'handover_delivered',
                'title' => 'Produk Telah Diserahkan',
                'message' => "Produk yang Anda buat untuk order #{$order->id} ({$productTitle}) telah diserahkan ke customer. Menunggu konfirmasi customer.",
                'data' => [
                    'order_id' => $order->id,
                    'production_id' => $order->production->id,
                    'product_title' => $productTitle,
                    'customer_name' => $order->customer_name,
                ],
                'user_id' => $order->production->teknisi_id,
                'related_production_id' => $order->production->id,
            ], false);
        }

        // Send email to customer (even if not registered user)
        try {
            if ($order->customer_email) {
                Mail::to($order->customer_email)->send(new \App\Mail\HandoverDeliveredEmail($order));
                Log::info('Handover delivered email sent to customer', [
                    'order_id' => $order->id,
                    'customer_email' => $order->customer_email,
                ]);
            }
        } catch (\Exception $e) {
            Log::error('Failed to send handover delivered email', [
                'order_id' => $order->id,
                'customer_email' => $order->customer_email,
                'error' => $e->getMessage(),
            ]);
        }
    }

    public function notifyHandoverConfirmed(Order $order)
    {
        $productTitle = $order->product?->product_title ?? 'N/A';

        // Admin
        $this->createNotification([
            'type' => 'order',
            'subtype' => 'handover_confirmed',
            'title' => 'Serah Terima Dikonfirmasi',
            'message' => "Serah terima untuk pesanan #{$order->id} ({$productTitle}) telah dikonfirmasi customer",
            'data' => [
                'order_id' => $order->id,
                'product_title' => $productTitle,
                'customer_name' => $order->customer_name,
            ],
            'role' => 'admin',
            'related_order_id' => $order->id,
        ], false);
    }

    /**
     * =========================
     * RECEIVABLE
     * =========================
     */
    public function notifyReceivableCreated(Receivable $receivable)
    {
        $order = $receivable->order;
        $productTitle = $order?->product?->product_title ?? 'N/A';

        // Admin
        $this->createNotification([
            'type' => 'order',
            'subtype' => 'receivable_created',
            'title' => 'Piutang Baru Dibuat',
            'message' => "Piutang baru untuk pesanan #{$order->id} ({$productTitle}) dengan total Rp " . number_format($receivable->total_amount, 0, ',', '.'),
            'data' => [
                'receivable_id' => $receivable->id,
                'order_id' => $order->id ?? null,
                'product_title' => $productTitle,
                'total_amount' => $receivable->total_amount,
                'due_date' => $receivable->due_date,
            ],
            'role' => 'admin',
            'related_order_id' => $order->id ?? null,
        ], false);

        // User
        if ($order && $order->user_id) {
            $this->createNotification([
                'type' => 'order',
                'subtype' => 'receivable_created',
                'title' => 'Piutang Dibuat',
                'message' => "Piutang untuk pesanan #{$order->id} ({$productTitle}) dengan total Rp " . number_format($receivable->total_amount, 0, ',', '.') . " jatuh tempo " . ($receivable->due_date ? $receivable->due_date->format('d/m/Y') : '-'),
                'data' => [
                    'receivable_id' => $receivable->id,
                    'order_id' => $order->id,
                    'product_title' => $productTitle,
                    'total_amount' => $receivable->total_amount,
                    'due_date' => $receivable->due_date,
                ],
                'user_id' => $order->user_id,
                'related_order_id' => $order->id,
            ], false);
        }
    }

    public function notifyReceivablePaymentReceived(Receivable $receivable, $amount)
    {
        $order = $receivable->order;
        $productTitle = $order?->product?->product_title ?? 'N/A';

        // Admin
        $this->createNotification([
            'type' => 'order',
            'subtype' => 'receivable_payment_received',
            'title' => 'Pembayaran Piutang Diterima',
            'message' => "Pembayaran sebesar Rp " . number_format($amount, 0, ',', '.') . " untuk piutang pesanan #{$order->id} ({$productTitle}) telah diterima",
            'data' => [
                'receivable_id' => $receivable->id,
                'order_id' => $order->id ?? null,
                'product_title' => $productTitle,
                'amount' => $amount,
                'remaining_amount' => $receivable->remaining_amount,
            ],
            'role' => 'admin',
            'related_order_id' => $order->id ?? null,
        ], false);

        // User
        if ($order && $order->user_id) {
            $this->createNotification([
                'type' => 'order',
                'subtype' => 'receivable_payment_received',
                'title' => 'Pembayaran Piutang Diterima',
                'message' => "Pembayaran sebesar Rp " . number_format($amount, 0, ',', '.') . " untuk piutang pesanan #{$order->id} telah diterima. Sisa: Rp " . number_format($receivable->remaining_amount, 0, ',', '.'),
                'data' => [
                    'receivable_id' => $receivable->id,
                    'order_id' => $order->id,
                    'product_title' => $productTitle,
                    'amount' => $amount,
                    'remaining_amount' => $receivable->remaining_amount,
                ],
                'user_id' => $order->user_id,
                'related_order_id' => $order->id,
            ], false);
        }
    }

    public function notifyReceivablePaidOff(Receivable $receivable)
    {
        $order = $receivable->order;
        $productTitle = $order?->product?->product_title ?? 'N/A';

        // Admin
        $this->createNotification([
            'type' => 'order',
            'subtype' => 'receivable_paid_off',
            'title' => 'Piutang Lunas',
            'message' => "Piutang untuk pesanan #{$order->id} ({$productTitle}) telah lunas",
            'data' => [
                'receivable_id' => $receivable->id,
                'order_id' => $order->id ?? null,
                'product_title' => $productTitle,
                'total_amount' => $receivable->total_amount,
            ],
            'role' => 'admin',
            'related_order_id' => $order->id ?? null,
        ], false);

        // User
        if ($order && $order->user_id) {
            $this->createNotification([
                'type' => 'order',
                'subtype' => 'receivable_paid_off',
                'title' => 'Piutang Lunas',
                'message' => "Piutang untuk pesanan #{$order->id} ({$productTitle}) telah lunas",
                'data' => [
                    'receivable_id' => $receivable->id,
                    'order_id' => $order->id,
                    'product_title' => $productTitle,
                ],
                'user_id' => $order->user_id,
                'related_order_id' => $order->id,
            ], false);
        }
    }

    /**
     * =========================
     * CORE
     * =========================
     */
    protected function createNotification(array $data, $sendEmail = false)
    {
        $notification = Notification::create($data);

        if ($sendEmail && in_array($data['type'], ['order', 'inquiry', 'contact'])) {
            $this->sendEmailNotification($notification);
        }

        return $notification;
    }

    protected function sendEmailNotification(Notification $notification)
    {
        try {
            $adminEmail = config('mail.admin_email', config('mail.from.address'));
            
            // Log sebelum kirim email untuk debugging
            Log::info('Sending email notification', [
                'to' => $adminEmail,
                'notification_id' => $notification->id,
                'type' => $notification->type,
                'title' => $notification->title,
            ]);
            
            // Kirim email berdasarkan type dengan Mail class yang sesuai
            switch ($notification->type) {
                case 'order':
                    if ($notification->subtype === 'new_order' && isset($notification->data['order_id'])) {
                        $order = Order::find($notification->data['order_id']);
                        if ($order) {
                            Mail::to($adminEmail)->send(new \App\Mail\NewOrderNotification($order));
                        }
                    } else {
                        // Fallback ke NotificationEmail untuk type order lainnya
                        Mail::to($adminEmail)->send(new \App\Mail\NotificationEmail($notification));
                    }
                    break;
                    
                case 'inquiry':
                    if ($notification->subtype === 'new_inquiry' && isset($notification->data['inquiry_id'])) {
                        $inquiry = ProductInquiry::find($notification->data['inquiry_id']);
                        if ($inquiry) {
                            Mail::to($adminEmail)->send(new \App\Mail\NewInquiryNotification($inquiry));
                        }
                    } else {
                        // Fallback ke NotificationEmail untuk type inquiry lainnya
                        Mail::to($adminEmail)->send(new \App\Mail\NotificationEmail($notification));
                    }
                    break;
                    
                case 'contact':
                    if ($notification->subtype === 'new_contact' && isset($notification->data['contact_id'])) {
                        $contact = Contact::find($notification->data['contact_id']);
                        if ($contact) {
                            Mail::to($adminEmail)->send(new \App\Mail\NewContactNotification($contact));
                        }
                    } else {
                        // Fallback ke NotificationEmail untuk type contact lainnya
                        Mail::to($adminEmail)->send(new \App\Mail\NotificationEmail($notification));
                    }
                    break;
                    
                default:
                    // Default menggunakan NotificationEmail
                    Mail::to($adminEmail)->send(new \App\Mail\NotificationEmail($notification));
                    break;
            }
            
            $notification->markEmailSent();
            
            Log::info('Email notification sent successfully', [
                'notification_id' => $notification->id,
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to send email notification', [
                'notification_id' => $notification->id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
        }
    }
}
