<?php

namespace App\Controllers\Api\Admin;

use App\Models\RewarderServiceCategoryModel;
use CodeIgniter\HTTP\ResponseInterface;

class ServiceCategories extends BaseAdminApiController
{
    public function index(): ResponseInterface
    {
        if ($resp = $this->requirePermission(['shop_services_manage', 'shop_service_categories_view'])) {
            return $resp;
        }

        $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');

        $shopId = $this->isShopkeeper() ? $this->shopkeeperShopId() : null;
        if ($shopId) {
            $q->where('c.shop_id', (int) $shopId);
        } else {
            $filterShopId = $this->request->getGet('shop_id');
            if ($filterShopId !== null && $filterShopId !== '') {
                $q->where('c.shop_id', (int) $filterShopId);
            }
        }

        $rows = $q->get()->getResult();
        foreach ($rows as $r) {
            $r->image_url = !empty($r->img_type) ? urlUpload('service_categories/' . $r->id . '.' . $r->img_type, true) : null;
        }

        return $this->ok($rows);
    }

    public function show(int $id): ResponseInterface
    {
        if ($resp = $this->requirePermission(['shop_services_manage', 'shop_service_categories_view'])) {
            return $resp;
        }

        $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', $id);

        $shopId = $this->isShopkeeper() ? $this->shopkeeperShopId() : null;
        if ($shopId) {
            $q->where('c.shop_id', (int) $shopId);
        }

        $row = $q->get()->getRow();
        if (!$row) {
            return $this->fail('Not found', 404);
        }
        $row->image_url = !empty($row->img_type) ? urlUpload('service_categories/' . $row->id . '.' . $row->img_type, true) : null;

        return $this->ok($row);
    }

    public function create(): ResponseInterface
    {
        if ($resp = $this->requirePermission('shop_services_manage')) {
            return $resp;
        }

        $name = trim((string) $this->input('name', ''));
        if ($name === '') {
            return $this->fail('Validation failed', 422, ['name' => 'Name is required']);
        }

        $shopId = $this->isShopkeeper() ? $this->shopkeeperShopId() : (int) $this->input('shop_id', 0);
        if (!$shopId) {
            return $this->fail('Validation failed', 422, ['shop_id' => 'Shop is required']);
        }

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

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

        $row = (new RewarderServiceCategoryModel())->getById($id);
        if ($row) {
            $row->image_url = !empty($row->img_type) ? urlUpload('service_categories/' . $row->id . '.' . $row->img_type, true) : null;
        }

        return $this->ok($row, [], 201);
    }

    public function update(int $id): ResponseInterface
    {
        if ($resp = $this->requirePermission('shop_services_manage')) {
            return $resp;
        }

        $m = new RewarderServiceCategoryModel();

        $shopId = $this->isShopkeeper() ? $this->shopkeeperShopId() : (int) $this->input('shop_id', 0);
        if (!$shopId) {
            return $this->fail('Validation failed', 422, ['shop_id' => 'Shop is required']);
        }

        if ($this->isShopkeeper()) {
            $exists = $m->where(['id' => $id, 'shop_id' => (int) $shopId])->first();
            if (!$exists) {
                return $this->fail('Not found', 404);
            }
        }

        $name = trim((string) $this->input('name', ''));
        if ($name === '') {
            return $this->fail('Validation failed', 422, ['name' => 'Name is required']);
        }

        $data = [
            'shop_id' => (int) $shopId,
            'name' => $name,
            'status' => (int) $this->input('status', 1),
        ];

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

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

        $row = $m->getById($id);
        if ($row) {
            $row->image_url = !empty($row->img_type) ? urlUpload('service_categories/' . $row->id . '.' . $row->img_type, true) : null;
        }

        return $this->ok($row);
    }

    public function delete(int $id): ResponseInterface
    {
        if ($resp = $this->requirePermission('shop_services_manage')) {
            return $resp;
        }

        $m = new RewarderServiceCategoryModel();
        if ($this->isShopkeeper()) {
            $shopId = $this->shopkeeperShopId();
            if (!$shopId) {
                return $this->fail('Shop not found', 422);
            }
            $m->where(['id' => $id, 'shop_id' => (int) $shopId])->delete();
        } else {
            $m->delete($id);
        }

        return $this->ok(true);
    }
}
