<?php

namespace App\Http\Controllers\Public;

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

class QuoteController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('role:seller');
    }

    /**
     * Store a new quote for an RFQ
     */
    public function store(Request $request, Rfq $rfq)
    {
        $seller = Auth::user()->seller;

        // Restriction: Only Paid Sellers can quote
        if (!$seller->isPaid()) {
            return redirect()->back()->with('error', 'Quote submission is available only for Premium Sellers. Please upgrade your plan to start quoting.');
        }

        $request->validate([
            'price' => 'required|numeric|min:1',
            'delivery_timeline' => 'required|string|max:100',
            'message' => 'nullable|string|max:2000',
        ]);

        $seller = Auth::user()->seller;

        // Check if already quoted
        $existingQuote = Quote::where('rfq_id', $rfq->id)
                              ->where('seller_id', $seller->id)
                              ->first();

        if ($existingQuote) {
            return redirect()->back()->with('error', 'You have already submitted a quote for this requirement.');
        }

        // Create quote
        Quote::create([
            'rfq_id' => $rfq->id,
            'seller_id' => $seller->id,
            'price' => $request->price,
            'delivery_timeline' => $request->delivery_timeline,
            'message' => $request->message,
            'status' => 'pending',
        ]);

        // Send notification to buyer
        if ($rfq->buyer && $rfq->buyer->user) {
            \App\Services\EmailService::send('quote-submitted', $rfq->buyer->user->email, [
                'buyer_name' => $rfq->buyer->user->name,
                'seller_company' => $seller->company_name,
                'rfq_title' => $rfq->title, // Assuming RFQ has a title field
                'price' => number_format($request->price, 2),
                'link' => route('buyer.quotes.index'), // Assuming a route to view quotes exists
            ]);
        }

        return redirect()->back()->with('success', 'Your quote has been submitted successfully! The buyer will review it shortly.');
    }
}
