<?php

function bid_control_file_path(): string
{
    return __DIR__ . '/../bid-control/bids.json';
}

function bid_load_rules(): array
{
    $file = bid_control_file_path();

    if (!file_exists($file)) {
        return [];
    }

    $json = @file_get_contents($file);
    $data = json_decode($json, true);

    return is_array($data) ? $data : [];
}

function bid_save_rules(array $rules): bool
{
    $file = bid_control_file_path();
    $dir  = dirname($file);

    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
    }

    return (bool)@file_put_contents($file, json_encode($rules, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}

function bid_get_rule(string $vertical): array
{
    $rules = bid_load_rules();

    if (!isset($rules[$vertical]) || !is_array($rules[$vertical])) {
        return [
            'enabled' => true,
            'min_bid' => 0,
        ];
    }

    return [
        'enabled' => isset($rules[$vertical]['enabled']) ? (bool)$rules[$vertical]['enabled'] : true,
        'min_bid' => isset($rules[$vertical]['min_bid']) ? (float)$rules[$vertical]['min_bid'] : 0,
    ];
}

function bid_is_allowed(string $vertical, float $bid): array
{
    $rule = bid_get_rule($vertical);

    if (!$rule['enabled']) {
        return [
            'allowed' => true,
            'reason'  => 'bid_control_disabled',
            'rule'    => $rule,
        ];
    }

    if ($rule['min_bid'] <= 0) {
        return [
            'allowed' => true,
            'reason'  => 'no_min_bid',
            'rule'    => $rule,
        ];
    }

    if ($bid >= $rule['min_bid']) {
        return [
            'allowed' => true,
            'reason'  => 'meets_threshold',
            'rule'    => $rule,
        ];
    }

    return [
        'allowed' => false,
        'reason'  => 'low_bid',
        'rule'    => $rule,
    ];
}

function bid_get_all_verticals_from_config(array $config): array
{
    $verticals = array_keys($config['verticals'] ?? []);
    sort($verticals);
    return $verticals;
}