<?php

namespace App\Controllers;

use App\Models\RewarderShopCategoryModel;
use App\Models\RewarderShopModel;

class RewarderShopCategories extends AdminBaseController
{
    public $title = 'Shop Categories';
    public $menu = 'rewarder';
    public $submenu = 'rewarder_shop_categories';

    public function index()
    {
        $this->permissionCheck('shop_categories_manage');
        $rows = (new RewarderShopCategoryModel())->orderBy('name', 'asc')->findAll();
        return view('admin/rewarder/shop_categories/list', compact('rows'));
    }

    public function add()
    {
        $this->permissionCheck('shop_categories_manage');
        return view('admin/rewarder/shop_categories/add');
    }

    public function save()
    {
        $this->permissionCheck('shop_categories_manage');
        postAllowed();

        $id = (new RewarderShopCategoryModel())->create([
            'name' => trim((string) post('name')),
            'status' => (int) post('status'),
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        $ext = uploadPublicImage('icon', 'shop_categories', (string) $id);
        if ($ext) {
            (new RewarderShopCategoryModel())->update($id, ['img_type' => $ext]);
        }

        return redirect()->to('rewarderShopCategories')->with('notifySuccess', 'Category created');
    }

    public function edit($id)
    {
        $this->permissionCheck('shop_categories_manage');
        $category = (new RewarderShopCategoryModel())->getById($id);
        return view('admin/rewarder/shop_categories/edit', compact('category'));
    }

    public function update($id)
    {
        $this->permissionCheck('shop_categories_manage');
        postAllowed();

        $data = [
            'name' => trim((string) post('name')),
            'status' => (int) post('status'),
            'updated_at' => date('Y-m-d H:i:s'),
        ];

        $ext = uploadPublicImage('icon', 'shop_categories', (string) $id);
        if ($ext) {
            $data['img_type'] = $ext;
        }

        (new RewarderShopCategoryModel())->update($id, $data);

        return redirect()->to('rewarderShopCategories')->with('notifySuccess', 'Category updated');
    }

    public function delete($id)
    {
        $this->permissionCheck('shop_categories_manage');

        $inUse = (new RewarderShopModel())->where('category_id', (int) $id)->countAllResults();
        if ($inUse > 0) {
            return redirect()->to('rewarderShopCategories')->with('notifyError', 'Category is used by shops and cannot be deleted');
        }

        (new RewarderShopCategoryModel())->delete($id);
        return redirect()->to('rewarderShopCategories')->with('notifySuccess', 'Category deleted');
    }
}

