<?php

namespace App\Http\Controllers\Backend;

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

class EditorialBoardController extends Controller
{
    public function index()
    {
        $categories = EditorialCategory::where('status', '1')->get();
        return view('backend.editorial_board.index', compact('categories'));
    }

    public function fetch(Request $request)
    {
        if ($request->ajax()) {
            $data = EditorialBoard::with('category')->latest()->get();
            $user = auth()->user(); // Get authenticated user

            return DataTables::of($data)
                ->addIndexColumn()
                ->addColumn('photo', function ($row) {
                    return $row->photo
                        ? '<img src="/' . $row->photo . '" width="50" height="50" style="border-radius:50%; object-fit:cover;">'
                        : 'No Image';
                })
                ->addColumn('category', function ($row) {
                    return $row->category ? $row->category->name : 'N/A';
                })
                ->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 Editorial Board')) {
                        $btn .= '<button onclick="editMember(' . $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 Editorial Board')) {
                        $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(['photo', 'status', 'action'])
                ->make(true);
        }
    }

    public function store(Request $request)
    {
        $request->validate([
            'category_id' => 'required',
            'name' => 'required',
            'photo' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $data = $request->except('_token', 'photo');

        if ($request->hasFile('photo')) {
            $imageName = time() . '.' . $request->photo->extension();
            $request->photo->move(public_path('uploads/editorial_board'), $imageName);
            $data['photo'] = 'uploads/editorial_board/' . $imageName;
        }

        if ($request->member_id) {
            $member = EditorialBoard::find($request->member_id);
            if ($request->hasFile('photo') && $member->photo && File::exists(public_path($member->photo))) {
                File::delete(public_path($member->photo));
            }
            $member->update($data);
        } else {
            EditorialBoard::create($data);
        }

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

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

    public function destroy($id)
    {
        $member = EditorialBoard::findOrFail($id);
        if ($member->photo && File::exists(public_path($member->photo))) {
            File::delete(public_path($member->photo));
        }
        $member->delete();
        return response()->json(['success' => 'Deleted successfully!']);
    }
}
