<?php

namespace App\Http\Controllers\Buyer;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Favorite;
use App\Models\SavedSearch;

class BuyerController extends Controller
{
    public function dashboard()
    {
        $buyer = Auth::user()->buyer;
        $rfqCount = $buyer->rfqs()->count();
        $favoritesCount = $buyer->favorites()->count();
        $savedSearchesCount = $buyer->savedSearches()->count();
        $inquiriesCount = $buyer->inquiries()->count();

        // Get quotes received on buyer's RFQs
        $rfqIds = $buyer->rfqs()->pluck('id');
        $quotesReceived = \App\Models\Quote::whereIn('rfq_id', $rfqIds)->count();
        $pendingQuotes = \App\Models\Quote::whereIn('rfq_id', $rfqIds)->where('status', 'pending')->count();
        $acceptedQuotes = \App\Models\Quote::whereIn('rfq_id', $rfqIds)->where('status', 'accepted')->count();

        $recentRfqs = $buyer->rfqs()->withCount('quotes')->latest()->take(5)->get();
        $recentInquiries = $buyer->inquiries()->with(['seller', 'product'])->latest()->take(5)->get();
        
        // Recent quotes received
        $recentQuotes = \App\Models\Quote::whereIn('rfq_id', $rfqIds)
            ->with(['rfq', 'seller.user'])
            ->latest()
            ->take(5)
            ->get();

        return view('buyer.dashboard', compact(
            'buyer', 'rfqCount', 'favoritesCount', 'savedSearchesCount', 
            'inquiriesCount', 'quotesReceived', 'pendingQuotes', 'acceptedQuotes',
            'recentRfqs', 'recentInquiries', 'recentQuotes'
        ));
    }

    public function favorites()
    {
        $favorites = Auth::user()->buyer->favorites()->with(['product.seller', 'product.category'])->latest()->paginate(12);
        return view('buyer.favorites', compact('favorites'));
    }

    public function addFavorite(\App\Models\Product $product)
    {
        $buyer = Auth::user()->buyer;
        
        // Check if already favorited
        $exists = Favorite::where('buyer_id', $buyer->id)
            ->where('product_id', $product->id)
            ->exists();
            
        if ($exists) {
            return back()->with('info', 'Product is already in your favorites.');
        }
        
        Favorite::create([
            'buyer_id' => $buyer->id,
            'product_id' => $product->id,
        ]);
        
        return back()->with('success', 'Product added to favorites!');
    }

    public function removeFavorite(Favorite $favorite)
    {
        $buyer = Auth::user()->buyer;
        
        // Ensure buyer owns this favorite
        if ($favorite->buyer_id !== $buyer->id) {
            abort(403, 'Unauthorized');
        }
        
        $favorite->delete();
        
        return back()->with('success', 'Product removed from favorites.');
    }

    public function savedSearches()
    {
        $savedSearches = Auth::user()->buyer->savedSearches()->latest()->paginate(10);
        return view('buyer.saved-searches', compact('savedSearches'));
    }

    public function deleteSavedSearch(SavedSearch $savedSearch)
    {
        $buyer = Auth::user()->buyer;
        
        // Ensure buyer owns this saved search
        if ($savedSearch->buyer_id !== $buyer->id) {
            abort(403, 'Unauthorized');
        }
        
        $savedSearch->delete();
        
        return back()->with('success', 'Saved search deleted.');
    }

    public function saveSearch(Request $request)
    {
        $buyer = Auth::user()->buyer;
        
        $request->validate([
            'query' => 'required|string|max:255',
            'filters' => 'nullable|array',
        ]);
        
        // Check for duplicate
        $exists = SavedSearch::where('buyer_id', $buyer->id)
            ->where('query', $request->query('query', $request->input('query')))
            ->exists();
            
        if ($exists) {
            return back()->with('info', 'This search is already saved.');
        }
        
        SavedSearch::create([
            'buyer_id' => $buyer->id,
            'query' => $request->input('query'),
            'filters' => $request->input('filters', []),
        ]);
        
        return back()->with('success', 'Search saved successfully! Access it from your dashboard.');
    }

