<?php

namespace App\Services;

use App\Models\AuditLog;
use App\Models\Branch;
use App\Models\Service;
use App\Models\Tenant;
use App\Models\TenantOnboarding;
use App\Models\User;

class TenantOnboardingService
{
    public function getProgress(Tenant $tenant): array
    {
        $onboarding = TenantOnboarding::firstOrCreate(
            ['tenant_id' => $tenant->id],
            ['status' => 'pending', 'progress_percentage' => 20]
        );

        $steps = [
            'company_profile' => ! empty($tenant->email) && ! empty($tenant->trn),
            'main_branch' => Branch::where('tenant_id', $tenant->id)->exists(),
            'owner_user' => User::where('tenant_id', $tenant->id)->exists(),
            'services_configured' => Service::where('tenant_id', $tenant->id)->exists(),
            'invoice_numbering' => true,
            'working_hours' => true,
        ];

        $completedCount = count(array_filter($steps));
        $totalCount = count($steps);
        $percentage = round(($completedCount / $totalCount) * 100);

        $onboarding->update(['progress_percentage' => $percentage]);

        return [
            'status' => $onboarding->status,
            'percentage' => $percentage,
            'steps' => $steps,
            'is_ready_for_go_live' => ($completedCount === $totalCount),
        ];
    }

    public function completeOnboarding(Tenant $tenant): TenantOnboarding
    {
        $onboarding = TenantOnboarding::firstOrCreate(['tenant_id' => $tenant->id]);
        $onboarding->update([
            'status' => 'completed',
            'progress_percentage' => 100,
            'completed_at' => now(),
        ]);

        AuditLog::record('onboarding', 'tenant.onboarding_completed', $tenant);

        return $onboarding;
    }
}
