<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\Backend\EditorialCategory;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class EditorialCategoryController extends Controller
{
    public function index()
    {
        return view('backend.editorial_category.index');
    }

    public function fetch(Request $request)
    {
        if ($request->ajax()) {
            $data = EditorialCategory::orderBy('serial_number', 'asc')->get();
            $user = auth()->user(); // Get authenticated user

            return DataTables::of($data)
                ->addIndexColumn()
                ->addColumn('status', function ($row) {
                    return $row->status == '1'
                        ? '<i class="feather feather-check-circle text-success"></i>'
                        : '<i class="feather feather-x-circle text-danger"></i>';
                })
                ->addColumn('action', function ($row) use ($user) {
                    $btn = '';

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

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

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

    public function store(Request $request)
    {
        // Added validation for the new serial_number field
        $request->validate([
            'name' => 'required',
            'serial_number' => 'required|integer',
        ]);

        EditorialCategory::updateOrCreate(
            ['id' => $request->category_id],
            $request->all()
        );

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

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

    public function destroy($id)
    {
        EditorialCategory::findOrFail($id)->delete();
        return response()->json(['success' => 'Deleted successfully!']);
    }
}
