<?php
namespace App\Controllers\Admin;

use Core\Request;
use Core\Response;
use Core\View;
use App\Models\Category;

class CategoryController
{
    public function index()
    {
        View::make('admin/categories')
            ->setLayout('admin_layout')
            ->with([
                'title' => 'Manage Categories',
                'categories' => Category::all()
            ])->render();
    }

    public function store()
    {
        $data = Request::all();
        if(empty($data['name'])) return Response::json(['status'=>'error', 'message'=>'Name is required']);
        
        Category::create(['name' => $data['name'], 'description' => $data['description'] ?? '']);
        return Response::json(['status' => 'success', 'message' => 'Category added.']);
    }

    public function update($id)
    {
        $data = Request::all();
        Category::update($id, ['name' => $data['name'], 'description' => $data['description']]);
        return Response::json(['status' => 'success', 'message' => 'Category updated.']);
    }

    public function destroy($id)
    {
        Category::delete($id);
        return Response::json(['status' => 'success', 'message' => 'Category deleted.']);
    }
}