<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Models\Buyer;
use App\Models\Rfq;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Spatie\Permission\Models\Role;

class PostRequirementController extends Controller
{
    public function index()
    {
        $layout = (Auth::check() && Auth::user()->hasRole('buyer')) ? 'layouts.buyer' : 'layouts.master';
        $countries = config('countries', []);
        return view('public.post-requirement', compact('layout', 'countries'));
    }

    public function store(Request $request)
    {
        // Get platform MOQ settings
        $minMoq = (int) \App\Models\Setting::getValue('min_moq', 10);
        $maxMoq = (int) \App\Models\Setting::getValue('max_moq', 150);

        $request->validate([
            'product_name' => 'required|string|max:255',
            'mobile' => 'required|string|max:20',
            'delivery_location' => 'required|string|max:255',
            'country' => 'nullable|string|max:255',
        ]);

        $user = null;

        if (Auth::check()) {
            $user = Auth::user();
        } else {
            // Check if user exists by PHONE (since we removed email)
            // Assuming 'phone' column exists on users table as verified
            $user = User::where('phone', $request->mobile)->first();

            if (!$user) {
                // Check by email as fallback if they used the placeholder pattern before? 
                // Unlikely, relying on phone.
                
                // Create new Guest User
                $password = Str::random(10);
                $placeholderEmail = $request->mobile . '@guest.miniport.com';
                
                // Check if this placeholder email exists (edge case)
                if (User::where('email', $placeholderEmail)->exists()) {
                    $user = User::where('email', $placeholderEmail)->first();
                } else {
                    $user = User::create([
                        'name' => 'Guest ' . substr($request->mobile, -4),
                        'email' => $placeholderEmail,
                        'phone' => $request->mobile,
                        'password' => Hash::make($password),
                        'role' => 'buyer',
                    ]);
    
                    // Assign role
                    $buyerRole = Role::where('name', 'buyer')->first();
                    if ($buyerRole) {
                        $user->assignRole($buyerRole);
                    }
    
                    // Create Buyer profile
                    Buyer::create([
                        'user_id' => $user->id,
                    ]);
                }
            }
        }

        // Ensure user has buyer profile
        $buyer = $user->buyer;
        if (!$buyer) {
            $buyer = Buyer::create(['user_id' => $user->id]);
        }

        // Find category (simple matching or default to first available)
        $category = \App\Models\Category::where('name', 'LIKE', '%' . $request->product_name . '%')->first();
        if (!$category) {
            $category = \App\Models\Category::first(); // Fallback to first available category
        }
        $categoryId = $category ? $category->id : null; 

        // Create RFQ with user-submitted quantity
        $rfq = Rfq::create([
            'buyer_id' => $buyer->id,
            'category_id' => $categoryId,
            'title' => $request->product_name,
            'description' => "Generated from Quick Inquiry.\nMobile: [Locked]",
            'quantity' => $request->quantity ?? 1,
            'delivery_location' => $request->delivery_location,
            'country' => $request->country,
            'status' => 'open',
        ]);

        // Route to Subscribed Sellers
        $sellers = \App\Models\Seller::where('category_id', $categoryId)
                    ->where('is_active', true)
                    ->subscribed() 
                    ->get();

        foreach ($sellers as $seller) {
            \App\Services\EmailService::send('new-rfq-notification', $seller->user->email, [
                'seller_name' => $seller->user->name,
                'product_name' => $rfq->title,
                'title' => $rfq->title,
                'location' => $rfq->delivery_location,
                'link' => route('seller.rfqs'), 
            ]);
        }

        // Notify Buyer ONLY if real email (not placeholder)
        if (!str_contains($user->email, '@guest.miniport.com')) {
            \App\Services\EmailService::send('rfq-posted-confirmation', $user->email, [
                'name' => $user->name,
                'product_name' => $rfq->title,
                'rfq_id' => $rfq->id,
            ]);
        }

        // Notify Admin
        $adminEmail = \App\Models\User::role('admin')->first()->email ?? 'admin@example.com';
        \App\Services\EmailService::send('admin-new-rfq', $adminEmail, [
            'product_name' => $rfq->title,
            'buyer_name' => $user->name . ' (' . $request->mobile . ')',
        ]);

        return redirect()->route('public.rfqs.index')->with('success', 'Your requirement has been posted successfully! We will contact you shortly.');
    }
}
