<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Tenant;
use App\Services\TenantService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class TenantController extends Controller
{
    public function __construct(private TenantService $tenantService)
    {
    }

    /** GET /api/admin/tenant/me — own profile + plan features */
    public function me(): JsonResponse
    {
        /** @var Tenant $tenant */
        $tenant = app('tenant');

        // Resolve plan features
        $allFeatures = [
            'products' => true,
            'categories' => true,
            'orders' => true,
            'leads' => true,
            'reviews' => true,
            'stock' => true,
            'marketing' => true,
            'courier' => true,
            'home_editor' => true,
            'landing_editor' => true,
            'messenger_ai' => true,
            'ubaidi_ai' => true,
            'ubaidi_ads_marketer' => true,
        ];

        if ($tenant->isTrialActive()) {
            $planFeatures = $allFeatures;
        } elseif ($tenant->isActive() && $tenant->plan_id) {
            $plan = \App\Models\SubscriptionPlan::find($tenant->plan_id);
            $planFeatures = $plan ? (json_decode($plan->features_json ?? '{}', true) ?: $allFeatures) : $allFeatures;
        } else {
            $planFeatures = [
                'products' => true,
                'categories' => false,
                'orders' => true,
                'leads' => false,
                'reviews' => false,
                'stock' => false,
                'marketing' => false,
                'courier' => false,
                'home_editor' => false,
                'landing_editor' => false,
                'messenger_ai' => false,
                'ubaidi_ai' => false,
                'ubaidi_ads_marketer' => false,
            ];
        }

        $trialEndsAt = $tenant->trial_ends_at;
        $trialDaysRemaining = $trialEndsAt
            ? max(0, (int) now()->diffInDays(\Carbon\Carbon::parse($trialEndsAt), false))
            : null;

        $ns1 = \Illuminate\Support\Facades\DB::table('global_settings')->where('setting_key', 'name_server_1')->value('setting_value');
        $ns2 = \Illuminate\Support\Facades\DB::table('global_settings')->where('setting_key', 'name_server_2')->value('setting_value');
        $ns3 = \Illuminate\Support\Facades\DB::table('global_settings')->where('setting_key', 'name_server_3')->value('setting_value');
        $ns4 = \Illuminate\Support\Facades\DB::table('global_settings')->where('setting_key', 'name_server_4')->value('setting_value');
        $ns5 = \Illuminate\Support\Facades\DB::table('global_settings')->where('setting_key', 'name_server_5')->value('setting_value');
        $ns6 = \Illuminate\Support\Facades\DB::table('global_settings')->where('setting_key', 'name_server_6')->value('setting_value');

        return response()->json([
            'success' => true,
            'data' => $tenant,
            // Flat keys expected by AdminDashboard.tsx
            'plan_features' => $planFeatures,
            'trial_days_remaining' => $trialDaysRemaining,
            'trial_ends_at' => $trialEndsAt,
            'subscription_status' => $tenant->subscription_status,
            'name_server_1' => $ns1 ?: 'ns1.shophyfast.com',
            'name_server_2' => $ns2 ?: 'ns2.shophyfast.com',
            'name_server_3' => $ns3 ?: '',
            'name_server_4' => $ns4 ?: '',
            'name_server_5' => $ns5 ?: '',
            'name_server_6' => $ns6 ?: '',
        ]);
    }

    /** POST /api/admin/tenant/update-slug */
    public function updateSlug(Request $request): JsonResponse
    {
        /** @var Tenant $tenant */
        $tenant = app('tenant');

        if ($tenant->subdomain_locked) {
            return response()->json(['error' => 'Subdomain আর পরিবর্তন করা যাবে না।'], 403);
        }

        $newSlug = $this->tenantService->generateUniqueSlug($request->input('custom_slug'));

        if (strlen($newSlug) < 3) {
            return response()->json(['error' => 'Subdomain কমপক্ষে ৩ অক্ষর হতে হবে'], 422);
        }

        $tenant->update(['business_slug' => $newSlug, 'subdomain_locked' => true]);

        return response()->json([
            'success' => true,
            'new_slug' => $newSlug,
            'subdomain' => $newSlug . '.shophyfast.com',
        ]);
    }

    /** POST /api/admin/tenant/update-custom-domain */
    public function updateCustomDomain(Request $request): JsonResponse
    {
        /** @var Tenant $tenant */
        $tenant = app('tenant');

        $customDomain = $request->input('custom_domain');

        // Remove http://, https://, www., and trailing slashes
        $customDomain = preg_replace('#^https?://#', '', $customDomain);
        $customDomain = preg_replace('#^www\.#', '', $customDomain);
        $customDomain = rtrim($customDomain, '/');

        if (empty($customDomain)) {
            return response()->json(['error' => 'ডোমেইন নাম প্রদান করুন'], 422);
        }

        // Check uniqueness
        $exists = Tenant::where('custom_domain', $customDomain)
            ->where('id', '!=', $tenant->id)
            ->exists();

        if ($exists) {
            return response()->json(['error' => 'এই ডোমেইনটি অন্য একজন ব্যবহার করছেন'], 422);
        }

        $tenant->update(['custom_domain' => $customDomain]);

        try {
            $ns1 = \Illuminate\Support\Facades\DB::table('global_settings')->where('setting_key', 'name_server_1')->value('setting_value');
            $ns2 = \Illuminate\Support\Facades\DB::table('global_settings')->where('setting_key', 'name_server_2')->value('setting_value');
            $ns3 = \Illuminate\Support\Facades\DB::table('global_settings')->where('setting_key', 'name_server_3')->value('setting_value');
            $ns4 = \Illuminate\Support\Facades\DB::table('global_settings')->where('setting_key', 'name_server_4')->value('setting_value');
            $ns5 = \Illuminate\Support\Facades\DB::table('global_settings')->where('setting_key', 'name_server_5')->value('setting_value');
            $ns6 = \Illuminate\Support\Facades\DB::table('global_settings')->where('setting_key', 'name_server_6')->value('setting_value');

            \Illuminate\Support\Facades\Mail::to($tenant->email)->send(new \App\Mail\CustomDomainAdded(
                $tenant,
                $customDomain,
                $ns1 ?: 'ns1.shophyfast.com',
                $ns2 ?: 'ns2.shophyfast.com',
                $ns3,
                $ns4,
                $ns5,
                $ns6
            ));
        } catch (\Exception $e) {
            // Ignore mail failure
        }

        return response()->json([
            'success' => true,
            'custom_domain' => $customDomain,
            'message' => 'Custom Domain সফলভাবে যুক্ত করা হয়েছে!'
        ]);
    }

    /** POST /api/admin/tenant/remove-custom-domain */
    public function removeCustomDomain(Request $request): JsonResponse
    {
        /** @var Tenant $tenant */
        $tenant = app('tenant');
        $removedDomain = $tenant->custom_domain;

        $tenant->update(['custom_domain' => null]);

        try {
            if ($removedDomain) {
                \Illuminate\Support\Facades\Mail::to($tenant->email)->send(new \App\Mail\CustomDomainRemoved($tenant, $removedDomain));
            }
        } catch (\Exception $e) {
            // Ignore mail failure
        }

        return response()->json([
            'success' => true,
            'message' => 'Custom Domain মুছে ফেলা হয়েছে। এখন আপনার Subdomain সক্রিয়।'
        ]);
    }
}
