<?php

namespace Modules\SaasSwitcher\Http\Controllers;

use App\Business;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Modules\SaasSwitcher\Support\ProjectRegistry;

/**
 * Super-admin page to manage per-business module entitlements per project —
 * the module-owned replacement for the old Business Settings checkboxes (so no
 * core controller/view is touched). Lives under /saas (super-admin only).
 *
 * Mode per project:  all  = NULL (fail-open, fully entitled)
 *                    none = []   (clean base ERP)
 *                    list = exactly the checked gateable modules
 * Saving applies to every business in that project's database.
 */
class EntitlementsController extends Controller
{
    private function assertSuperAdmin(): void
    {
        DB::setDefaultConnection('mysql');
        abort_unless(Auth::check() && Auth::user()->can('superadmin'), 403, 'Super-admin only.');
    }

    public function index()
    {
        $this->assertSuperAdmin();

        $gateable = config('saasswitcher.gateable_modules', []);
        $projects = [];

        foreach (ProjectRegistry::all() as $key => $proj) {
            $conn = $proj['connection'] ?? null;
            $current = null; // null = all (fail-open)
            try {
                if ($conn) {
                    $raw = optional(Business::on($conn)->orderBy('id')->first())
                        ->getAttributes()['module_entitlements'] ?? null;
                    $decoded = is_string($raw) ? json_decode($raw, true) : $raw;
                    $current = is_array($decoded) ? $decoded : null;
                }
            } catch (\Throwable $e) {
                $current = null;
            }

            $projects[$key] = ['meta' => $proj, 'current' => $current];
        }

        return view('saasswitcher::entitlements', compact('projects', 'gateable'));
    }

    public function save(Request $request, string $key)
    {
        $this->assertSuperAdmin();
        abort_unless(ProjectRegistry::exists($key), 404);

        $conn     = ProjectRegistry::connection($key);
        $gateable = array_keys(config('saasswitcher.gateable_modules', []));
        $mode     = $request->input('mode', 'list');

        if ($mode === 'all') {
            $value = null;                 // fail-open
        } elseif ($mode === 'none') {
            $value = [];                   // base ERP
        } else {
            $value = array_values(array_intersect((array) $request->input('modules', []), $gateable));
        }

        // Apply to every business in this project's DB (raw JSON; no model cast needed).
        Business::on($conn)->getQuery()->update([
            'module_entitlements' => $value === null ? null : json_encode($value),
        ]);

        return redirect()->route('saas.entitlements')
            ->with('status', ['success' => 1, 'msg' => "Entitlements updated for '{$key}'."]);
    }
}
