<?php

/**
 * Handles locks
 *
 * @package northmill-online-shared
 */
declare (strict_types=1);
namespace Northmill_Online_Shared_Sync\Northmill_Online_Shared\Modules\Cron;

defined('ABSPATH') || exit;
/**
 * Class Locks
 */
class Locks
{
    public const LOCK_OPTION_PREFIX = 'mf_lock_';
    /**
     * Get all locks from DB.
     *
     * @return array
     */
    public static function get_all(): array
    {
        global $wpdb;
        $option_name = self::LOCK_OPTION_PREFIX . '_%';
        $results = $wpdb->get_results("SELECT * FROM {$wpdb->options} WHERE option_name LIKE '{$option_name}'");
        $locks = array();
        if (!$results) {
            return $locks;
        }
        foreach ($results as $result) {
            $info = explode('_', $result->option_name);
            $type = $info[3];
            // Remove the first 4 elements of the array.
            array_splice($info, 0, 4);
            $key = implode('_', $info);
            if (!isset($locks[$key])) {
                $locks[$key] = array();
            }
            if ('time' === $type) {
                $locks[$key]['time'] = !empty($result->option_value) ? (int) $result->option_value : null;
            } elseif ('value' === $type) {
                $locks[$key]['value'] = $result->option_value;
            }
        }
        return $locks;
    }
}
