<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Category;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use DataTables;

class CategoryController extends Controller
{
    protected $user;

    public function __construct()
    {
        $this->user = Auth::guard('admin')->user();
    }

    public function index(Request $request) {
        if (is_null($this->user) || !$this->user->can('category.view')) {
            abort(403, 'Access Denied: You do not have permission to view categories.');
        }

        $headerTitle = 'Category List';

        if ($request->ajax()) {
            $query = Category::latest();

            return DataTables::of($query)
                        ->editColumn('status', function($category) {
                            return $category->status === 0 
                                ? '<span class="badge badge-success">Active</span>' 
                                : '<span class="badge badge-secondary">Inactive</span>';
                        })
                        ->addColumn('actions', function($category) {
                            return view('backend.admin.categories.partials.actions', compact('category'))->render();
                        })
                        ->rawColumns(['status', 'actions'])
                        ->make(true);
        }

        return view('backend.admin.categories.index', compact('headerTitle'));
    }

    public function add(Request $request) {
        if (is_null($this->user) || !$this->user->can('category.create')) {
            return back()->with('error', 'Access Denied: You do not have permission to create new category.');
        }

        $request->validate([
            'name' => 'required|string|max:255',
            'icon' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        $iconUrl = $this->handleUploadedFile($request->file('icon'));

        $category = new Category;
        $category->name = $request->name;
        $category->icon = $iconUrl; 
        $category->save();

        return redirect()->back()->with(['success' => 'Category added successfully']);
    }

    public function getCategoryById($id) {
        if (is_null($this->user) || !$this->user->can('category.edit')) {
            abort(403, 'Access Denied: You do not have permission to view category details.');
        }

        $category = Category::findOrFail($id);

        return response()->json($category);
    }

    public function update(Request $request) {
        if (is_null($this->user) || !$this->user->can('category.edit')) {
            return back()->with('error', 'Access Denied: You do not have permission to edit category.');
        }

        $request->validate([
            'name' => 'required|string|max:255',
            'icon' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048',
        ]);

        $category = Category::find($request->category_id);

        if ($request->hasFile('icon')) {
            if ($category->icon && file_exists(public_path($category->icon))) {
                unlink(public_path($category->icon));
            } 

            $iconUrl = $this->handleUploadedFile($request->file('icon'));
            $category->icon = $iconUrl;
        }

        $category->name = $request->name;
        $category->status = $request->status;
        $category->save();

        return redirect()->back()->with(['success' => 'Category successfully updated']);
    }

    public function delete($id)
    {
        if (is_null($this->user) || !$this->user->can('category.delete')) {
            return back()->with('error', 'Access Denied: You do not have permission to delete category.');
        }

        $category = Category::find($id);

        if (empty($category)) {
            abort(404);  
        }

        $category->delete();

        if ($category->icon && file_exists(public_path($category->icon))) {
            unlink(public_path($category->icon));
        } 

        return redirect()->back()->with(['success' => 'Category successfully deleted']);
    }

    private function handleUploadedFile($file) {
        if ($file && $file->isValid()) {
            $directory = 'assets/uploads/categories/';
            $fileName = Str::uuid() . '.' . $file->getClientOriginalExtension();
            $file->move(public_path($directory), $fileName);
            return $directory . $fileName;
        }
        return null;
    }
}
