<?php

namespace Soft_Tehnica\Freya_Sync_Service\Services;

use Soft_Tehnica\Freya_Sync_Service\Data\FSSResponse;
use wpdb;

class LocationService
{
    static LocationService $instance;

    public function getAvaliableLocations(bool $fromApi): array
    {
        if (!$fromApi) {
            return $this->getLocalLocations();
        } else {
            return $this->getApiLocations();
        }
    }

    private function getLocalLocations(): array
    {
        /** @var wpdb $wpdb */
        global $wpdb;
        return $wpdb->get_results(
            "SELECT DISTINCT name.meta_value AS name, uid.meta_value AS uid FROM $wpdb->postmeta uid
            INNER JOIN $wpdb->postmeta name
            WHERE uid.post_id = name.post_id
            AND uid.meta_key = 'location_uid'
            AND name.meta_key = 'location_name'",
            ARRAY_A
        );
    }

    private function fetchLocations(int $page = 1): FSSResponse
    {
        $companyUid = PluginSettings::get()->getCompanyUid();
        return makeHttpGet("api/wp/locations?page=$page&companyUid=$companyUid");
    }

    private function getApiLocations(): array
    {
        $ret = [];
        $page = 0;
        do {
            $page++;
            $res = $this->fetchLocations($page);
            if (!$res->status) {
                break;
            }
            foreach ($res->payload->data as $location) {
                $ret[] = [
                    'name' => $location->name,
                    'uid' => $location->uid
                ];
            }
        } while ($page !== $res->payload->last_page);
        return $ret;
    }

    public static function get(): LocationService
    {
        if (!isset(static::$instance)) {
            static::$instance = new LocationService();
        }
        return static::$instance;
    }
}