<?php

namespace App\Http\Controllers\Buyer;

use App\Http\Controllers\Controller;
use App\Models\Quote;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Services\EmailService;

class QuoteController extends Controller
{
    public function index()
    {
        $quotes = Quote::whereHas('rfq', function($q) {
            $q->where('buyer_id', Auth::user()->buyer->id);
        })->with(['rfq', 'seller', 'seller.user'])->latest()->paginate(10);

        $buyer = Auth::user()->buyer;
        $stats = [
            'total' => \App\Models\Quote::whereHas('rfq', fn($q) => $q->where('buyer_id', $buyer->id))->count(),
            'pending' => \App\Models\Quote::whereHas('rfq', fn($q) => $q->where('buyer_id', $buyer->id))->whereIn('status', ['pending', 'viewed'])->count(),
            'accepted' => \App\Models\Quote::whereHas('rfq', fn($q) => $q->where('buyer_id', $buyer->id))->where('status', 'accepted')->count(),
            'rejected' => \App\Models\Quote::whereHas('rfq', fn($q) => $q->where('buyer_id', $buyer->id))->where('status', 'rejected')->count(),
        ];

        return view('buyer.quotes.index', compact('quotes', 'stats'));
    }

    public function updateStatus(Request $request, Quote $quote)
    {
        // Ensure the quote belongs to an RFQ owned by this buyer
        if ($quote->rfq->buyer_id !== Auth::user()->buyer->id) {
            abort(403);
        }

        $request->validate([
            'status' => 'required|in:accepted,rejected',
        ]);

        $quote->update(['status' => $request->status]);

        // Triggers Email Events
        if ($request->status === 'accepted') {
            EmailService::send('quote-accepted', $quote->seller->user->email, [
               'product_name' => $quote->rfq->title, // Seeder expects product_name
               'buyer_name' => Auth::user()->name,   // Seeder expects buyer_name
            ]);
        } elseif ($request->status === 'rejected') {
            EmailService::send('quote-rejected', $quote->seller->user->email, [
               'product_name' => $quote->rfq->title, // Seeder expects product_name
            ]);
        }

        return redirect()->back()->with('success', 'Quote status updated successfully.');
    }
}
