<?php

namespace App\Http\Controllers\Admin;


use App\Models\Subcategory;
use App\Models\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Rules\FileTypeValidate;

class SubcategoryController extends Controller
{
    public function index()
    {
        $pageTitle  = 'All Subcategories';
        $categories = Category::active()->orderBy('name')->get();
        $subcategories  = Subcategory::with('category', 'cards')->searchable(['name'])->orderBy('name')->paginate(getPaginate());
        return view('admin.subcategory.index', compact('pageTitle', 'categories', 'subcategories'));
    }

    public function store(Request $request, $id = 0)
    {
        $imageValidation = $id ? 'nullable' : 'required';

        $request->validate([
            'category_id' => 'required|exists:categories,id',
            'name'        => 'required|unique:subcategories,name,' . $id,
            'price'       => 'required|numeric|gt:0',
            'image'       => ["$imageValidation", new FileTypeValidate(['jpg', 'jpeg', 'png'])],
        ]);

        if ($id) {
            $subcategory           = Subcategory::findOrFail($id);
            $notification       = 'Subcategory updated successfully';
        } else {
            $subcategory           = new Subcategory();
            $notification       = 'Subcategory added successfully';
        }

        if ($request->hasFile('image')) {
            try {
                $old = @$subcategory->image;
                $subcategory->image = fileUploader($request->image, getFilePath('subcategory'), getFileSize('subcategory'), $old);
            } catch (\Exception $exp) {
                $notify[] = ['error', 'Couldn\'t upload subcategory image'];
                return back()->withNotify($notify);
            }
        }

        $subcategory->category_id = $request->category_id;
        $subcategory->name = $request->name;
        $subcategory->price = $request->price;
        $subcategory->save();

        $notify[] = ['success', $notification];
        return back()->withNotify($notify);
    }

    public function status($id)
    {
        return Category::changeStatus($id);
    }

    public function featured($id)
    {
        return Category::changeStatus($id, 'featured');
    }
}
