<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;
use DataTables;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class PermissionController extends Controller {
    
    /* 1- validate and insert into to database */
    public function store(Request $request) {
        $validator = \Validator::make($request->all(), [
            'page' => 'required|string|max:255',
            'guard_name' => 'required|string|max:255',
        ]);

        if ($validator->passes()) {
            $page = $request->input('page');
            $guardName = $request->input('guard_name');
            $titles = ['list', 'create', 'edit', 'delete'];
            $created = 0;
            $skipped = 0;
            
            // Create 4 permissions automatically (list, create, edit, delete)
            foreach ($titles as $title) {
                $name = $page . '-' . $title;
                
                // Check if permission already exists
                $existing = Permission::where('name', $name)
                    ->where('guard_name', $guardName)
                    ->whereNull('deleted_at')
                    ->first();
                
                if (!$existing) {
                    Permission::create([
                        'name' => $name,
                        'page' => $page,
                        'title' => $title,
                        'guard_name' => $guardName,
                    ]);
                    $created++;
                } else {
                    $skipped++;
                }
            }
            
            if ($created > 0) {
                $message = "Successfully created {$created} permission(s).";
                if ($skipped > 0) {
                    $message .= " {$skipped} permission(s) already exist and were skipped.";
                }
                return response()->json(['success' => $message]);
            } else {
                return response()->json(['error' => ['page' => ['All permissions for this page and guard name already exist.']]]);
            }
        }
        return response()->json(['error' => $validator->errors()]);
    }

    /* 2- view index page */
    public function index() {
        return view('permissions.index');
    }

    public function datatable(Request $request)
    {
        if ($request->ajax()) {
            $data = Permission::select('id', 'title', 'guard_name', 'name', 'page')
                ->whereNull('deleted_at')
                ->orderByDesc('id');

            return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('id', fn($row) => $row->id)
                ->addColumn('page', fn($row) => e($row->page))
                ->addColumn('title', fn($row) => e($row->title))
                ->addColumn('guard_name', fn($row) => e($row->guard_name))
                ->addColumn('name', fn($row) => e($row->name))
                ->addColumn('action', fn($row) => view('permissions.partials.actions', compact('row'))->render())
                ->rawColumns(['action'])
                ->setRowId(fn($row) => 'row_' . $row->id)
                ->make(true);
        }

        return view('permissions.index');
    }

    /* 3- View Add page */
    public function create() {
        return view('permissions.create');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id) {
        $permission = Permission::findOrFail($id);
        return view('permissions.show', compact('permission'));
    }

    /* 4- View update page */
    public function edit($id) {
        $row = Permission::find($id);
        return view('permissions.edit', ['row' => $row]);
    }

    /* 5- validate and update data into database */
    public function update(Request $request, $id) {
        $validator = \Validator::make($request->all(), [
            'page' => 'required|string|max:255',
            'title' => 'required|string|max:255|in:list,create,edit,delete',
            'guard_name' => 'required|string|max:255',
        ]);

        if ($validator->passes()) {
            $permission = Permission::where('id', $id)->whereNull('deleted_at')->first();
            
            if (!$permission) {
                return response()->json(['error' => ['title' => ['Permission not found.']]]);
            }

            // Auto-generate name as {page}-{title}
            $page = $request->input('page');
            $title = $request->input('title');
            $name = $page . '-' . $title;
            
            // Check if permission already exists (excluding current)
            $existing = Permission::where('name', $name)
                ->where('guard_name', $request->input('guard_name'))
                ->where('id', '!=', $id)
                ->whereNull('deleted_at')
                ->first();
            
            if ($existing) {
                return response()->json(['error' => ['title' => ['Permission with this page, title and guard name already exists.']]]);
            }

            $permission->name = $name;
            $permission->page = $page;
            $permission->title = $title;
            $permission->guard_name = $request->input('guard_name');
            $permission->update();

            return response()->json(['success' => 'Record is updated Successfully.']);
        }
        return response()->json(['error' => $validator->errors()]);
    }

    /* 6- delete record from database */
    public function destroy($id) {
        $row = Permission::where('id', $id)->whereNull('deleted_at')->first();
        if ($row) {
            $row->deleted_at = now();
            $row->save();
            return response()->json(['success' => '200', 'message' => 'Record is deleted Successfully. You can restore from restore button.']);
        }
        return response()->json(['error' => 'Permission not found.']);
    }

    /* 7- restore record from database */
    public function restore($id) {
        $row = Permission::where('id', $id)
            ->whereNotNull('deleted_at')
            ->first();
        if ($row) {
            $row->deleted_at = null;
            $row->save();
            return response()->json(['success' => '200', 'message' => 'Record is restored Successfully.']);
        }
        return response()->json(['error' => 'Permission not found.']);
    }
}

