<?php

namespace App\Controllers\Api;

use App\Models\ShopCategoryModel;
use App\Models\InventoryModel;

class ShopController extends BaseApiController
{
    /**
     * GET api/shop/categories - list shop categories (Gas accessories, Car accessories, Lubricants)
     */
    public function categories()
    {
        $model = model(ShopCategoryModel::class);
        $list  = $model->findAll();
        $data  = array_map(static function ($row) {
            return [
                'id'   => (int) $row->id,
                'name' => $row->name,
            ];
        }, $list);
        return $this->success($data);
    }

    /**
     * GET api/shop/products - list shop products; optional ?category_id=
     */
    public function products()
    {
        $categoryId = $this->request->getGet('category_id');
        $inv = model(InventoryModel::class);
        $inv->where('item_type', 'shop');
        if ($categoryId !== null && $categoryId !== '') {
            $inv->where('category_id', (int) $categoryId);
        }
        $rows = $inv->findAll();
        $data = array_map(static function ($r) {
            return [
                'id'          => (int) $r->id,
                'category_id' => $r->category_id ? (int) $r->category_id : null,
                'item_name'   => $r->item_name,
                'price'       => (float) $r->price,
                'stock_count' => (int) $r->stock_count,
                'image_url'   => isset($r->image_url) && $r->image_url !== '' ? $r->image_url : null,
            ];
        }, $rows);
        return $this->success($data);
    }
}
