<?php
namespace Atlasly\Core;

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

use Atlasly\Admin\Menu;
use Atlasly\Rest\ContentTypesController;
use Atlasly\Rest\DashboardController;
use Atlasly\Rest\EntriesController;
use Atlasly\Rest\ImportExportController;
use Atlasly\Rest\FileUploadController;
use Atlasly\Rest\GraphQLController;
use Atlasly\Rest\RelationshipController;
use Atlasly\Rest\FormGeneratorController;
use Atlasly\Admin\Pages\SetupWizard;
use Atlasly\Admin\Pages\Integration;

class Loader
{

    public static function init()
    {
        ApiSecurity::init();
        Version::init();
        Permissions::init();
        Webhooks::init();
        Network::init();
        RealTime::init();
        Security::init();
        CLI::init();

        add_action('admin_menu', [self::class, 'admin_menu']);
        add_action('admin_enqueue_scripts', [self::class, 'enqueue_assets']);
        add_action('rest_api_init', [ContentTypesController::class, 'register']);
        add_action('rest_api_init', [DashboardController::class, 'register']);
        add_action('rest_api_init', [EntriesController::class, 'register']);
        add_action('rest_api_init', [ImportExportController::class, 'register']);
        add_action('rest_api_init', [FileUploadController::class, 'register']);
        add_action('rest_api_init', [GraphQLController::class, 'register']);
        add_action('rest_api_init', [RelationshipController::class, 'register']);
        add_action('rest_api_init', [FormGeneratorController::class, 'register']);
        add_action('wp_ajax_atlasly_setup', [SetupWizard::class, 'handle_setup']);
        add_action('wp_ajax_atlasly_reset_setup', [SetupWizard::class, 'handle_reset']);
        add_action('wp_ajax_atlasly_save_security_settings', [self::class, 'handle_security_settings']);
        add_action('wp_ajax_atlasly_save_webhooks', [self::class, 'handle_save_webhooks']);
        add_action('wp_ajax_atlasly_save_cors', [self::class, 'handle_save_cors']);

        Integration::init();
    }

    public static function admin_menu()
    {
        Menu::register();
    }

    public static function enqueue_assets($hook)
    {
        if (strpos($hook, 'atlasly') === false)
            return;

        wp_enqueue_style('atlasly-admin', ATLASLY_URL . 'assets/css/admin.css', [], ATLASLY_VERSION);

        // Enqueue entries-specific CSS
        if (strpos($hook, 'atlasly-entries') !== false) {
            wp_enqueue_style('atlasly-entries', ATLASLY_URL . 'assets/css/entries.css', ['atlasly-admin'], ATLASLY_VERSION);
        }

        wp_enqueue_script('atlasly-admin', ATLASLY_URL . 'assets/js/admin.js', ['wp-element', 'wp-api-fetch'], ATLASLY_VERSION, true);

        // Add ajaxurl for setup wizard
        wp_localize_script('atlasly-admin', 'atlasly_ajax', [
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('atlasly_setup'),
            'security_nonce' => wp_create_nonce('atlasly_security_settings'),
            'admin_url' => admin_url(),
            'plugin_url' => ATLASLY_URL
        ]);

        // Add security settings
        wp_localize_script('atlasly-admin', 'atlasly_settings', [
            'allowed_origins' => get_option('atlasly_allowed_origins', []),
            'api_keys' => array_keys(get_option('atlasly_api_keys', []))
        ]);

        if (strpos($hook, 'atlasly-webhooks') !== false) {
            wp_enqueue_script(
                'atlasly-webhooks',
                ATLASLY_URL . 'assets/js/webhooks.js',
                ['wp-element'],
                ATLASLY_VERSION,
                true
            );

            wp_localize_script('atlasly-webhooks', 'atlasly_webhooks_data', [
                'ajaxurl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('atlasly_webhooks'),
                'webhooks' => get_option('atlasly_webhooks', []),
            ]);
        }
    }

    public static function handle_security_settings()
    {
        check_ajax_referer('atlasly_security_settings', 'security_nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized');
            return;
        }

        if (isset($_POST['generate_api_key'])) {
            $key_name = isset($_POST['api_key_name']) ? sanitize_text_field(wp_unslash($_POST['api_key_name'])) : 'Generated Key';
            if ($key_name === '') {
                $key_name = 'Generated Key';
            }
            $api_key = \Atlasly\Core\ApiSecurity::generate_api_key($key_name);
            wp_send_json_success(['api_key' => $api_key]);
            return;
        }

        if (isset($_POST['allowed_origins'])) {
            $origins_input = sanitize_textarea_field(wp_unslash($_POST['allowed_origins']));
            $origins = array_filter(array_map('trim', explode("\n", $origins_input)));
            \Atlasly\Core\ApiSecurity::set_allowed_origins($origins);
            wp_send_json_success(['message' => 'Settings saved successfully']);
            return;
        }

        wp_send_json_error('Invalid request');
    }

    public static function handle_save_webhooks()
    {
        check_ajax_referer('atlasly_webhooks', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized');
            return;
        }

        $webhooks_json = isset($_POST['webhooks']) ? wp_unslash($_POST['webhooks']) : '';
        $decoded = json_decode($webhooks_json, true);
        $webhooks = [];

        if (is_array($decoded)) {
            foreach ($decoded as $event => $hooks) {
                $event_key = sanitize_key((string) $event);
                if (!is_array($hooks) || $event_key === '') {
                    continue;
                }

                $sanitized_hooks = [];
                foreach ($hooks as $hook) {
                    $url = isset($hook['url']) ? esc_url_raw((string) $hook['url']) : '';
                    $secret = isset($hook['secret']) ? sanitize_text_field((string) $hook['secret']) : '';
                    if ($url !== '') {
                        $sanitized_hooks[] = [
                            'url' => $url,
                            'secret' => $secret,
                        ];
                    }
                }

                if (!empty($sanitized_hooks)) {
                    $webhooks[$event_key] = $sanitized_hooks;
                }
            }
        }

        update_option('atlasly_webhooks', $webhooks);
        wp_send_json_success(['message' => 'Webhooks saved']);
    }

    public static function handle_save_cors()
    {
        check_ajax_referer('atlasly_cors', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized');
            return;
        }

        $origins_input = isset($_POST['allowed_origins']) ? sanitize_textarea_field(wp_unslash($_POST['allowed_origins'])) : '';
        $origins = array_filter(array_map('trim', explode("\n", $origins_input)));
        \Atlasly\Core\ApiSecurity::set_allowed_origins($origins);
        wp_send_json_success(['message' => 'CORS settings saved']);
    }
}
