<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;
use Yajra\DataTables\Facades\DataTables;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\PermissionsImport;
class PermissionController extends Controller
{
    public function index()
    {
        // Returns the main blade file containing your DataTable and Modal
        return view('backend.permissions.index');
    }

    public function fetch(Request $request)
    {
        if ($request->ajax()) {
            // Fetch permissions
            $data = Permission::orderBy('id', 'desc')->get();
            $user = auth()->user(); // Get authenticated user

            return DataTables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function ($row) use ($user) {
                    $btn = '';

                    // Edit Permission Check
                    if ($user->can('edit Permission')) {
                        $btn .= '<button onclick="editPermission(' . $row->id . ')" class="btn btn-info mr-1" title="Edit"><i class="feather feather-edit"></i></button>';
                    }

                    // Delete Permission Check
                    if ($user->can('delete Permission')) {
                        $btn .= '<button onclick="confirmDelete(' . $row->id . ')" class="btn btn-danger" title="Delete"><i class="feather feather-trash-2"></i></button>';
                    }

                    return $btn ?: '<span class="badge bg-secondary">No Action</span>';
                })
                ->rawColumns(['action'])
                ->make(true);
        }
    }

    public function store(Request $request)
    {
        // Validate, ensuring the name is unique but ignoring the current ID if updating
        $request->validate([
            'name' => 'required|string|max:255|unique:permissions,name,' . $request->permission_id,
        ]);

        Permission::updateOrCreate(
            ['id' => $request->permission_id],
            [
                'name' => $request->name,
                'guard_name' => 'web' // Explicitly setting guard name is good practice with Spatie
            ]
        );

        return response()->json(['success' => 'Permission saved successfully!']);
    }

    public function edit($id)
    {
        $permission = Permission::findOrFail($id);
        return response()->json(['permission' => $permission]);
    }

    public function destroy($id)
    {
        Permission::findOrFail($id)->delete();
        return response()->json(['success' => 'Deleted successfully!']);
    }
    public function import(Request $request)
    {
        $request->validate([
            'excel_file' => 'required|mimes:xlsx,xls,csv|max:2048'
        ]);

        try {
            Excel::import(new PermissionsImport, $request->file('excel_file'));
            return response()->json(['success' => 'Permissions imported successfully!']);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Error importing file. Ensure the header row is "name".'], 500);
        }
    }

    // NEW METHOD: Generates a sample CSV file dynamically
    public function downloadSample()
    {
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="permissions_sample.csv"',
        ];

        $callback = function () {
            $file = fopen('php://output', 'w');
            fputcsv($file, ['name']);
            fputcsv($file, ['edit articles']);
            fputcsv($file, ['delete articles']);
            fputcsv($file, ['manage users']);
            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }
}
