<?php

/**
 * Sync for Hub Accounts.
 *
 * @package northmill-online-shared
 */
declare (strict_types=1);
namespace Northmill_Online_Shared_Sync\Northmill_Online_Shared\Abstracts\Hub_API\Hub_Accounts;

use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Abstracts\Hub_API\API;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Abstracts\Hub_API\Hub_Accounts\Models\Hub_Account_Model;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Helpers\Time_Helpers;
defined('ABSPATH') || exit;
/**
 * Sync class.
 */
class Sync
{
    /**
     * Syncs Hub account settings to CPT
     *
     * @param Hub_Account_Model $account The account to sync.
     * @param string|null       $action  The action to perform. Can be 'create' or 'update'.
     *
     * @return bool True if the sync was successful, false otherwise.
     */
    public static function sync_and_store(Hub_Account_Model $account, ?string $action): bool
    {
        $api = new API($account);
        $store_settings = $api->get_store_settings();
        if (!empty($store_settings->Settings)) {
            return (bool) self::process_pulled_backoffice_account($account, $store_settings->Settings, $action);
        } else {
            $invalid_accounts = Invalid_Hub_Accounts::get_invalid_accounts();
            $invalid_accounts[] = $account;
            Invalid_Hub_Accounts::update_invalid_accounts($invalid_accounts);
            return (bool) self::process_pulled_backoffice_account($account, null, $action);
        }
    }
    /**
     * Processes the pulled Hub account
     *
     * @param Hub_Account_Model $account  The Hub account to update.
     * @param ?Object           $settings The settings to update the Hub account with, or null if the account is invalid.
     * @param ?string           $action   The action to perform on the Hub account. Can be 'create' or 'update'.
     *
     * @return int|false The post id of the Hub account, or false if the sync failed.
     */
    public static function process_pulled_backoffice_account(Hub_Account_Model $account, ?object $settings, ?string $action): false|int
    {
        if (!empty($settings)) {
            $account->org_name = $settings->CompanyName;
            $account->org_num = $settings->OrganizationNumber;
        } else {
            $account->org_name = '';
            $account->org_num = '';
        }
        $account->last_sync = Time_Helpers::get_current_api_time();
        if ('create' === $action) {
            $status = WP_Repository::create_from_model($account);
            $post_id = $status->wp_id ?? 0;
        } else {
            $status = WP_Repository::update_from_model($account);
            $post_id = $status;
        }
        if (!empty($status) && !is_wp_error($status)) {
            return $post_id;
        } else {
            return \false;
        }
    }
}
