<?php

/**
 * Plugin Name: Freya Sync Service
 * Plugin URI: https://www.freyapos.com/
 * Description: Sincronizează comenzi și produse cu o instanță de Freya
 * Version: 2.9.0
 * Requires PHP: 7.4
 * Author: Soft Tehnica
 * Author URI: https://soft-tehnica.com/
 **/

define("fsRootPath", plugin_dir_path(__FILE__));
define("fsPluginUrl", plugin_dir_url(__FILE__));

require_once plugin_dir_path(__FILE__) . 'vendor/autoload.php';

use FortAwesome\FontAwesome;
use FortAwesome\FontAwesome_Loader;
use Soft_Tehnica\Freya_Sync_Service\Services\AddressService;
use Soft_Tehnica\Freya_Sync_Service\Services\PluginSettings;
use Soft_Tehnica\Freya_Sync_Service\Services\SessionService;
use function FortAwesome\fa;
use Soft_Tehnica\Freya_Sync_Service\Services\SettingsPage;
use Soft_Tehnica\Freya_Sync_Service\Services\CartService;
use Soft_Tehnica\Freya_Sync_Service\Services\AdminOrderService;
use Soft_Tehnica\Freya_Sync_Service\Services\RestService;
use Soft_Tehnica\Freya_Sync_Service\Services\AdminProductService;
use Soft_Tehnica\Freya_Sync_Service\Services\ToppingService;

class FreyaSyncService
{
    public SettingsPage $settingsPage;
    public CartService $cartService;
    public AdminProductService $adminProductService;
    public RestService $restService;
    public AdminOrderService $adminOrderService;
    public ToppingService $toppingService;

    public function __construct()
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        SessionService::get()->loadSession();
        SessionService::get()->refreshSession();
        PluginSettings::get()->initializeSettings();
        AddressService::get();
        $this->registerPages();
    }

    public function registerPages(): void
    {
        $this->settingsPage = new SettingsPage();
        $this->cartService = new CartService();
        $this->adminProductService = new AdminProductService();
        $this->restService = new RestService();
        $this->adminOrderService = new AdminOrderService();
        $this->toppingService = new ToppingService();
    }
}

function no_woocommerce_error(): void
{
    ?>
    <div class="notice notice-error is-dismissible">
        <p><?php
            _e(
                'Trebuie să instalați plugin-ul Woocommerce înainte de a activa plugin-ul Freya Sync!',
                'sample-text-domain'
            ); ?></p>
    </div>
    <?php
}

function freya_sync_service_v2_active(): void
{
    try {
        FontAwesome_Loader::initialize();
    } catch (Throwable $e) {
        return;
    }

    $today = new DateTime();
    $args = array(
        'date_created' => '>=' . $today->format("Y-m-d")
    );

    try {
        $orders = wc_get_orders($args);
    } catch (Throwable $e) {
        // WooCommerce is probably not installed, handled in has_woocommerce()
        return;
    }

    foreach ($orders as $order) {
        $fssError = get_post_meta($order->get_id(), 'freya-sync-error', true);
        $fssProcessed = get_post_meta($order->get_id(), 'freya-sync-processed', true);

        if (!$fssError && !$fssProcessed) {
            update_post_meta($order->get_id(), 'location_uid', ' - ');
            update_post_meta($order->get_id(), 'location_name', ' - ');
            update_post_meta($order->get_id(), 'freya-sync-uid', ' - ');
            update_post_meta($order->get_id(), 'freya-order-id', ' - ');
            update_post_meta(
                $order->get_id(),
                'freya-sync-error',
                'Comandă trimisă înainte de activarea pluginului, nu va fi sincronizată.'
            );
            update_post_meta($order->get_id(), 'freya-sync-processed', 'true');
        }
    }
}

function check_dependencies(): void
{
    if (!is_admin() || !current_user_can('activate_plugins')) {
        return;
    }

    $deactivate = false;

    if (!is_plugin_active('woocommerce/woocommerce.php')) {
        add_action('admin_notices', 'no_woocommerce_error');
        $deactivate = true;
    }

    if ($deactivate) {
        deactivate_plugins(plugin_basename(__FILE__));

        if (isset($_GET['activate'])) {
            unset($_GET['activate']);
        }
    }
}

function freya_sync_service_uninstall(): void
{
    FontAwesome_Loader::maybe_uninstall();
}

register_activation_hook(__FILE__, 'freya_sync_service_v2_active');
register_deactivation_hook(__FILE__, function () {
    if (class_exists(FontAwesome_Loader::class)) {
        FontAwesome_Loader::maybe_deactivate();
    }
});
register_uninstall_hook(__FILE__, 'freya_sync_service_uninstall');

add_action('admin_init', 'check_dependencies');
add_action('font_awesome_preferences', function () {
    fa()->register([
        'name' => 'Freya Sync Service',
        'version' => [[FontAwesome::instance()->latest_version_5(), '>=']],
    ]);
});
add_action('init', function () {
    new FreyaSyncService();
    $script_args = include(plugin_dir_path(__FILE__) . 'assets/public/scripts.asset.php');
    wp_enqueue_script(
        'wp-typescript',
        plugins_url('assets/public/scripts.js', __FILE__),
        $script_args['dependencies'],
        $script_args['version']
    );
    wp_enqueue_style('modal-address-css', fsPluginUrl . 'assets/css/modal-address.css');
    wp_enqueue_style('admin-css', fsPluginUrl . 'assets/css/admin.css');
    wp_enqueue_style("fss_topping", fsPluginUrl . "assets/css/topping.css");
    wp_enqueue_style('fss-settings', fsPluginUrl . "assets/css/settings.css");

    $data = [
        'api_url' => fsServiceUrl(true),
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('wp_rest'),
        'version' => get_plugin_data(__FILE__)['Version']
    ];

    wp_add_inline_script('wp-typescript', "const php_data = " . json_encode($data), 'before');
});
