<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Backend\Journal;
use Illuminate\Support\Facades\File;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Database\QueryException;
class JournalController extends Controller
{
    public function index()
    {
        return view('backend.journal.index');
    }

    public function fetch(Request $request)
    {
        if ($request->ajax()) {
            $data = Journal::latest()->get();
            $user = auth()->user(); // বর্তমান ইউজারের অবজেক্ট

            return DataTables::of($data)
                ->addIndexColumn()
                ->addColumn('cover_image', function ($row) {
                    if ($row->cover_image) {
                        return '<img src="/' . $row->cover_image . '" width="60" height="70" style="object-fit:cover; border-radius:4px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">';
                    }
                    return '<span class="text-muted">No Image</span>';
                })
                ->addColumn('status', function ($row) {
                    // Check mark for active, Cross mark for inactive
                    return $row->status == '1'
                        ? '<i class="feather feather-check-circle text-success" style="font-size: 24px;"></i>'
                        : '<i class="feather feather-x-circle text-danger" style="font-size: 24px;"></i>';
                })
                ->addColumn('action', function ($row) use ($user) {
                    $btn = '';

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

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

                    // ৩. যদি কোনো পারমিশন না থাকে
                    if (empty($btn)) {
                        return '<span class="badge badge-light text-muted">No Action</span>';
                    }

                    return $btn;
                })
                ->rawColumns(['cover_image', 'status', 'action'])
                ->make(true);
        }
    }

    public function store(Request $request)
    {
        $request->validate([
            'volume' => 'required',
            'issue' => 'required',
            'link' => 'required|url',
            'cover_image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

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

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

        // Only one active journal allowed
        if ($request->status == '1') {
            Journal::query()->update(['status' => '0']);
        }

        Journal::create($data);

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

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

    public function update(Request $request, $id)
    {
        $journal = Journal::findOrFail($id);

        $request->validate([
            'volume' => 'required',
            'issue' => 'required',
            'link' => 'required|url',
            'cover_image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

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

        if ($request->hasFile('cover_image')) {
            if ($journal->cover_image && File::exists(public_path($journal->cover_image))) {
                File::delete(public_path($journal->cover_image));
            }
            $imageName = time() . '.' . $request->cover_image->extension();
            $request->cover_image->move(public_path('uploads/journals'), $imageName);
            $data['cover_image'] = 'uploads/journals/' . $imageName;
        }

        // Only one active journal allowed
        if ($request->status == '1') {
            Journal::where('id', '!=', $id)->update(['status' => '0']);
        }

        $journal->update($data);

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


    public function destroy($id)
    {
        try {
            $journal = Journal::findOrFail($id);

            // ১. ছবি সঠিকভাবে ডিলিট করার লজিক (ltrim ব্যবহার করা হয়েছে যাতে শুরুতেই / থাকলে সমস্যা না হয়)
            if ($journal->cover_image) {
                $relativePath = ltrim($journal->cover_image, '/');
                $fullPath = public_path($relativePath);

                if (File::exists($fullPath)) {
                    File::delete($fullPath);
                }
            }

            // ২. ডাটাবেস থেকে ডিলিট
            $journal->delete();

            return response()->json([
                'success' => 'Journal deleted successfully!'
            ]);

        } catch (QueryException $e) {
            // ফরেন কি/ডাটাবেস কনস্ট্রেইন্ট এরর ধরবে
            return response()->json([
                'error' => 'Cannot delete journal! It is connected to other records.'
            ], 422);

        } catch (\Exception $e) {
            // অন্যান্য যেকোনো এরর ধরবে
            return response()->json([
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
