<?php

namespace BookneticApp\Backend\Services;

use BookneticApp\Models\Service;
use BookneticApp\Models\ServiceCategory;
use BookneticApp\Providers\Core\Capabilities;
use BookneticApp\Providers\Helpers\Helper;
use BookneticApp\Providers\Request\Post;
use BookneticApp\Providers\UI\DataTableUI;

class ServiceCategoryController extends \BookneticApp\Providers\Core\Controller
{
    public function index()
    {
        Capabilities::must('service_categories');

        $query = ServiceCategory::noTenant()
            ->leftJoinSelf(
                'parent_category',
                ['name'],
                ServiceCategory::getField('parent_id'),
                'parent_category.id'
            )
            ->select([
                ServiceCategory::getField('id'),
                ServiceCategory::getField('name'),
                ServiceCategory::getField('parent_id AS parent'),
                'parent_category.name AS parent_name'
            ]);

        $dataTable = new DataTableUI($query);

        $dataTable
            ->setIdFieldForQuery('id')
            ->setTitle(bkntc__('Service Categories'))
            ->addColumns(bkntc__('ID'), 'id')
            ->addColumns(bkntc__('Category Name'), 'name')
            ->addColumns(bkntc__('Parent Category'), 'parent_name')
            ->addNewBtn(bkntc__('ADD Category'))
            ->addAction('edit', bkntc__('Edit'))
            ->addAction('delete', bkntc__('Delete'), [ $this, '_delete' ]);

        $dataTable->searchBy([ServiceCategory::getField('name'), 'parent_category.name']);

        $this->view('service-category', [
            'table' => $dataTable->renderHTML()
        ]);
    }

    public static function _delete()
    {
        Capabilities::must('services_delete_category');

        $ids = Post::array('ids');

        if (empty($ids) || ! is_array($ids)) {
            Helper::response(false, bkntc__('No Category is selected'));
            return;
        }

        $existSubCategory = ServiceCategory::where('parent_id', 'IN', $ids)->count();

        if ($existSubCategory != 0) {
            Helper::response(false, bkntc__('Firstly remove sub categories!'));
            return;
        }

        $services = Service::where('category_id', 'IN', $ids)->count();

        if ($services != 0) {
            Helper::response(false, bkntc__('There are some services in this category.'));
            return;
        }

        ServiceCategory::where('id', 'IN', $ids)->delete();
    }
}