    public function inquiries()
    {
        $inquiries = Auth::user()->buyer->inquiries()->with('seller')->latest()->paginate(10);
        return view('buyer.inquiries.index', compact('inquiries'));
    }

    public function rfqShow($id)
    {
        $rfq = Auth::user()->buyer->rfqs()->findOrFail($id);
        // Assuming quotes relationship exists or will be added. For now just show RFQ.
        // $quotes = $rfq->quotes; 
        return view('buyer.rfqs.show', compact('rfq'));
    }

    public function profile()
    {
        $user = Auth::user();
        $buyer = $user->buyer;
        return view('buyer.profile.edit', compact('user', 'buyer'));
    }

    public function updateProfile(Request $request)
    {
        $user = Auth::user();
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255|unique:users,email,' . $user->id,
            'phone' => 'nullable|string|max:20',
            // Add buyer specific fields validation if any
        ]);

        $user->update([
            'name' => $request->name,
            'email' => $request->email,
            'phone' => $request->phone,
        ]);

        // Update buyer specific fields if any
        // $user->buyer->update([...]);

        return redirect()->route('buyer.profile')->with('success', 'Profile updated successfully.');
    }

    public function receivedQuotes()
    {
        $buyer = Auth::user()->buyer;
        
        // Get all quotes on buyer's RFQs
        $quotes = \App\Models\Quote::whereHas('rfq', function($q) use ($buyer) {
            $q->where('buyer_id', $buyer->id);
        })
        ->with(['rfq', 'seller.user'])
        ->latest()
        ->paginate(15);

        $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', [
            'quotes' => $quotes,
            'stats' => $stats
        ]);
    }

    public function quoteDetails(\App\Models\Quote $quote)
    {
        $buyer = Auth::user()->buyer;
        
        // Ensure buyer owns the RFQ
        if ($quote->rfq->buyer_id !== $buyer->id) {
            abort(403, 'Unauthorized');
        }

        // Mark as viewed if pending
        $quote->markAsViewed();

        $quote->load(['rfq', 'seller.user', 'seller']);

        return view('buyer.quotes.show', compact('quote'));
    }

    public function respondToQuote(Request $request, \App\Models\Quote $quote)
    {
        $buyer = Auth::user()->buyer;
        
        // Ensure buyer owns the RFQ
        if ($quote->rfq->buyer_id !== $buyer->id) {
            abort(403, 'Unauthorized');
        }

        $request->validate([
            'action' => 'required|in:accept,reject,negotiate',
            'response_message' => 'nullable|string|max:2000',
        ]);

        $statusMap = [
            'accept' => 'accepted',
            'reject' => 'rejected',
            'negotiate' => 'negotiation',
        ];

        $quote->update([
            'status' => $statusMap[$request->action],
            'buyer_response' => $request->response_message,
        ]);

        $messages = [
            'accept' => 'Quote accepted! The seller has been notified.',
            'reject' => 'Quote rejected.',
            'negotiate' => 'Negotiation request sent to seller.',
        ];

        // Send Email Notification
        $emailSlug = match($request->action) {
            'accept' => 'quote-accepted',
            'reject' => 'quote-rejected',
            'negotiate' => 'quote-negotiation',
            default => null,
        };

        if ($emailSlug) {
            \App\Services\EmailService::send($emailSlug, $quote->seller->user->email, [
                'seller_name' => $quote->seller->user->name,
                'buyer_name' => $buyer->user->name,
                'product_name' => $quote->rfq->title,
                'message' => $request->response_message ?? 'No message provided.',
                'link' => route('seller.quotes.show', $quote->id),
            ]);
        }

        return redirect()->back()->with('success', $messages[$request->action]);
    }
}

