<?php

namespace App\Controllers;

use App\Models\RewarderServiceCategoryModel;
use App\Models\RewarderShopModel;

class RewarderServiceCategories extends AdminBaseController
{
    public $title = 'Service Categories';
    public $menu = 'rewarder';
    public $submenu = 'rewarder_service_categories';

    public function index()
    {
        if (\is_logged() && !(hasPermissions('shop_services_manage') || hasPermissions('shop_service_categories_view'))) {
            $this->response->redirect('/errors/denied');
        }

        $q = db_connect()->table('rewarder_service_categories c')
            ->select('c.*, sh.name as shop_name')
            ->join('rewarder_shops sh', 'sh.id = c.shop_id', 'left')
            ->orderBy('c.id', 'desc');

        if (is_role('Shopkeeper')) {
            $shopId = shopkeeper_shop_id();
            $q->where('c.shop_id', (int) $shopId);
        }

        $rows = $q->get()->getResult();

        return view('admin/rewarder/service_categories/list', compact('rows'));
    }

    public function view($id)
    {
        if (\is_logged() && !(hasPermissions('shop_services_manage') || hasPermissions('shop_service_categories_view'))) {
            $this->response->redirect('/errors/denied');
        }

        $q = db_connect()->table('rewarder_service_categories c')
            ->select('c.*, sh.name as shop_name')
            ->join('rewarder_shops sh', 'sh.id = c.shop_id', 'left')
            ->where('c.id', (int) $id);

        if (is_role('Shopkeeper')) {
            $shopId = shopkeeper_shop_id();
            $q->where('c.shop_id', (int) $shopId);
        }

        $category = $q->get()->getRow();
        if (!$category) {
            return redirect()->to('rewarderServiceCategories')->with('notifyError', 'Category not found');
        }

        return view('admin/rewarder/service_categories/view', compact('category'));
    }

    public function add()
    {
        $this->permissionCheck('shop_services_manage');
        if (is_role('Shopkeeper')) {
            $shopId = shopkeeper_shop_id();
            if (!$shopId) {
                return redirect()->to('rewarderServiceCategories')->with('notifyError', 'No shop assigned');
            }
            $shops = (new RewarderShopModel())->where('id', (int) $shopId)->orderBy('name', 'asc')->findAll();
        } else {
            $shops = (new RewarderShopModel())->orderBy('name', 'asc')->findAll();
        }
        return view('admin/rewarder/service_categories/add', compact('shops'));
    }

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

        $shopId = is_role('Shopkeeper') ? shopkeeper_shop_id() : (int) post('shop_id');
        if (!$shopId) {
            return redirect()->back()->with('notifyError', 'No shop assigned')->withInput();
        }

        $id = (new RewarderServiceCategoryModel())->create([
            'shop_id' => (int) $shopId,
            'name' => post('name'),
            'status' => (int) post('status'),
        ]);

        $ext = uploadPublicImage('image', 'service_categories', (string) $id);
        if ($ext) {
            (new RewarderServiceCategoryModel())->update($id, ['img_type' => $ext]);
        }

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

    public function edit($id)
    {
        $this->permissionCheck('shop_services_manage');
        if (is_role('Shopkeeper')) {
            $shopId = shopkeeper_shop_id();
            $category = (new RewarderServiceCategoryModel())->where(['id' => $id, 'shop_id' => $shopId])->first();
            if (!$category) {
                return redirect()->to('rewarderServiceCategories')->with('notifyError', 'Category not found');
            }
            $shops = $shopId ? (new RewarderShopModel())->where('id', (int) $shopId)->orderBy('name', 'asc')->findAll() : [];
        } else {
            $category = (new RewarderServiceCategoryModel())->getById($id);
            $shops = (new RewarderShopModel())->orderBy('name', 'asc')->findAll();
        }
        return view('admin/rewarder/service_categories/edit', compact('category', 'shops'));
    }

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

        $shopId = is_role('Shopkeeper') ? shopkeeper_shop_id() : (int) post('shop_id');
        if (!$shopId) {
            return redirect()->back()->with('notifyError', 'No shop assigned')->withInput();
        }

        $data = [
            'shop_id' => (int) $shopId,
            'name' => post('name'),
            'status' => (int) post('status'),
        ];

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

        $m = new RewarderServiceCategoryModel();
        if (is_role('Shopkeeper')) {
            $m->where(['id' => $id, 'shop_id' => (int) $shopId])->set($data)->update();
        } else {
            $m->update($id, $data);
        }

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

    public function delete($id)
    {
        $this->permissionCheck('shop_services_manage');
        if (is_role('Shopkeeper')) {
            $shopId = shopkeeper_shop_id();
            (new RewarderServiceCategoryModel())->where(['id' => $id, 'shop_id' => (int) $shopId])->delete();
        } else {
            (new RewarderServiceCategoryModel())->delete($id);
        }
        return redirect()->to('rewarderServiceCategories')->with('notifySuccess', 'Category deleted');
    }
}

