<?php

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

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

require_once plugin_dir_path(__FILE__) . 'vendor/autoload.php';
require_once ABSPATH . "wp-admin/includes/plugin.php";

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 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\ReturoService;
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 ReturoService $returoService;

    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
    {
        // Inițializăm doar dacă nu se face request în wp-json sau dacă se face request în store API
        if (!fss_is_wp_json() || fss_is_wc_store_api()) {
            $this->settingsPage = new SettingsPage();
            $this->cartService = new CartService();
            $this->adminProductService = new AdminProductService();
            $this->adminOrderService = new AdminOrderService();
            $this->toppingService = new ToppingService();
            $this->returoService = new ReturoService();
        }
        $this->restService = new RestService();
    }
}

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

function freya_sync_service_v2_active(): void
{
    if (is_plugin_active('font-awesome/index.php')) {
        \FortAwesome\FontAwesome_Loader::initialize();
    }

    check_dependencies();

    $today = new DateTime();
    $args = [
        '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 = $order->get_meta('freya-sync-error');
        $fssProcessed = $order->get_meta('freya-sync-processed');

        if (!$fssError && !$fssProcessed) {
            $order->update_meta_data('location_uid', ' - ');
            $order->update_meta_data('location_name', ' - ');
            $order->update_meta_data('freya-sync-uid', ' - ');
            $order->update_meta_data('freya-order-id', ' - ');
            $order->update_meta_data('freya-sync-error', '');
            $order->update_meta_data('freya-sync-processed', 'old');
            $order->save_meta_data();
        }
    }
}

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

    $deactivate = false;
    if (!function_exists('is_plugin_active')) {
        include ABSPATH . "wp-admin/includes/plugin.php";
    }

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

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

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

function freya_sync_service_uninstall(): void
{
    if (is_plugin_active('font-awesome/index.php')) {
        \FortAwesome\FontAwesome_Loader::maybe_uninstall();
    }
}

register_activation_hook(__FILE__, 'freya_sync_service_v2_active');
register_deactivation_hook(__FILE__, function () {
    if (is_plugin_active('font-awesome/index.php')) {
        \FortAwesome\FontAwesome_Loader::maybe_deactivate();
    }
});
register_uninstall_hook(__FILE__, 'freya_sync_service_uninstall');

add_action('admin_init', 'check_dependencies');

add_action('init', function () {
    if (!function_exists('is_plugin_active')) {
        include ABSPATH . "wp-admin/includes/plugin.php";
    }
    check_dependencies();

    if (is_plugin_active('font-awesome/index.php')) {
        add_action('font_awesome_preferences', function () {
            \FortAwesome\fa()->register([
                'name' => 'Freya Sync Service',
                'version' => [[\FortAwesome\fa()->latest_version_5(), '>=']],
            ]);
        });
    }

    new FreyaSyncService();
    $script_args = include(plugin_dir_path(
        __FILE__
    ) . 'assets/public/scripts.asset.php');
    $script2_args = include(plugin_dir_path(
        __FILE__
    ) . 'assets/public/blocks/scripts.asset.php');
    wp_enqueue_script(
        'freya-sync-service/main',
        plugins_url('assets/public/scripts.js', __FILE__),
        $script_args['dependencies'],
        $script_args['version']
    );
    wp_enqueue_script(
        'freya-sync-service/wc-blocks',
        plugins_url('assets/public/blocks/scripts.js', __FILE__),
        $script2_args['dependencies'],
        $script2_args['version']
    );

    wp_enqueue_style(
        'modal-address-css',
        fsPluginUrl . 'assets/css/modal-address.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'],
        'pickup' => SessionService::get()->isPickup()
    ];

    wp_localize_script(
        'freya-sync-service/main',
        'php_data',
        $data
    );
});
