<?php

declare(strict_types=1);

namespace App\Controllers\PlatformAdmin;

use App\Core\BaseController;
use App\Core\Database;
use App\Core\PlatformAuth;
use App\Core\Request;
use App\Core\Response;
use App\Core\Validator;
use App\Services\SubscriptionService;
use PDO;

/**
 * PlatformCompanyController
 *
 * The platform owner's view across every tenant: who's active, who's
 * trialing, who's lapsed — and the manual-onboarding path for a
 * company you're setting up yourself rather than having sign up.
 */
final class PlatformCompanyController extends BaseController
{
    public function index(Request $request): Response
    {
        $companies = Database::connection()->query(
            "SELECT bl.*,
                    (SELECT COUNT(*) FROM users u JOIN user_business_lines ubl ON ubl.user_id = u.id WHERE ubl.business_line_id = bl.id) AS user_count
             FROM business_lines bl
             ORDER BY bl.created_at DESC"
        )->fetchAll(PDO::FETCH_ASSOC);

        return $this->view('platform/companies', [
            'title' => 'Companies',
            'companies' => $companies,
            'appDomain' => (string) config('app.domain', 'yourapp.com'),
        ], useLayout: false);
    }

    public function showOnboard(Request $request): Response
    {
        return $this->view('platform/companies-onboard', ['title' => 'Onboard a company'], useLayout: false);
    }

    public function onboard(Request $request): Response
    {
        $validator = Validator::make($request->all(), [
            'company_name' => 'required|string|max:191',
            'subdomain' => 'required|string|max:63',
            'first_name' => 'required|string|max:100',
            'last_name' => 'required|string|max:100',
            'email' => 'required|email',
            'duration_months' => 'required|integer|min:1|max:60',
        ]);

        if ($validator->fails()) {
            return $this->withErrors($request, $validator->errors(), 'platform/companies/onboard');
        }

        $data = $validator->validated();
        $tempPassword = bin2hex(random_bytes(8));

        try {
            $service = new SubscriptionService();
            $result = $service->registerTenant(
                companyName: $data['company_name'],
                subdomainSlug: $data['subdomain'],
                ownerFirstName: $data['first_name'],
                ownerLastName: $data['last_name'],
                ownerEmail: $data['email'],
                ownerPasswordHash: password_hash($tempPassword, PASSWORD_ARGON2ID),
            );

            $service->activateManually(
                $result['business_line_id'],
                (int) PlatformAuth::id(),
                (int) $data['duration_months'],
            );
        } catch (\RuntimeException $e) {
            return $this->withErrors($request, ['subdomain' => $e->getMessage()], 'platform/companies/onboard');
        }

        // Shown once — the admin passes this to the company directly.
        // There's no email-sending wired up here yet (see docs/SAAS_MIGRATION.md);
        // MailService already exists in this codebase and is the natural
        // place to plug in a "welcome, here's your login" email later.
        return $this->view('platform/companies-onboarded', [
            'title' => 'Company onboarded',
            'companyName' => $data['company_name'],
            'subdomain' => $data['subdomain'],
            'email' => $data['email'],
            'temporaryPassword' => $tempPassword,
            'appDomain' => (string) config('app.domain', 'yourapp.com'),
        ], useLayout: false);
    }

    public function suspend(Request $request, int $businessLineId): Response
    {
        (new SubscriptionService())->cancel($businessLineId);

        return $this->redirect('platform/companies');
    }
}
