<?php

namespace App\Http\Controllers;

use App\Models\ProductInquiry;
use App\Services\NotificationService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;

class GuestInquiryController extends Controller
{
    public function index()
    {
        return view('guest.inquiry.index');
    }
    
    public function show(ProductInquiry $inquiry)
    {
        return view('guest.inquiry.show', compact('inquiry'));
    }
    
    public function track($trackingCode)
    {
        $inquiry = ProductInquiry::where('tracking_code', $trackingCode)->firstOrFail();
        return view('guest.inquiry.track', compact('inquiry'));
    }

    /**
     * Customer accepts final offer
     */
    public function accept(ProductInquiry $inquiry)
    {
        // Validasi: Final offer must exist
        if (is_null($inquiry->final_offer_price)) {
            return back()->with('error', 'Belum ada harga final dari admin.');
        }
        
        // Validasi: Jangan bisa setujui jika sudah di-convert ke order
        if ($inquiry->status === 'converted_to_order' || !is_null($inquiry->order_id)) {
            return back()->with('error', 'Penawaran ini sudah diubah menjadi pesanan. Silakan cek menu "Pesanan Saya" untuk melihat detail pesanan.');
        }
        
        // Validasi: Jangan bisa setujui jika sudah pernah disetujui
        if ($inquiry->status === 'customer_accepted') {
            return back()->with('info', 'Penawaran ini sudah Anda setujui sebelumnya. Admin akan segera menindaklanjuti.');
        }
        
        $oldStatus = $inquiry->status;
        $inquiry->update(['status' => 'customer_accepted', 'is_read' => false]);
        
        // Kirim notifikasi ke admin
        try {
            $notificationService = new NotificationService();
            $notificationService->notifyCustomerAcceptedFinalOffer($inquiry->fresh());
            $notificationService->notifyInquiryStatusChanged($inquiry->fresh(), $oldStatus, 'customer_accepted');
        } catch (\Exception $e) {
            Log::error('Failed to send customer accepted notification: ' . $e->getMessage());
        }
        
        // Notifikasi admin via email (backup)
        try {
            Mail::send('emails.customer-accept', [ 'inquiry' => $inquiry ], function ($mail) use ($inquiry) {
                $mail->to(config('mail.from.address'), 'Admin')
                    ->subject('Customer Menyetujui Penawaran - ' . ($inquiry->product->product_title ?? 'Produk'))
                    ->from(config('mail.from.address'), config('mail.from.name'));
            });
        } catch (\Exception $e) {
            Log::error('Failed to send customer accepted email: ' . $e->getMessage());
        }
        
        return back()->with('success', 'Terima kasih! Penawaran telah Anda setujui. Admin akan segera menindaklanjuti.');
    }

    /**
     * Customer counters within allowed range
     */
    public function counter(Request $request, ProductInquiry $inquiry)
    {
        $request->validate([
            'counter_price' => 'required|numeric|min:0',
        ]);

        $price = (float)$request->counter_price;
        if (!is_null($inquiry->supervisor_floor_price) && $price < $inquiry->supervisor_floor_price) {
            return back()->with('error', 'Nominal di bawah batas minimal.');
        }
        if (!is_null($inquiry->supervisor_ceiling_price) && $price > $inquiry->supervisor_ceiling_price) {
            return back()->with('error', 'Nominal di atas batas maksimal.');
        }

        $inquiry->update([
            'customer_bid_price' => $price,
            'status' => 'customer_counter',
            'is_read' => false,
        ]);
        // Notifikasi admin via email
        try {
            Mail::send('emails.customer-counter', [ 'inquiry' => $inquiry ], function ($mail) use ($inquiry) {
                $mail->to(config('mail.from.address'), 'Admin')
                    ->subject('Customer Counter Offer - ' . ($inquiry->product->product_title ?? 'Produk'))
                    ->from(config('mail.from.address'), config('mail.from.name'));
            });
        } catch (\Exception $e) { }

        return back()->with('success', 'Terima kasih! Penawaran balik Anda sudah dikirim. Admin akan mengonfirmasi.');
    }
}
