<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css"
        integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
</html>
<?php

namespace Elementor\Modules\GlobalClasses;

use Elementor\Core\Kits\Documents\Kit;
use Elementor\Modules\GlobalClasses\Concerns\Has_Kit_Dependency;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Global_Classes_Order {
	use Has_Kit_Dependency;

	const META_KEY = '_elementor_global_classes_order';

	private ?array $cache = null;

	private function __construct() {
	}

	public static function make( Kit $kit ): self {
		return ( new self() )->set_kit( $kit );
	}

	public function get_order(): array {
		$payload = $this->read_kit_meta_payload();

		return $payload['order'] ?? [];
	}

	public function set_order( array $ids ): bool {
		$kit = $this->get_kit();

		if ( ! $kit ) {
			return false;
		}

		$payload = [
			'order' => array_values( $ids ),
		];

		$result = $kit->update_meta( self::META_KEY, $payload );
		$this->cache = null;

		return false !== $result;
	}

	public function remove_class_id( string $id ): bool {
		$order = $this->get_order();

		if ( ! in_array( $id, $order, true ) ) {
			return true;
		}

		$order = array_filter( $order, fn( $item ) => $item !== $id );

		return $this->set_order( $order );
	}

	private function read_kit_meta_payload(): array {
		if ( null !== $this->cache ) {
			return $this->cache;
		}

		$kit = $this->get_kit();

		if ( ! $kit ) {
			return [];
		}

		$payload = $kit->get_meta( self::META_KEY );
		$this->cache = is_array( $payload ) ? $payload : [];

		return $this->cache;
	}
}
