<?php
/**
 * Plugin Name: RTM WordPress Models (Working Title)
 * Description: Must use plugin to add extended functionality to the WordPress framework, providing Doctrine integration and more!
 * Author: RTM Business
 * Version: 0.5.2
 */

use Psr\Container\ContainerInterface;
use WordpressModels\WordpressPluginContainers;

if (!class_exists('WordpressModels\ORM\EntityManagerFactory', false)) {
    require_once __DIR__ . '/vendor/autoload.php';
}

define('WPM_PLUGIN_DIR', __DIR__);
define('WPM_PLUGIN_VERSION', '0.5.2');


// directory locations
define('WPM_CONTAINER_CACHE_DIR', WPM_PLUGIN_DIR . '/cache');
// used for meta value check
if (!function_exists('is_json')) {
    /**
     * Check if a string is a valid json.
     * @param string|null $argument
     * @param bool $ignore_scalars
     * @return bool
     */
    function is_json(?string $argument, bool $ignore_scalars = true)
    {
        if (!is_string($argument) || '' === $argument) {
            return false;
        }

        if ($ignore_scalars && !in_array($argument[0], ['{', '['], true)) {
            return false;
        }

        json_decode($argument, true);

        return json_last_error() === JSON_ERROR_NONE;
    }
}

/**
 * Convenience function to get the global container.
 *
 * @return ContainerInterface
 */
function wpm_container(): ContainerInterface
{
    global $wpmc;
    $wpm_container = $wpmc->getContainer();

    return $wpm_container;
}

/**
 * Invalidate the global container.
 *
 * Deletes the container cache file.
 *
 * @return void
 */
function _wpm_invalidate_container(): void
{
    global $wpmc;
    $wpmc->invalidate();
}

if (is_admin()) {
    // add admin script enqueue hook for specific pages
    add_action('admin_enqueue_scripts', function ($hook_suffix) {
        global $typenow;

        // add hook for all admin pages
        do_action("admin_enqueue_scripts-{$hook_suffix}");

        // add hook for specific post type
        if ($typenow) {
            do_action("admin_enqueue_scripts-{$hook_suffix}/{$typenow}");
        }
    }, 0);
}

global $wpmc;

// if we're not executing tests, we will build the container
if (!defined('WPM_TESTING') || !WPM_TESTING) {
    $wpmc = new WordpressPluginContainers();
}