<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class CategoryController extends Controller
{
    function index()
    {
        return view('admin.category.index');
    }

    function create()
    {
        return view('admin.category.create');
    }

    function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
        ]);

        $date = Carbon::now();
        
        $image = '';
        
        if($request->has('image')) {
            $image = "categories/" . $date->format('Y/m/');
            $file  = $request->file('image');
            $name = Str::slug($request->name) . '.' . $file->extension();
            $file->move($image, $name);
            $image .= $name;
        }

        

        Category::create([
            'name' => $request->name,
            'thumbnail' => $image,
        ]);

        return redirect()
            ->route('categories.index')
            ->with('type', 'success')
            ->with('message', 'Category created successfully');
    }

    function edit(Request $request, Category $category)
    {
        return view('admin.category.edit', compact('category'));
    }

    function update(Request $request, Category $category)
    {
        $request->validate([
            'name' => 'required',
        ]);

        $date = Carbon::now();

        $image = $category->thumbnail;

        if ($request->has('image')) {
            if(file_exists($category->thumbnail)) {
                unlink($category->thumbnail);
            }
            
            $image = "categories/" . $date->format('Y/m/');
            $file  = $request->file('image');
            $name = Str::slug($request->name) . '.' . $file->extension();
            $file->move($image, $name);
            $image .= $name;
        }

        $category->update([
            'name' => $request->name,
            'description' => $request->description,
            'thumbnail' => $image,
        ]);

        return redirect()
            ->route('categories.index')
            ->with('type', 'success')
            ->with('message', 'Category updated successfully');
    }

    function show(Category $category)
    {
        return view('admin.category.edit', compact('category'));
    }


    function destroy(Category $category)
    {
        $category->delete();
        return redirect()
            ->route('categories.index')
            ->with('success', 'Category deleted successfully');
    }

    public function list(Request $request)
    {
        $data['draw'] = $request->draw;
        $query = Category::query();
        $data['recordsFiltered'] =  $data['recordsTotal'] = $query->count();
        $query->select([
            'id',
            'name',
            'thumbnail',
        ]);

        if ($request->search['value'] != '') {
            $search = $request->search['value'];
            $query->where(function ($query) use ($search) {
                $query->where('name', 'like', "%{$search}%");
            });

            $data['recordsFiltered'] = $query->count();
        }

        $query->offset($request->start ?? 0)
            ->limit($request->length ?? 10)
            ->orderBy('created_at', 'desc');

        $data['data'] = $query->get()->map(function ($e) {
            $routeEdit = route('categories.edit', ['category' => $e->id]);
            $routeDelete = route('categories.destroy', ['category' => $e->id]);
            $image = strlen($e->thumbnail) > 0 ? url($e->thumbnail) : '';
            return [
                'name' => $e->name ?? '',
                'thumbnail' => (empty($image)) ?  '-' :  "<img src='$image' class='img img-responsive' style='width: 150px;height:100px'>",
                'action' => "<a href='$routeEdit' class='btn btn-sm btn-warning '>
                                Edit
                            </a>
                                <a href='$routeDelete' class='btn btn-sm btn-danger item_delete'>
                                Delete
                            </a>"
            ];
        });

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