<?php

namespace App\Http\Controllers;

use App\Models\Permission;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;

class PermissionController extends Controller
{
    /** permissions টেবিলে guard_name আছে? */
    private function hasGuardColumn(): bool
    {
        return Schema::hasColumn('permissions', 'guard_name');
    }

    /** ডাটা অ্যারেতে guard_name কন্ডিশনালি যোগ করো */
    private function withGuard(array $data, string $guard): array
    {
        if ($this->hasGuardColumn()) {
            $data['guard_name'] = $guard ?: 'web';
        }
        return $data;
    }

    /** List + search */
    public function index(Request $request)
    {
        $q = trim((string) $request->get('q', ''));

        $permissions = Permission::query()
            ->when($q !== '', function ($qry) use ($q) {
                $qry->where(function ($x) use ($q) {
                    $x->where('name', 'like', "%{$q}%")
                      ->orWhere('slug', 'like', "%{$q}%");
                });
            })
            ->orderBy('position')
            ->orderBy('id')
            ->paginate(20)
            ->appends(['q' => $q]);

        return view('permissions.index', compact('permissions'));
    }

    /** Create form */
    public function create()
    {
        // parent হিসেবে দেখাবো যেগুলোর parent_permission_id = 0 (root parent)
        $parents = Permission::query()
            ->where('parent_permission_id', 0)
            ->orderBy('name')
            ->get(['id','name','slug']);

        return view('permissions.create', compact('parents'));
    }

    /** Store: single OR scaffold */
    public function store(Request $request)
    {
        // পুরনো DB হলে guard লাগবে না; তবু কন্ডিশনাল রাখলাম
        $guard = trim((string) $request->input('guard_name', 'web')) ?: 'web';

        // -----------------------------
        // 1) Scaffold Mode: পুরো module একসাথে
        // -----------------------------
        if ($request->boolean('scaffold')) {
            $module = Str::of($request->input('module', ''))
                ->lower()->replace([' ', '/', '\\'], '-')->trim('-')->value();

            if ($module === '') {
                return back()->withErrors(['module' => 'Module is required for scaffold.'])
                             ->withInput();
            }

            $label    = $request->input('label', Str::headline($module)); // e.g. "Group"
            $actions  = $request->input('actions', ['view','create','edit','delete']);
            $position = (int) $request->input('position', 999);
            $status   = (int) $request->input('status', 1);
            $desc     = $request->input('description');

            // parent row: {module}.index  -> parent_permission_id = 0 (NOT NULL টেবিলের জন্য)
            $base = [
                'name'        => $label,
                'slug'        => "{$module}.index",
                'description' => $desc,
                'created_by'  => Auth::id(),
                'updated_by'  => Auth::id(),
                'parent_permission_id' => 0,
                'status'      => $status,
                'position'    => $position,
            ];
            $parent = Permission::create($this->withGuard($base, $guard));

            // children
            foreach ($actions as $act) {
                $act = Str::of($act)->lower()->replace(' ', '_')->value();
                $child = [
                    'name'        => Str::title(str_replace('_', ' ', $act)),
                    'slug'        => "{$module}.{$act}",
                    'description' => null,
                    'created_by'  => Auth::id(),
                    'updated_by'  => Auth::id(),
                    'parent_permission_id' => $parent->id,  // child's parent
                    'status'      => $status,
                    'position'    => $position,
                ];
                Permission::create($this->withGuard($child, $guard));
            }

            return redirect()->route('permissions.index')
                ->with('status', "Scaffolded `{$label}` permissions created.");
        }

        // -----------------------------
        // 2) Single permission insert
        // -----------------------------
        $parentId = max(0, (int) $request->input('parent_permission_id', 0)); // ❗ ডিফল্ট 0

        // ইউনিক রুল: guard থাকলে guard অনুযায়ী, না থাকলে শুধু slug
        $slugRule = Rule::unique('permissions', 'slug');
        if ($this->hasGuardColumn()) {
            $slugRule = $slugRule->where(fn ($q) => $q->where('guard_name', $guard));
        }

        $validated = $request->validate([
            'name'        => ['required','string','max:255'],
            'slug'        => ['nullable','string','max:255', $slugRule],
            'description' => ['nullable','string','max:1000'],
            'parent_permission_id' => ['nullable','integer','min:0'], // 0 = root
            'status'      => ['nullable','in:0,1'],
            'position'    => ['nullable','integer'],
            'guard_name'  => ['nullable','in:web,api'],
        ]);

        // slug auto
        $slug = $validated['slug'] ?? Str::of($validated['name'])->lower()
            ->replace(['  ', ' '], ' ')
            ->replace([' index',' view',' create',' edit',' delete'],
                      ['.index','.view','.create','.edit','.delete'])
            ->replace(' ', '.')
            ->value();
        if (!str_contains($slug, '.')) {
            $slug = Str::of($validated['name'])->lower()
                       ->replace([' ', '/', '\\'], '.')->value();
        }

        $data = [
            'name'        => $validated['name'],
            'slug'        => $slug,
            'description' => $validated['description'] ?? null,
            'created_by'  => Auth::id(),
            'updated_by'  => Auth::id(),
            'parent_permission_id' => $parentId,
            'status'      => $validated['status'] ?? 1,
            'position'    => $validated['position'] ?? 999,
        ];

        $permission = Permission::create($this->withGuard($data, $guard));

        return redirect()->route('permissions.index')
            ->with('status', "Permission `{$permission->slug}` created.");
    }

    /** Edit form */
    public function edit(Permission $permission)
    {
        $parents = Permission::query()
            ->where('parent_permission_id', 0)
            ->where('id', '<>', $permission->id)
            ->orderBy('name')
            ->get(['id','name','slug']);

        return view('permissions.edit', compact('permission','parents'));
    }

    /** Update */
    public function update(Request $request, Permission $permission)
    {
        $guard = $this->hasGuardColumn()
            ? (trim((string) $request->input('guard_name', $permission->guard_name ?: 'web')) ?: 'web')
            : 'web';

        $parentId = max(0, (int) $request->input('parent_permission_id', 0));

        $slugRule = Rule::unique('permissions', 'slug')->ignore($permission->id);
        if ($this->hasGuardColumn()) {
            $slugRule = $slugRule->where(fn ($q) => $q->where('guard_name', $guard));
        }

        $validated = $request->validate([
            'name'        => ['required','string','max:255'],
            'slug'        => ['nullable','string','max:255', $slugRule],
            'description' => ['nullable','string','max:1000'],
            'parent_permission_id' => ['nullable','integer','min:0'],
            'status'      => ['nullable','in:0,1'],
            'position'    => ['nullable','integer'],
            'guard_name'  => ['nullable','in:web,api'],
        ]);

        $permission->name        = $validated['name'];
        $permission->slug        = $validated['slug'] ?? ($permission->slug ?: Str::slug($validated['name']));
        $permission->description = $validated['description'] ?? $permission->description;
        $permission->parent_permission_id = $parentId;              // ❗ 0 allowed
        $permission->status      = $validated['status'] ?? $permission->status;
        $permission->position    = $validated['position'] ?? $permission->position;
        if ($this->hasGuardColumn()) {
            $permission->guard_name = $guard;
        }
        $permission->updated_by  = Auth::id();
        $permission->save();

        return redirect()->route('permissions.index')
            ->with('status', "Permission `{$permission->slug}` updated.");
    }

    public function destroy(Permission $permission)
    {
        $slug = $permission->slug ?? $permission->name;
        $permission->delete();

        return redirect()->route('permissions.index')
            ->with('status', "Permission `{$slug}` deleted.");
    }
}



