<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Seller;
use App\Models\Buyer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class RegisterController extends Controller
{
    public function __construct()
    {
        $this->middleware('guest');
    }
    public function showSellerRegistrationForm()
    {
        $categories = \App\Models\Category::all();
        $units = \App\Models\Unit::where('is_active', true)->get();
        
        // Fetch Dynamic MOQ Settings
        $minMoq = \App\Models\Setting::getValue('registration_moq_min', 10);
        $maxMoq = \App\Models\Setting::getValue('registration_moq_max', 150);
        
        // Check for plan in URL
        $planId = request()->query('plan');
        
        return view('auth.register-seller-multistep', compact('categories', 'units', 'minMoq', 'maxMoq', 'planId'));
    }

    public function showBuyerRegistrationForm()
    {
        return view('auth.register-buyer');
    }

    public function registerSeller(Request $request)
    {
        // Fetch Dynamic MOQ Settings for Validation
        $minMoq = \App\Models\Setting::getValue('registration_moq_min', 10);
        $maxMoq = \App\Models\Setting::getValue('registration_moq_max', 150);

        $request->validate([
            // Step 1: Personal
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'mobile' => 'required|string|max:20',
            'password' => 'required|string|min:8|confirmed',
            'city' => 'nullable|string|max:255',
            'state' => 'nullable|string|max:255',
            'country' => 'nullable|string|max:255',
            
            // Step 2: Company & Product
            'company_name' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'subcategory_id' => 'nullable|exists:categories,id',
            'custom_category' => 'nullable|string|max:255',
            'business_type' => 'required|array|min:1',
            'moq_quantity' => "required|integer|between:$minMoq,$maxMoq",
            'unit' => 'required|string|max:50',
            'product_name' => 'nullable|string|max:255',
            'product_price' => 'required|numeric|min:0',
            'product_description' => 'nullable|string|max:2000',
            'address' => 'nullable|string|max:500',
            'pincode' => 'required|string|size:6',
            
            // Product Images
            'product_images' => 'required|array|min:1|max:4',
            'product_images.*' => 'image|mimes:jpeg,png,jpg,webp|max:2048',
            
            // Step 3: KYC (Mandatory: seller_photo, pan_number, pan_card_doc ONLY IF submit_kyc is checked OR Optional Docs Provided)
            'submit_kyc' => 'nullable|boolean',
            'seller_photo' => 'required_if:submit_kyc,1|required_with:gst_number,udyam_number,iec_code|image|mimes:jpeg,png,jpg,webp|max:2048',
            'pan_number' => 'required_if:submit_kyc,1|required_with:gst_number,udyam_number,iec_code|nullable|string|size:10|regex:/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/i',
            'pan_card_doc' => 'required_if:submit_kyc,1|required_with:gst_number,udyam_number,iec_code|file|mimes:pdf,jpg,png,jpeg|max:5120',
            // Optional KYC fields
            'gst_number' => 'nullable|string|max:15',
            'udyam_number' => 'nullable|string|max:25',
            'iec_code' => 'nullable|string|max:10',
            'kyc_documents' => 'nullable|array',
            'kyc_documents.*' => 'file|mimes:pdf,jpg,png,jpeg|max:5120',
            'declaration' => 'accepted',
            'plan_id' => 'nullable|exists:plans,id',
        ]);

        DB::transaction(function () use ($request, $minMoq, $maxMoq) {
            // 1. Create User
            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'password' => Hash::make($request->password),
                'role' => 'seller',
                'phone' => $request->mobile,
            ]);
            
            // Assign Spatie role for middleware compatibility
            $user->assignRole('seller');

            // 2. Handle Product Images
            $productImages = [];
            if($request->hasFile('product_images')) {
                foreach($request->file('product_images') as $image) {
                     $productImages[] = $image->store('products', 'public');
                }
            }

            // 3. Handle Mandatory KYC Files
            $sellerPhotoPath = null;
            if ($request->hasFile('seller_photo')) {
                $sellerPhotoPath = $request->file('seller_photo')->store('kyc/photos', 'public');
            }
            
            $panCardPath = null;
            if ($request->hasFile('pan_card_doc')) {
                $panCardPath = $request->file('pan_card_doc')->store('kyc/pan', 'public');
            }
            
            // Handle optional additional KYC docs
            $additionalDocs = [];
            if ($request->hasFile('kyc_documents')) {
                foreach ($request->file('kyc_documents') as $doc) {
                    $additionalDocs[] = $doc->store('kyc/documents', 'public');
                }
            }

            // 4. Create Seller
            $sellerData = [
                'user_id' => $user->id,
                'company_name' => $request->company_name,
                'category_id' => $request->category_id,
                'city' => $request->city,
                'state' => $request->state,
                'country' => $request->country ?? 'India',
                'address' => $request->address,
                'pincode' => $request->pincode,
                'business_type' => $request->business_type, 
                'moq_quantity' => $request->moq_quantity,
                'moq_range_start' => $minMoq,
                'moq_range_end' => $maxMoq,
                
                // KYC Mandatory Fields
                'photo' => $sellerPhotoPath,
                'pan_number' => $request->pan_number ? strtoupper($request->pan_number) : null,
                'pan_doc' => $panCardPath,
                'kyc_status' => $request->submit_kyc ? 'submitted' : 'pending',
                
                // KYC Optional Fields
                'gst' => strtoupper($request->gst_number),
                'udyam_number' => strtoupper($request->udyam_number),
                'iec_code' => $request->iec_code,
            ];

            $seller = Seller::create($sellerData);

            // 5. Create Initial Product
            if (!empty($productImages)) {
                \App\Models\Product::create([
                    'seller_id' => $seller->id,
                    'category_id' => $request->category_id,
                    'name' => $request->product_name ?: 'Main Product',
                    'price' => $request->product_price ?: 0,
                    'unit_id' => 1, // Default unit ID or fetch from input if we add Unit dropdown
                    'description' => $request->product_description ?: 'No description provided.',
                    'images_json' => $productImages, // Model should cast this to array
                    'slug' => \Illuminate\Support\Str::slug(($request->product_name ?: 'product') . '-' . \Illuminate\Support\Str::random(6)),
                    'status' => 'pending', // Pending approval
                    'moq' => $request->moq_quantity ?: 1, // Use user input or default to 1
                ]);
            }

            // Login
            Auth::login($user);

            // Send Welcome Email
            \App\Services\EmailService::send('seller-welcome', $user->email, [
                'name' => $user->name,
            ]);

            // Notify Admin (Optional but good practice)
            $adminEmail = \App\Models\Setting::getValue('support_email') ?? 'admin@example.com'; 
            \App\Services\EmailService::send('admin-new-seller', $adminEmail, [
                'name' => $user->name,
                'company_name' => $request->company_name,
                'email' => $user->email,
            ]);
        });

        if ($request->plan_id) {
            $plan = \App\Models\Plan::find($request->plan_id);
            if ($plan && ($plan->price_inr > 0 || $plan->price_usd > 0)) {
                 return redirect()->route('seller.subscription.checkout', ['plan' => $plan->id, 'currency' => 'INR'])
                     ->with('success', 'Account created successfully! Please complete your subscription payment.');
            }
        }

        return redirect()->route('seller.dashboard')->with('success', 'Registration successful! Welcome to MiniPort.');
    }

    public function registerBuyer(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);

        DB::transaction(function () use ($request) {
            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'password' => Hash::make($request->password),
                'role' => 'buyer',
            ]);
            
            // Assign Spatie role for middleware compatibility
            $user->assignRole('buyer');

            Buyer::create([
                'user_id' => $user->id,
            ]);

            Auth::login($user);

            // Send Welcome Email
            \App\Services\EmailService::send('buyer-welcome', $user->email, [
                'name' => $user->name,
                'email' => $user->email,
            ]);
        });

        return redirect('/buyer/dashboard');
    }
}
