<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\DemoRequest;
use App\Models\Role;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;
use Illuminate\View\View;

/**
 * Platform-wide sales leads from the public marketing page's "Request a
 * Demo" form — Super Admin only, same as Companies/Roles/Screenshots (a
 * demo lead isn't scoped to any single company).
 */
class DemoRequestController extends Controller
{
    public function index(): View
    {
        return view('admin.demo-requests.index', [
            'demoRequests' => DemoRequest::latest()->get(),
        ]);
    }

    public function updateStatus(Request $request, DemoRequest $demoRequest): RedirectResponse
    {
        $data = $request->validate([
            'status' => ['required', Rule::in(['new', 'contacted', 'converted', 'closed'])],
        ]);

        $demoRequest->update($data);

        return back()->with('success', 'Lead status updated.');
    }

    public function destroy(DemoRequest $demoRequest): RedirectResponse
    {
        $demoRequest->delete();

        return back()->with('success', 'Lead removed.');
    }

    /**
     * ORG-02 / AUTO-02 from the system analysis: converting a won lead into
     * a real tenant previously meant manually creating the company, then
     * separately creating its first admin user, then remembering to
     * communicate credentials — all by hand. This does all three in one
     * transaction.
     */
    public function convertForm(DemoRequest $demoRequest): View
    {
        abort_if($demoRequest->status === 'converted', 404);

        return view('admin.demo-requests.convert', compact('demoRequest'));
    }

    public function convert(Request $request, DemoRequest $demoRequest): RedirectResponse
    {
        abort_if($demoRequest->status === 'converted', 409, 'This lead has already been converted.');

        $data = $request->validate([
            'company_name' => ['required', 'string', 'max:255'],
            'company_code' => ['required', 'string', 'max:20', 'alpha_dash', Rule::notIn(['123']), 'unique:companies,code'],
            'slug' => ['required', 'string', 'max:255', 'alpha_dash', 'unique:companies,slug'],
            'admin_name' => ['required', 'string', 'max:255'],
            'admin_username' => ['required', 'string', 'max:255', 'alpha_dash', 'unique:users,username'],
            'admin_email' => ['required', 'email', 'max:255', 'unique:users,email'],
            'admin_password' => ['required', 'string', Password::defaults()],
        ]);

        [$company, $admin] = DB::transaction(function () use ($data, $demoRequest) {
            $company = Company::create([
                'name' => $data['company_name'],
                'slug' => $data['slug'],
                'code' => $data['company_code'],
                'distance_unit' => 'mi',
                'timezone' => 'UTC',
                'is_active' => true,
            ]);

            $admin = User::create([
                'company_id' => $company->id,
                'role_id' => Role::where('name', 'company_admin')->value('id'),
                'name' => $data['admin_name'],
                'username' => $data['admin_username'],
                'email' => $data['admin_email'],
                'password' => Hash::make($data['admin_password']),
                'status' => 'active',
            ]);

            $demoRequest->update(['status' => 'converted']);

            return [$company, $admin];
        });

        return redirect()->route('admin.companies.edit', $company)->with(
            'success',
            "Company \"{$company->name}\" created with code {$company->code}. Admin login: username \"{$admin->username}\"."
        );
    }
}
