<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Backend\JournalInfo;
use Yajra\DataTables\Facades\DataTables;
class JournalInfoController extends Controller
{
    public function index()
    {
        return view('backend.journal_info.index');
    }

    public function fetch(Request $request)
    {
        if ($request->ajax()) {
            $data = JournalInfo::orderBy('serial', '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 Journal Info')) {
                        $btn .= '<button onclick="editJournalInfo(' . $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 Journal Info')) {
                        $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)
    {
        $request->validate(['title' => 'required', 'serial' => 'required|integer']);
        JournalInfo::updateOrCreate(['id' => $request->id], $request->all());
        return response()->json(['success' => 'Journal Info saved successfully!']);
    }

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

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