<?php
require_once __DIR__ . '/../config/user_functions.php';

if (!function_exists('orders_file_path')) {
    function orders_file_path() {
        return __DIR__ . '/orders.json';
    }

    function clients_file_path() {
        return __DIR__ . '/clients.json';
    }

    function products_file_path() {
        return __DIR__ . '/products.json';
    }

    function load_json_array($path) {
        if (!file_exists($path)) {
            file_put_contents($path, json_encode([], JSON_PRETTY_PRINT));
        }
        $data = json_decode(file_get_contents($path), true);
        if (!is_array($data)) $data = [];
        return $data;
    }

    function save_json_array($path, array $data) {
        file_put_contents($path, json_encode(array_values($data), JSON_PRETTY_PRINT));
    }

    function load_orders() {
        return load_json_array(orders_file_path());
    }

    function save_orders(array $orders) {
        save_json_array(orders_file_path(), $orders);
    }

    function load_clients() {
        return load_json_array(clients_file_path());
    }

    function save_clients(array $clients) {
        $out = [];
        foreach ($clients as $c) {
            if (is_string($c)) {
                $out[] = $c;
            } elseif (is_array($c) && isset($c['name'])) {
                $out[] = $c['name'];
            }
        }
        save_json_array(clients_file_path(), $out);
    }

    function load_products() {
        return load_json_array(products_file_path());
    }

    function save_products(array $products) {
        $out = [];
        foreach ($products as $p) {
            if (is_string($p)) {
                $out[] = $p;
            } elseif (is_array($p) && isset($p['name'])) {
                $out[] = $p['name'];
            }
        }
        save_json_array(products_file_path(), $out);
    }

    function find_order_by_id(array $orders, $id) {
        foreach ($orders as $idx => $o) {
            if ((int)($o['id'] ?? 0) === (int)$id) {
                return [$idx, $o];
            }
        }
        return [null, null];
    }
}
?>