<?php

namespace App\Http\Controllers;

use App\Models\ProductInquiry;
use App\Models\User;
use App\Models\Notification;
use App\Models\Setting;
use App\Services\NotificationService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;


class ProductInquiryController extends Controller
{
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'product_id' => 'required|exists:products,id',
            'name' => 'required|string|max:255',
            'email' => 'required|email',
            'phone' => 'required|string|max:20',
            'message' => 'required|string',
        ]);

        if (        $validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first(),
            ], 422);
        }

        // Generate tracking code yang unik menggunakan kombinasi timestamp + microsecond + random
        // Kemudian update dengan ID-based tracking code setelah create untuk konsistensi
        $maxRetries = 10;
        $retryCount = 0;
        $inquiry = null;
        
        while ($retryCount < $maxRetries) {
            try {
                // Generate unique temporary tracking code menggunakan timestamp + microsecond + random
                // Ini memastikan unique bahkan dalam race condition
                $microtime = microtime(true);
                $random = mt_rand(1000, 9999);
                $uniqueValue = (int)(($microtime * 10000) % 1000000) + $random;
                $tempTrackingCode = 'INQ' . str_pad($uniqueValue % 1000000, 6, '0', STR_PAD_LEFT);
                
                // Create inquiry dengan temporary tracking code
                $inquiry = ProductInquiry::create([
                    'product_id' => $request->product_id,
                    'name' => $request->name,
                    'email' => $request->email,
                    'phone' => $request->phone,
                    'message' => $request->message,
                    'tracking_code' => $tempTrackingCode,
                    'is_read' => false,
                    'status' => 'pending',
                ]);
                
                // Setelah create berhasil, update tracking_code menggunakan ID yang sudah auto-increment
                // Ini lebih konsisten dan mudah di-track, serta pasti unique karena ID unique
                $finalTrackingCode = 'INQ' . str_pad($inquiry->id, 6, '0', STR_PAD_LEFT);
                
                // Cek apakah final tracking code sudah ada (safety check)
                $finalExists = ProductInquiry::where('tracking_code', $finalTrackingCode)
                    ->where('id', '!=', $inquiry->id)
                    ->exists();
                
                if (!$finalExists) {
                    $inquiry->update(['tracking_code' => $finalTrackingCode]);
                }
                // Jika sudah ada (sangat jarang), tetap gunakan temp tracking code
                
                break; // Berhasil, keluar dari loop
                
            } catch (\Illuminate\Database\QueryException $e) {
                // Jika error karena duplicate entry, coba lagi
                if ($e->getCode() == 23000 && strpos($e->getMessage(), 'Duplicate entry') !== false) {
                    $retryCount++;
                    if ($retryCount >= $maxRetries) {
                        Log::error('Failed to generate unique tracking code after ' . $maxRetries . ' retries');
                        return response()->json([
                            'success' => false,
                            'message' => 'Gagal membuat kode pelacakan unik. Silakan coba lagi.',
                        ], 500);
                    }
                    // Tunggu sebentar sebelum retry (exponential backoff)
                    usleep(100000 * $retryCount); // 100ms, 200ms, 300ms, etc.
                } else {
                    // Error lain, log dan return error
                    Log::error('Error creating product inquiry: ' . $e->getMessage());
                    return response()->json([
                        'success' => false,
                        'message' => 'Gagal membuat penawaran: ' . $e->getMessage(),
                    ], 500);
                }
            } catch (\Exception $e) {
                Log::error('Error creating product inquiry: ' . $e->getMessage());
                return response()->json([
                    'success' => false,
                    'message' => 'Gagal membuat penawaran. Silakan coba lagi.',
                ], 500);
            }
        }

        if (!$inquiry) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal membuat penawaran. Silakan coba lagi.',
            ], 500);
        }

        // Kirim notifikasi untuk penawaran baru
        try {
            $notificationService = new NotificationService();
            $notificationService->notifyNewInquiry($inquiry, true);
        } catch (\Exception $e) {
            Log::error('Failed to send inquiry notification: ' . $e->getMessage());
        }

        return response()->json([
            'success' => true,
            'message' => 'Pesan berhasil dikirim! Admin akan segera merespons.',
            'tracking_code' => $inquiry->tracking_code,
            'tracking_url' => route('guest.inquiry.track', $inquiry->tracking_code),
        ]);
    }

    public function index(Request $request)
    {
        $query = ProductInquiry::with('product');

        // Search functionality - perbaiki dengan grouping yang benar
        if ($request->filled('search') && trim($request->search) !== '') {
            $searchTerm = trim($request->search);
            $query->where(function($q) use ($searchTerm) {
                // Cek apakah search adalah ID numerik
                if (is_numeric($searchTerm)) {
                    $q->where('id', $searchTerm)
                      ->orWhere('tracking_code', 'like', "%{$searchTerm}%");
                }
                // Pencarian teks biasa
                $q->orWhere('name', 'like', "%{$searchTerm}%")
                  ->orWhere('email', 'like', "%{$searchTerm}%")
                  ->orWhere('phone', 'like', "%{$searchTerm}%")
                  ->orWhere('message', 'like', "%{$searchTerm}%")
                  ->orWhere('tracking_code', 'like', "%{$searchTerm}%")
                  ->orWhereHas('product', function($productQuery) use ($searchTerm) {
                      $productQuery->where('product_title', 'like', "%{$searchTerm}%");
                  });
            });
        }

        // Filter by read/unread (UI status)
        if ($request->has('status') && !empty($request->status)) {
            if ($request->status === 'unread') {
                $query->where('is_read', false);
            } elseif ($request->status === 'read') {
                $query->where('is_read', true);
            }
        }

        // Filter by business state (workflow status)
        if ($request->filled('state')) {
            $query->where('status', $request->state);
        }

        // Urutkan unread (is_read = false) di atas terlebih dahulu, lalu latest created_at
        $itemsPerPage = (int) Setting::get('items_per_page', 10);
        $inquiries = $query->orderBy('is_read', 'asc') // false (0) di atas
            ->orderBy('created_at', 'desc')
            ->paginate($itemsPerPage)
            ->withQueryString();

        // Statistik
        $totalInquiries = ProductInquiry::count();
        $unreadCount = ProductInquiry::where('is_read', false)->count();
        $readCount = ProductInquiry::where('is_read', true)->count();
        $followUpCount = ProductInquiry::whereNotNull('admin_reply')
            ->where('is_read', false)
            ->count();
            
        return view('admin.product-inquiries.index', compact('inquiries', 'totalInquiries', 'unreadCount', 'readCount', 'followUpCount'));
    }

    public function markAsRead($id)
    {
        try {
            $inquiry = ProductInquiry::findOrFail($id);
            $inquiry->update(['is_read' => true]);
            
            // Update notifikasi terkait untuk admin (role = admin dan related_inquiry_id = inquiry id)
            Notification::where(function($q) {
                $q->where(function($subQ) {
                    // Notifikasi untuk semua admin (role = admin dan user_id = null)
                    $subQ->where('role', 'admin')
                        ->whereNull('user_id');
                })
                ->orWhere(function($subQ) {
                    // Notifikasi untuk user yang sedang login (jika ada)
                    $subQ->where('user_id', auth()->id());
                });
            })
            ->where('related_inquiry_id', $id)
            ->where('is_read', false)
            ->update(['is_read' => true, 'read_at' => now()]);

            if (request()->ajax() || request()->wantsJson()) {
                return response()->json([
                    'success' => true,
                    'message' => 'Pesan ditandai sebagai dibaca.',
                ]);
            }

            return redirect()->back()->with('success', 'Pesan sudah ditandai sebagai dibaca.');
        } catch (\Exception $e) {
            if (request()->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Error: ' . $e->getMessage(),
                ], 500);
            }
            return redirect()->back()->with('error', 'Terjadi kesalahan: ' . $e->getMessage());
        }
    }

    public function reply(Request $request, ProductInquiry $inquiry)
    {
        $validator = Validator::make($request->all(), [
            'subject' => 'required|string|max:255',
            'message' => 'required|string',
            'reply_method' => 'required|in:email,whatsapp,phone',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first(),
            ], 422);
        }

        try {
            // Update inquiry with admin reply
            $inquiry->update([
                'admin_reply' => $request->message,
                'admin_replied_at' => now(),
                'reply_method' => $request->reply_method,
                'is_read' => true,
            ]);

            // Send reply based on method
            if ($request->reply_method === 'email') {
                // Kirim email reply
                // Gunakan 'reply_message' untuk menghindari konflik dengan variabel $message dari Laravel Mail
                Mail::send('emails.product-inquiry-reply', [
                    'inquiry' => $inquiry,
                    'subject' => $request->subject,
                    'reply_message' => $request->message,
                ], function ($mailMessage) use ($inquiry, $request) {
                    $mailMessage->to($inquiry->email, $inquiry->name)
                         ->subject('Re: ' . $request->subject)
                         ->from(config('mail.from.address'), config('mail.from.name'));
                });
            } elseif ($request->reply_method === 'whatsapp') {
                // Generate WhatsApp link
                $whatsappMessage = urlencode("Halo {$inquiry->name},\n\nTerima kasih atas minat Anda pada produk kami.\n\n{$request->message}\n\nTerima kasih,\nAdmin POLJAM TECH");
                $whatsappLink = "https://wa.me/{$inquiry->phone}?text={$whatsappMessage}";
                
                return response()->json([
                    'success' => true,
                    'message' => 'Reply berhasil disimpan! Klik link WhatsApp untuk mengirim pesan.',
                    'whatsapp_link' => $whatsappLink,
                ]);
            } elseif ($request->reply_method === 'phone') {
                // Generate phone link
                $phoneLink = "tel:{$inquiry->phone}";
                
                return response()->json([
                    'success' => true,
                    'message' => 'Reply berhasil disimpan! Klik link untuk menelepon.',
                    'phone_link' => $phoneLink,
                ]);
            }

            return response()->json([
                'success' => true,
                'message' => 'Reply email berhasil dikirim!',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengirim reply: ' . $e->getMessage(),
            ], 500);
        }
    }

    public function followUp(Request $request, ProductInquiry $inquiry)
    {
        $validator = Validator::make($request->all(), [
            'subject' => 'required|string|max:255',
            'message' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first(),
            ], 422);
        }

        try {
            // Kirim email follow-up
            // Gunakan 'followup_message' untuk menghindari konflik dengan variabel $message dari Laravel Mail
            Mail::send('emails.product-inquiry-followup', [
                'inquiry' => $inquiry,
                'subject' => $request->subject,
                'followup_message' => $request->message,
            ], function ($mailMessage) use ($inquiry, $request) {
                $mailMessage->to($inquiry->email, $inquiry->name)
                     ->subject('Follow-up: ' . $request->subject)
                     ->from(config('mail.from.address'), config('mail.from.name'));
            });

            return response()->json([
                'success' => true,
                'message' => 'Follow-up email berhasil dikirim!',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengirim email: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Bulk mark as read
     */
    public function bulkMarkAsRead(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'inquiry_ids' => 'required|array',
            'inquiry_ids.*' => 'exists:product_inquiries,id',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Data tidak valid',
            ], 422);
        }

        try {
            ProductInquiry::whereIn('id', $request->inquiry_ids)
                ->update(['is_read' => true]);
            
            // Update notifikasi terkait untuk admin
            Notification::where(function($q) {
                $q->where(function($subQ) {
                    // Notifikasi untuk semua admin (role = admin dan user_id = null)
                    $subQ->where('role', 'admin')
                        ->whereNull('user_id');
                })
                ->orWhere(function($subQ) {
                    // Notifikasi untuk user yang sedang login (jika ada)
                    $subQ->where('user_id', auth()->id());
                });
            })
            ->whereIn('related_inquiry_id', $request->inquiry_ids)
            ->where('is_read', false)
            ->update(['is_read' => true, 'read_at' => now()]);

            return response()->json([
                'success' => true,
                'message' => count($request->inquiry_ids) . ' penawaran berhasil ditandai sebagai dibaca.',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal update status: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Bulk mark as unread
     */
    public function bulkMarkAsUnread(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'inquiry_ids' => 'required|array',
            'inquiry_ids.*' => 'exists:product_inquiries,id',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Data tidak valid',
            ], 422);
        }

        try {
            ProductInquiry::whereIn('id', $request->inquiry_ids)
                ->update(['is_read' => false]);

            return response()->json([
                'success' => true,
                'message' => count($request->inquiry_ids) . ' penawaran berhasil ditandai sebagai belum dibaca.',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal update status: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Delete single inquiry
     */
    public function destroy($id)
    {
        try {
            $inquiry = ProductInquiry::findOrFail($id);
            $inquiry->delete();

            if (request()->ajax() || request()->wantsJson()) {
                return response()->json([
                    'success' => true,
                    'message' => 'Penawaran berhasil dihapus.',
                ]);
            }

            return redirect()->route('admin.product-inquiries.index')
                ->with('success', 'Penawaran berhasil dihapus.');
        } catch (\Exception $e) {
            if (request()->ajax() || request()->wantsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Gagal menghapus: ' . $e->getMessage(),
                ], 500);
            }

            return redirect()->route('admin.product-inquiries.index')
                ->with('error', 'Gagal menghapus penawaran: ' . $e->getMessage());
        }
    }

    /**
     * Bulk delete
     */
    public function bulkDelete(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'inquiry_ids' => 'required|array',
            'inquiry_ids.*' => 'exists:product_inquiries,id',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Data tidak valid',
            ], 422);
        }

        try {
            ProductInquiry::whereIn('id', $request->inquiry_ids)->delete();

            return response()->json([
                'success' => true,
                'message' => count($request->inquiry_ids) . ' penawaran berhasil dihapus.',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal menghapus: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Forward ke Supervisor untuk review harga
     */
    public function forwardToSupervisor($id)
    {
        $inquiry = ProductInquiry::findOrFail($id);
        $oldStatus = $inquiry->status;
        $inquiry->update(['status' => 'supervisor_review']);
        
        // Kirim notifikasi
        try {
            $notificationService = new NotificationService();
            $notificationService->notifyInquiryForwardedToSupervisor($inquiry);
            $notificationService->notifyInquiryStatusChanged($inquiry, $oldStatus, 'supervisor_review');
        } catch (\Exception $e) {
            Log::error('Failed to send supervisor notification: ' . $e->getMessage());
        }
        
        return response()->json([
            'success' => true,
            'message' => 'Penawaran telah diteruskan ke Supervisor.',
        ]);
    }

    /**
     * Forward ke Teknisi untuk estimasi pengerjaan
     */
    public function forwardToTeknisi($id)
    {
        $inquiry = ProductInquiry::findOrFail($id);
        $oldStatus = $inquiry->status;
        // Set is_read = false agar teknisi mendapat notifikasi penawaran baru
        $inquiry->update([
            'status' => 'teknisi_review',
            'is_read' => false
        ]);
        
        // Kirim notifikasi ke semua teknisi
        try {
            $notificationService = new NotificationService();
            $notificationService->notifyInquiryForwardedToTeknisi($inquiry, null); // null = kirim ke semua teknisi
            $notificationService->notifyInquiryStatusChanged($inquiry, $oldStatus, 'teknisi_review');
        } catch (\Exception $e) {
            Log::error('Failed to send teknisi notification: ' . $e->getMessage());
        }
        
        return response()->json([
            'success' => true,
            'message' => 'Penawaran telah diteruskan ke Teknisi.',
        ]);
    }

    /**
     * Final approval dari Admin
     */
    public function finalApproval(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'final_price' => 'required|numeric|min:0',
            'notes' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first(),
            ], 422);
        }

        $inquiry = ProductInquiry::findOrFail($id);
        $oldStatus = $inquiry->status;

        // Validasi terhadap floor/ceiling supervisor jika ada
        if (!is_null($inquiry->supervisor_floor_price) && $request->final_price < $inquiry->supervisor_floor_price) {
            return response()->json([
                'success' => false,
                'message' => 'Final price di bawah floor price supervisor.',
            ], 422);
        }
        if (!is_null($inquiry->supervisor_ceiling_price) && $request->final_price > $inquiry->supervisor_ceiling_price) {
            return response()->json([
                'success' => false,
                'message' => 'Final price di atas ceiling price supervisor.',
            ], 422);
        }

        // Validasi margin minimum terhadap biaya internal
        $finalPrice = (float) $request->final_price;
        $internalCost = null;
        if (!is_null($inquiry->total_cost)) {
            $internalCost = (float) $inquiry->total_cost;
        } else {
            $materialsTotal = (float) ($inquiry->materials_total_cost ?? 0);
            $sparepartsTotal = (float) ($inquiry->spareparts_total_cost ?? 0);
            $laborTotal = (float) ($inquiry->labor_cost_total ?? $inquiry->labor_cost ?? 0);
            $internalCost = $materialsTotal + $sparepartsTotal + $laborTotal;
        }

        if ($internalCost > 0) {
            $margin = ($finalPrice - $internalCost) / $internalCost;
            $minMargin = (float) config('services.pricing_min_margin', 0.20);
            if ($margin < $minMargin) {
                return response()->json([
                    'success' => false,
                    'message' => 'Final price di bawah margin minimum ' . number_format($minMargin * 100, 0) . '% terhadap biaya internal.',
                ], 422);
            }
        }

        $inquiry->update([
            'final_offer_price' => $request->final_price,
            'final_price' => $request->final_price, // legacy usage
            'status' => 'sent_to_customer', // Kirim ke customer dulu untuk approval, bukan langsung 'approved'
            'admin_final_notes' => $request->notes,
            'admin_reply' => 'Penawaran harga final: Rp ' . number_format($request->final_price, 0, ',', '.'),
            'admin_replied_at' => now(),
        ]);

        // Kirim notifikasi final offer dan status changed
        try {
            $notificationService = new NotificationService();
            $notificationService->notifyFinalOfferSent($inquiry);
            $notificationService->notifyInquiryStatusChanged($inquiry, $oldStatus, 'sent_to_customer');
        } catch (\Exception $e) {
            Log::error('Failed to send final offer notification: ' . $e->getMessage());
        }

        // Kirim email final offer ke customer (tanpa breakdown internal)
        try {
            $previewUrl = route('admin.print.quotation.offer.preview', $inquiry);
            Mail::send('emails.quotation-final-offer', [
                'inquiry' => $inquiry,
                'previewUrl' => $previewUrl,
            ], function ($mail) use ($inquiry) {
                $mail->to($inquiry->email, $inquiry->name)
                    ->subject('Penawaran Harga Final - ' . ($inquiry->product->product_title ?? 'Produk'))
                    ->from(config('mail.from.address'), config('mail.from.name'));
            });
        } catch (\Exception $e) {
            // Biarkan lanjut walau email gagal
        }

        return response()->json([
            'success' => true,
            'message' => 'Penawaran disetujui dan dikirim ke customer.',
            'whatsapp_link' => 'https://wa.me/' . preg_replace('/\D/', '', $inquiry->phone) . '?text=' . urlencode(
                'Halo ' . $inquiry->name . ',\n\n' .
                'Penawaran harga final untuk ' . ($inquiry->product->product_title ?? 'produk') . ' adalah Rp ' . number_format($inquiry->final_offer_price, 0, ',', '.') . ".\nLihat dokumen: " . route('admin.print.quotation.offer.preview', $inquiry)
            ),
        ]);
    }

    /**
     * Convert Inquiry ke Order (Two-Stage Manual Approval)
     * Admin harus approve manual sebelum convert ke order
     */
    public function convertToOrder(Request $request, $id)
    {
        $inquiry = ProductInquiry::findOrFail($id);

        // Validasi masa berlaku penawaran: jika ada dan sudah lewat, jangan lanjut
        if (!empty($inquiry->validity_until) && \Carbon\Carbon::parse($inquiry->validity_until)->isPast()) {
            return response()->json([
                'success' => false,
                'message' => 'Penawaran sudah melewati masa berlaku. Silakan kirim penawaran ulang atau perbarui masa berlaku.',
            ], 422);
        }

        // Validasi: Hanya bisa convert jika customer sudah accept
        if ($inquiry->status !== 'customer_accepted') {
            return response()->json([
                'success' => false,
                'message' => 'Hanya inquiry dengan status customer_accepted yang bisa di-convert ke order.',
            ], 422);
        }

        // Validasi: Cek apakah sudah pernah di-convert (PREVENT DUPLICATE)
        if ($inquiry->status === 'converted_to_order' || !is_null($inquiry->order_id)) {
            return response()->json([
                'success' => false,
                'message' => 'Inquiry ini sudah pernah di-convert ke order. Order ID: #' . ($inquiry->order_id ?? 'N/A'),
            ], 422);
        }

        // Validasi: Harus ada final_offer_price
        if (is_null($inquiry->final_offer_price)) {
            return response()->json([
                'success' => false,
                'message' => 'Harga final belum ditetapkan. Silakan set final offer price terlebih dahulu.',
            ], 422);
        }

        // Validasi: Harus ada product
        if (!$inquiry->product) {
            return response()->json([
                'success' => false,
                'message' => 'Produk tidak ditemukan.',
            ], 422);
        }

        $request->validate([
            'quantity' => 'required|integer|min:1',
            'address' => 'required|string|max:500',
            'payment_method' => 'required|string|in:transfer,cod,dp,midtrans',
            'order_status' => 'required|string|in:menunggu,diterima,ditolak',
        ]);

        DB::beginTransaction();
        try {
            $quantity = $request->quantity;
            $price = $inquiry->final_offer_price; // Pakai harga final dari inquiry
            $total = $price * $quantity;

            $matchedUser = \App\Models\User::where('email', $inquiry->email)->first();
            $order = \App\Models\Order::create([
                'customer_name'     => $inquiry->name,
                'customer_email'    => $inquiry->email,
                'phone_number'      => $inquiry->phone,
                'address'           => $request->address,
                'user_id'           => $matchedUser?->id,
                'product_id'        => $inquiry->product_id,
                'quantity'          => $quantity,
                'price'             => $price,
                'total_price'       => $total,
                'payment_method'    => $request->payment_method,
                'dp_percentage'     => $request->payment_method === 'dp' ? 30.00 : null, // Default 30% untuk DP
                'status'            => in_array($request->payment_method, ['cod']) ? 'diproses' : ($request->payment_method === 'dp' ? 'menunggu' : 'menunggu'),
                'order_status'      => $request->order_status,
                'production_status' => 'menunggu',
                'is_read'           => false, // Belum dibaca admin
                'order_type'        => 'penawaran', // Tandai jenis pesanan sebagai Penawaran (hasil convert dari inquiry)
            ]);

            // Update inquiry status menjadi "converted_to_order" dan simpan order_id
            // Set is_read = true karena sudah diproses (tidak perlu notifikasi admin lagi)
            $oldInquiryStatus = $inquiry->status;
            $inquiry->update([
                'status' => 'converted_to_order',
                'order_id' => $order->id, // Link ke order
                'admin_final_notes' => ($inquiry->admin_final_notes ?? '') . "\n\n[Converted to Order #{$order->id} on " . now()->format('d M Y H:i') . ']',
                'converted_to_order_at' => now(), // Timestamp untuk notifikasi user
                'is_read' => true, // Mark as read karena sudah diproses menjadi order
            ]);

            // Kirim notifikasi inquiry converted to order
            try {
                $notificationService = new NotificationService();
                $notificationService->notifyInquiryConvertedToOrder($inquiry->fresh(), $order);
                $notificationService->notifyInquiryStatusChanged($inquiry->fresh(), $oldInquiryStatus, 'converted_to_order');
            } catch (\Exception $e) {
                Log::error('Failed to send inquiry converted notification: ' . $e->getMessage());
            }

            // Kirim email notifikasi ke customer
            try {
                Mail::send('emails.inquiry-converted-to-order', [
                    'inquiry' => $inquiry,
                    'order' => $order,
                ], function ($mail) use ($inquiry, $order) {
                    $mail->to($inquiry->email, $inquiry->name)
                        ->subject('Pesanan Anda Telah Dibuat - Order #' . $order->id)
                        ->from(config('mail.from.address'), config('mail.from.name'));
                });
            } catch (\Exception $e) {
                // Biarkan lanjut walau email gagal
                Log::error('Failed to send conversion email: ' . $e->getMessage());
            }

            // Buat produksi otomatis jika order_status diterima
            if ($request->order_status === 'diterima') {
                \App\Models\Production::firstOrCreate(
                    ['order_id' => $order->id],
                    [
                        'product_id' => $order->product_id,
                        'quantity' => $order->quantity,
                        'start_date' => now(),
                        'status' => 'menunggu', // Tetap menunggu, tidak langsung dalam_proses
                        'total_material_cost' => 0,
                        'total_sparepart_cost' => 0,
                        'total_production_cost' => 0,
                    ]
                );

                $order->updateQuietly([
                    'production_status' => 'menunggu',
                ]);
            }

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Inquiry berhasil di-convert ke Order #' . $order->id,
                'order_id' => $order->id,
                'redirect_url' => route('admin.master.orders.show', $order),
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Gagal convert ke order: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Get user address by email
     * Digunakan untuk mengambil alamat user yang sudah terdaftar di profil
     */
    public function getUserAddress(Request $request)
    {
        try {
            $email = $request->input('email');
            
            if (!$email) {
                return response()->json([
                    'success' => false,
                    'message' => 'Email tidak boleh kosong'
                ], 400);
            }

            $user = User::where('email', $email)->first();
            
            if (!$user) {
                return response()->json([
                    'success' => false,
                    'message' => 'User tidak ditemukan',
                    'address' => null
                ]);
            }

            return response()->json([
                'success' => true,
                'address' => $user->address ?? null,
                'has_address' => !empty($user->address)
            ]);
        } catch (\Exception $e) {
            Log::error('Error getting user address: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengambil alamat user: ' . $e->getMessage(),
                'address' => null
            ], 500);
        }
    }
}
