<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\Addon;
use App\Models\SubscriptionPlan;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class PlanController extends Controller
{
    private const FEATURE_KEYS = [
        'payroll' => 'Payroll',
        'compliance_pf_esi_pt' => 'Compliance (PF, ESI, PT)',
        'attendance_biometric' => 'Attendance (biometric)',
        'leave_management' => 'Leave management',
        'api_access' => 'API access',
    ];

    public function index()
    {
        $plans = SubscriptionPlan::withCount('companies')->orderBy('base_price_monthly')->get();
        return view('superadmin.plans.index', compact('plans'));
    }

    public function create()
    {
        $addons = Addon::orderBy('name')->get();
        $featureKeys = self::FEATURE_KEYS;

        return view('superadmin.plans.create', compact('addons', 'featureKeys'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string|max:1000',
            'base_price_monthly' => 'required|numeric|min:0',
            'base_price_yearly' => 'required|numeric|min:0',
            'per_employee_price' => 'required|numeric|min:0',
            'employee_limit' => 'nullable|integer|min:1',
            'billing_type' => ['required', Rule::in(['monthly', 'yearly', 'lifetime'])],
            'active' => 'boolean',
            'is_popular' => 'boolean',
            'currency_code' => 'nullable|string|max:10',
            'currency_symbol' => 'nullable|string|max:10',
            'features' => 'nullable|array',
            'features.*' => ['string', Rule::in(array_keys(self::FEATURE_KEYS))],
            'addon_ids' => 'nullable|array',
            'addon_ids.*' => 'integer|exists:addons,id',
        ]);
        $data['active'] = $request->boolean('active');
        $data['is_popular'] = $request->boolean('is_popular');
        $data['currency_code'] = $data['currency_code'] ?? 'INR';
        $data['currency_symbol'] = $data['currency_symbol'] ?? '₹';
        $data['employee_limit'] = $data['employee_limit'] ?? null;

        $plan = SubscriptionPlan::create(collect($data)->except(['features', 'addon_ids'])->toArray());
        $this->syncFeaturesAndAddons($plan, $data['features'] ?? [], $data['addon_ids'] ?? []);
        return redirect()->route('superadmin.plans.index')->with('success', 'Plan created successfully.');
    }

    public function edit(SubscriptionPlan $plan)
    {
        $plan->load(['planFeatures', 'addons']);
        $addons = Addon::orderBy('name')->get();
        $featureKeys = self::FEATURE_KEYS;

        return view('superadmin.plans.edit', compact('plan', 'addons', 'featureKeys'));
    }

    public function update(Request $request, SubscriptionPlan $plan)
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string|max:1000',
            'base_price_monthly' => 'required|numeric|min:0',
            'base_price_yearly' => 'required|numeric|min:0',
            'per_employee_price' => 'required|numeric|min:0',
            'employee_limit' => 'nullable|integer|min:1',
            'billing_type' => ['required', Rule::in(['monthly', 'yearly', 'lifetime'])],
            'active' => 'boolean',
            'is_popular' => 'boolean',
            'currency_code' => 'nullable|string|max:10',
            'currency_symbol' => 'nullable|string|max:10',
            'features' => 'nullable|array',
            'features.*' => ['string', Rule::in(array_keys(self::FEATURE_KEYS))],
            'addon_ids' => 'nullable|array',
            'addon_ids.*' => 'integer|exists:addons,id',
        ]);
        $data['active'] = $request->boolean('active');
        $data['is_popular'] = $request->boolean('is_popular');
        $data['currency_code'] = $data['currency_code'] ?? 'INR';
        $data['currency_symbol'] = $data['currency_symbol'] ?? '₹';
        $data['employee_limit'] = $data['employee_limit'] ?? null;

        $plan->update(collect($data)->except(['features', 'addon_ids'])->toArray());
        $this->syncFeaturesAndAddons($plan, $data['features'] ?? [], $data['addon_ids'] ?? []);
        return redirect()->route('superadmin.plans.index')->with('success', 'Plan updated successfully.');
    }

    public function destroy(SubscriptionPlan $plan)
    {
        if ($plan->companies()->count() > 0) {
            return redirect()->route('superadmin.plans.index')
                ->with('error', 'Cannot delete plan: it has tenants assigned. Reassign or remove tenants first.');
        }
        $plan->delete();
        return redirect()->route('superadmin.plans.index')->with('success', 'Plan deleted successfully.');
    }

    public function toggleActive(SubscriptionPlan $plan)
    {
        $plan->update(['active' => ! $plan->active]);
        return redirect()->route('superadmin.plans.index')
            ->with('success', 'Plan marked as ' . ($plan->active ? 'active' : 'inactive') . '.');
    }

    private function syncFeaturesAndAddons(SubscriptionPlan $plan, array $selectedFeatures, array $addonIds): void
    {
        $rows = collect(array_keys(self::FEATURE_KEYS))
            ->map(fn (string $featureKey) => [
                'feature_key' => $featureKey,
                'feature_value' => in_array($featureKey, $selectedFeatures, true) ? '1' : '0',
            ])
            ->all();

        $plan->planFeatures()->delete();
        $plan->planFeatures()->createMany($rows);
        $plan->addons()->sync($addonIds);
    }
}
