<?php

namespace App\Http\Controllers;

use App\Models\Vendor;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class VendorRegistrationController extends Controller
{
    public function create()
    {
        if (Auth::user()->isVendor()) {
            return redirect()->route('vendor.dashboard');
        }

        return view('vendor.register');
    }

    public function store(Request $request)
    {
        if (Auth::user()->isVendor()) {
            return redirect()->route('vendor.dashboard');
        }

        $data = $request->validate([
            'shop_name' => 'required|string|max:255|unique:vendors',
            'description' => 'nullable|string',
            'phone' => 'nullable|string|max:20',
            'address' => 'nullable|string',
            'city' => 'nullable|string|max:100',
            'state' => 'nullable|string|max:100',
            'country' => 'required|string|max:100',
            'zip_code' => 'nullable|string|max:20',
            'logo' => 'nullable|image|max:2048',
        ]);

        if ($request->hasFile('logo')) {
            $data['logo'] = $request->file('logo')->store('vendors/logos', 'public');
        }

        $data['user_id'] = Auth::id();
        $data['slug'] = Str::slug($data['shop_name']);
        $data['status'] = 'pending';

        Vendor::create($data);

        // Assign vendor role
        Auth::user()->assignRole('vendor');

        return redirect()->route('vendor.pending')
            ->with('success', 'Vendor application submitted. Awaiting approval.');
    }

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