<?php

namespace App\Services;

use App\Models\Tenant;

class TenantService
{
    /**
     * Get tenant from request token
     */
    public function getFromToken(string $token): ?Tenant
    {
        return Tenant::where('auth_token', $token)->first();
    }

    /**
     * Get tenant by business slug
     */
    public function getBySlug(string $slug): ?Tenant
    {
        return Tenant::where('business_slug', $slug)->first();
    }

    /**
     * Check if tenant has access to a specific feature
     */
    public function hasFeatureAccess(Tenant $tenant, string $feature): bool
    {
        // Trial tenants get all features
        if ($tenant->isTrialActive()) {
            return true;
        }

        // Active paid subscription
        if ($tenant->isActive() && $tenant->plan_id) {
            $plan = \App\Models\SubscriptionPlan::find($tenant->plan_id);
            if (!$plan || empty($plan->features_json)) return false;

            $features = json_decode($plan->features_json, true);
            return !empty($features[$feature]);
        }

        return false;
    }

    /**
     * Generate a unique business slug
     */
    public function generateUniqueSlug(string $businessName): string
    {
        $base = $this->slugify($businessName);
        $slug = $base;
        $i    = 1;

        while (Tenant::where('business_slug', $slug)->exists()) {
            $slug = $base . '-' . $i++;
        }

        return $slug;
    }

    private function slugify(string $text): string
    {
        $text = mb_strtolower(trim($text));
        $text = preg_replace('/[^\p{L}\p{N}\s-]/u', '', $text);
        $text = preg_replace('/\s+/', '-', $text);
        $text = preg_replace('/-+/', '-', $text);
        $text = trim($text, '-');
        return substr($text ?: 'shop-' . rand(1000, 9999), 0, 50);
    }
}
