<?php

namespace App\Http\Controllers;

use App\Models\Business;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class BusinessController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        
        // Check if this is a new user coming from email verification without business setup
        if (!$user->business_id) {
            // Show business setup form for new users
            return view('business.setup', [
                'user' => $user,
                'isSetup' => true
            ]);
        }
        
        // For existing users, show the business management page
        $businesses = Business::where('owner_id', Auth::id())->get();
        return view('settings.settings-general', compact('businesses'));
    }

    public function store(Request $request)
    {
        $user = Auth::user();
        
        // Check if this is initial setup (user has no business_id) or regular business creation
        $isInitialSetup = !$user->business_id;
        
        if ($isInitialSetup) {
            // Validation for initial business setup - using existing field names
            $validatedData = $request->validate([
                'name' => 'required|string|max:255',
                'address' => 'nullable|string|max:255',
                'city' => 'nullable|string|max:255',
                'state' => 'nullable|string|max:255',
                'zip' => 'nullable|integer',
                'phone' => 'nullable|string|max:15',
                'common_email' => 'nullable|email|max:255',
                'website' => 'nullable|string|max:255',
                'business_information' => 'nullable|string',
                'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048',
            ]);

            // Add owner_id to validated data
            $validatedData['owner_id'] = $user->id;

            // Handle image upload
            if ($request->hasFile('image')) {
                $validatedData['image'] = $request->file('image')->store('business_images', 'public');
            }

            // Create business for initial setup
            $business = Business::create($validatedData);

            // Update user with business_id
            $user->update(['business_id' => $business->id]);

            // Log out user after initial setup
            // Auth::logout();

            // return redirect()->route('login')
            //                 ->with('success', 'Business setup completed successfully! Please login to continue.');

            return redirect()->route('index');
            
        } else {
            // Regular business creation (existing functionality)
            $validatedData = $request->validate([
                'name' => 'required|string|max:255',
                'address' => 'nullable|string|max:255',
                'city' => 'nullable|string|max:255',
                'state' => 'nullable|string|max:255',
                'zip' => 'nullable|integer',
                'phone' => 'nullable|string|max:15',
                'common_email' => 'nullable|email|max:255',
                'website' => 'nullable|string|max:255',
                'business_information' => 'nullable|string',
            ]);

            // Add owner_id to validated data
            $validatedData['owner_id'] = auth()->id();

            if ($request->hasFile('image')) {
                $validatedData['image'] = $request->file('image')->store('business_images', 'public');
            }

            Business::create($validatedData);
            return redirect()->back()->with('success', 'Business created successfully.');
        }
    }

    // Update method (keep existing functionality)
    public function update(Request $request, $id)
    {
        $business = Business::findOrFail($id);
        $user = Auth::user();

        // Security check: ensure user can update this business
        if ($business->owner_id !== $user->id && $user->business_id !== $business->id) {
            return redirect()->back()->with('error', 'Unauthorized to update this business.');
        }

        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048',
            'address' => 'nullable|string|max:255',
            'city' => 'nullable|string|max:255',
            'state' => 'nullable|string|max:255',
            'zip' => 'nullable|integer',
            'phone' => 'nullable|string|max:15',
            'common_email' => 'nullable|email|max:255',
            'website' => 'nullable|string|max:255',
            'business_information' => 'nullable|string',
        ]);

        $validatedData['owner_id'] = auth()->id();

        if ($request->hasFile('image')) {
            $uploadedFile = $request->file('image');
            if ($business->image) {
                Storage::disk('public')->delete($business->image);
            }
            $path = $uploadedFile->store('business_images', 'public');
            $validatedData['image'] = $path;
        } else {
            $validatedData['image'] = $business->image;
        }

        $business->update($validatedData);
        return redirect()->back()->with('success', 'Business updated successfully.');
    }
}
