<?php

namespace Modules\VetOneDemo\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Utils\BusinessUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Modules\VetOneDemo\Services\DemoProvisioner;

/**
 * Public self-service registration for a VetOne 48-hour demo tenant.
 * Does NOT touch the core /business/register flow.
 */
class RegisterController extends Controller
{
    public function __construct(
        protected BusinessUtil $businessUtil,
        protected DemoProvisioner $provisioner,
    ) {
    }

    public function create()
    {
        return view('vetonedemo::register', [
            'staffRoles' => config('vetonedemo.staff_roles', []),
            'tps'        => config('vetonedemo.tps', []),
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name'         => 'required|string|max:255',
            'owner_first'  => 'required|string|max:255',
            'owner_last'   => 'nullable|string|max:255',
            'email'        => 'required|email|max:255|unique:users,email',
            'phone'        => 'required|string|max:40',
            'whatsapp'     => 'nullable|string|max:40',
            'country'      => 'required|string|max:255',
            'state'        => 'nullable|string|max:255',
            'city'         => 'required|string|max:255',
            'zip_code'     => 'nullable|string|max:20',
            'landmark'     => 'nullable|string|max:255',
            'website'      => 'nullable|string|max:255',
            'accent_hex'   => 'nullable|string|max:9',
            'business_logo' => 'nullable|image|max:2048',
            'password'     => 'required|string|min:6|confirmed',
            'doctors'      => 'required|integer|min:1|max:20',
            'nurses'       => 'nullable|integer|min:0|max:50',
            'receptionists' => 'nullable|integer|min:0|max:50',
            'accounting'   => 'nullable|integer|min:0|max:50',
            'hr'           => 'nullable|integer|min:0|max:50',
        ]);

        // Unique slug from the business name.
        $slug = $this->uniqueSlug($validated['name']);

        // Logo → stored file + public URL for the PWA brand payload.
        $logoName = $this->businessUtil->uploadFile($request, 'business_logo', 'business_logos', 'image');
        $logoUrl  = ! empty($logoName) ? url('uploads/business_logos/' . $logoName) : null;

        $input = [
            'name'        => $validated['name'],
            'owner_first' => $validated['owner_first'],
            'owner_last'  => $validated['owner_last'] ?? '',
            'email'       => $validated['email'],
            'phone'       => $validated['phone'],
            'whatsapp'    => $validated['whatsapp'] ?? $validated['phone'],
            'slug'        => $slug,
            'accent_hex'  => $validated['accent_hex'] ?? null,
            'country'     => $validated['country'],
            'state'       => $validated['state'] ?? '',
            'city'        => $validated['city'],
            'zip_code'    => $validated['zip_code'] ?? '',
            'landmark'    => $validated['landmark'] ?? '',
            'website'     => $validated['website'] ?? '',
            'logo'        => $logoName ?: null,
            'logo_url'    => $logoUrl,
            'password'    => $validated['password'],
            'counts'      => [
                'Doctor'       => (int) $validated['doctors'],
                'Nurse'        => (int) ($validated['nurses'] ?? 0),
                'Receptionist' => (int) ($validated['receptionists'] ?? 0),
                'Accounting'   => (int) ($validated['accounting'] ?? 0),
                'HR'           => (int) ($validated['hr'] ?? 0),
            ],
        ];

        try {
            $result = $this->provisioner->provision($input);
        } catch (\Throwable $e) {
            Log::error('VetOneDemo provisioning failed: ' . $e->getMessage() . ' @ ' . $e->getFile() . ':' . $e->getLine());
            return back()->withInput()->with('error', __('Something went wrong creating your demo. Please try again or contact TPS.'));
        }

        // Log the owner straight in and send them through the onboarding gate.
        Auth::login($result['owner']);

        return redirect()->route('vetone.onboarding')->with('demo_provisioned', [
            'slug'     => $result['slug'],
            'username' => $result['owner_username'],
        ]);
    }

    /** Async slug availability for the register form. */
    public function checkSlug(Request $request)
    {
        $base = (string) $request->input('name', $request->input('slug', ''));
        $slug = Str::slug($base);

        $available = $slug !== '' && ! $this->slugTaken($slug);

        return response()->json([
            'slug'      => $slug,
            'suggested' => $available ? $slug : $this->uniqueSlug($base),
            'available' => $available,
        ]);
    }

    /* ─────────────────────────── helpers ──────────────────────────────── */

    protected function uniqueSlug(string $name): string
    {
        $base = Str::slug($name) ?: 'clinic';
        $slug = $base;
        $i = 2;
        while ($this->slugTaken($slug)) {
            $slug = $base . '-' . $i;
            $i++;
        }
        return $slug;
    }

    protected function slugTaken(string $slug): bool
    {
        return DB::table('portal_brands')->where('slug', $slug)->exists()
            || DB::table('business')->where('demo_slug', $slug)->exists();
    }
}
