<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Empresa;
use App\Models\Plan;
use App\Models\Rol;
use App\Models\Suscripcion;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class RegistroEmpresaController extends Controller
{
    public function create(): View
    {
        $plans = Plan::query()
            ->where('activo', 1)
            ->orderBy('precio_mensual')
            ->orderBy('id')
            ->get(['id', 'nombre', 'precio_mensual']);

        return view('auth.register', [
            'plans' => $plans,
            'guestColumnClass' => 'col-12 col-lg-11 col-xl-10 col-xxl-9',
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'nombre' => ['required', 'string', 'max:150'],
            'email' => ['nullable', 'email', 'max:180'],
            'nit' => ['nullable', 'string', 'max:40'],
            'telefono' => ['nullable', 'string', 'max:40'],
            'direccion' => ['nullable', 'string', 'max:255'],
            'plan_id' => ['required', 'integer', Rule::exists('planes', 'id')->where('activo', 1)],
            'admin_nombre' => ['required', 'string', 'max:150'],
            'admin_email' => ['required', 'email', 'max:180', Rule::unique('usuarios', 'email')],
            'admin_password' => ['required', 'string', 'min:8', 'confirmed:admin_password_confirm'],
            'admin_password_confirm' => ['required', 'string'],
        ], [
            'admin_password.confirmed' => 'La confirmación de contraseña no coincide.',
            'admin_email.unique' => 'Ese correo ya existe en el sistema. Inicia sesión o usa otro correo.',
        ]);

        $slug = $this->sanitizeSlug($validated['nombre']);
        if ($slug === '') {
            return back()->withInput()->withErrors(['nombre' => 'No se pudo generar un identificador de empresa válido.']);
        }
        if (Empresa::query()->where('slug', $slug)->exists()) {
            return back()->withInput()->withErrors(['nombre' => 'Ese nombre de acceso ya existe. Usa otro nombre de empresa.']);
        }

        $plan = Plan::query()->where('activo', 1)->findOrFail((int) $validated['plan_id']);

        DB::transaction(function () use ($validated, $slug, $plan): void {
            $empresa = Empresa::query()->create([
                'nombre' => trim($validated['nombre']),
                'slug' => $slug,
                'nit' => $validated['nit'] ?? null,
                'email' => isset($validated['email']) ? mb_strtolower(trim($validated['email'])) : null,
                'telefono' => $validated['telefono'] ?? null,
                'direccion' => $validated['direccion'] ?? null,
                'moneda' => 'COP',
                'zona_horaria' => 'America/Bogota',
                'estado' => 'activa',
            ]);

            $rol = Rol::query()->firstOrCreate(
                ['slug' => 'admin_empresa'],
                ['nombre' => 'Admin Empresa', 'descripcion' => 'Administrador del tenant', 'activo' => 1]
            );

            DB::table('rol_permiso')->insertUsing(
                ['rol_id', 'permiso_id', 'created_at'],
                DB::table('permisos')
                    ->select(DB::raw((int) $rol->id.' as rol_id'), 'id as permiso_id', DB::raw('NOW() as created_at'))
                    ->where('modulo', '<>', 'superadmin')
                    ->where('modulo', '<>', 'empresas')
                    ->where('codigo', 'not like', 'superadmin.%')
                    ->where('codigo', 'not like', 'empresas.%')
                    ->whereNotIn('id', function ($query) use ($rol): void {
                        $query->select('permiso_id')->from('rol_permiso')->where('rol_id', (int) $rol->id);
                    })
            );

            $user = User::query()->create([
                'empresa_id' => $empresa->id,
                'rol_id' => $rol->id,
                'nombre' => trim($validated['admin_nombre']),
                'email' => mb_strtolower(trim($validated['admin_email'])),
                'password' => Hash::make($validated['admin_password']),
                'activo' => 1,
            ]);

            DB::table('usuario_empresa')->insert([
                'usuario_id' => $user->id,
                'empresa_id' => $empresa->id,
                'es_principal' => 1,
                'created_at' => now(),
            ]);

            $isFree = ((float) $plan->precio_mensual) <= 0;
            $startDate = now()->toDateString();
            $endDate = now()->addDays($isFree ? 14 : 30)->toDateString();

            Suscripcion::query()->create([
                'empresa_id' => $empresa->id,
                'plan_id' => $plan->id,
                'fecha_inicio' => $startDate,
                'fecha_vencimiento' => $endDate,
                'estado' => 'activa',
                'trial' => $isFree ? 1 : 0,
                'auto_renovacion' => 1,
            ]);
        });

        return redirect()->route('login', ['empresa' => $slug])
            ->with('status', 'Empresa registrada correctamente. Ya puedes iniciar sesión.');
    }

    private function sanitizeSlug(string $value): string
    {
        $slug = Str::slug($value, '-');

        return trim($slug, '-');
    }
}
