<?php

namespace App\Controllers\Api;

use App\Models\ProviderModel;
use App\Models\InventoryModel;

class ProvidersController extends BaseApiController
{
    /**
     * GET api/providers?type=fuel|gas - list providers by type (with prices from inventory)
     */
    public function index()
    {
        $type = $this->request->getGet('type');
        $allowed = ['fuel', 'gas'];
        if ($type !== null && ! in_array($type, $allowed, true)) {
            return $this->error('Invalid type', 400);
        }
        $providerModel = model(ProviderModel::class);
        $q = $providerModel->select('providers.*');
        if ($type !== null) {
            $q->where('provider_type', $type);
        }
        $providers = $q->findAll();
        $inventoryModel = model(InventoryModel::class);
        $data = [];
        foreach ($providers as $p) {
            $items = $inventoryModel->where('provider_id', $p->id)->findAll();
            $data[] = [
                'id'       => (int) $p->id,
                'name'     => $p->name,
                'type'     => $p->provider_type ?? 'fuel',
                'logo_url' => isset($p->logo_url) && $p->logo_url !== '' ? $p->logo_url : null,
                'items'    => array_map(static function ($i) {
                    return [
                        'id'         => (int) $i->id,
                        'item_name'  => $i->item_name,
                        'price'      => (float) $i->price,
                        'item_type'  => $i->item_type ?? 'fuel',
                    ];
                }, $items),
            ];
        }
        return $this->success($data);
    }
}
