<?php

namespace App\Controllers\Api;

use App\Models\SettingModel;

class ConfigController extends BaseApiController
{
    /**
     * GET api/config
     * Returns service_fee and fuel ticker data for payment overview / dashboard.
     */
    public function index()
    {
        $settings = model(SettingModel::class);
        $serviceFee = $settings->getValue('service_fee');
        if ($serviceFee === null) {
            $serviceFee = '0';
        }
        $deliveryFee = $settings->getValue('delivery_fee');
        if ($deliveryFee === null) {
            $deliveryFee = '0';
        }

        // Ticker: fuel prices from inventory (e.g. provider + item_name + price)
        $db = \Config\Database::connect();
        $items = $db->table('inventory')
            ->select('inventory.*, providers.name as provider_name')
            ->join('providers', 'providers.id = inventory.provider_id')
            ->get()
            ->getResult();
        $ticker = [];
        foreach ($items as $row) {
            $ticker[] = [
                'provider' => $row->provider_name ?? 'Provider',
                'item'     => $row->item_name,
                'price'    => (float) $row->price,
                'currency' => 'UGX',
            ];
        }

        return $this->success([
            'service_fee'   => (float) $serviceFee,
            'delivery_fee'  => (float) $deliveryFee,
            'ticker'        => $ticker,
        ]);
    }
}
