<?php

namespace MovieEngine\Admin\ImportExport;

if (! defined("ABSPATH")) {
    exit; // Exit if accessed directly
}

class ImportExportHandler {

    public function __construct() {
        add_action('admin_init', [$this, 'handle_export']);
        add_action('admin_init', [$this, 'handle_import']);
    }

    /**
     * Handle the export of settings
     */
    public function handle_export() {
        if (!isset($_POST['movie_engine_export_nonce'])) {
            return;
        }

        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['movie_engine_export_nonce'])), 'movie_engine_export_action')) {
            wp_die(esc_html__('Security check failed.', 'cine-movie-engine'));
        }

        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Insufficient permissions.', 'cine-movie-engine'));
        }

        $options_to_export = [
            'movie_engine_general_settings',
            'movie_engine_design_settings',
            'movie_engine_api_settings',
            'movie_engine_monetization_settings',
            'movie_engine_payments_settings',
            'movie_engine_email_settings',
            'movie_engine_player_settings',
            'movie_engine_referral_settings',
            'movie_engine_social_settings'
        ];

        $export_data = [
            'version' => MOVIE_ENGINE_VERSION,
            'timestamp' => time(),
            'site_url' => site_url(),
            'settings' => []
        ];

        foreach ($options_to_export as $option_name) {
            $export_data['settings'][$option_name] = get_option($option_name);
        }

        $filename = 'movie-engine-settings-export-' . gmdate('Y-m-d-H-i-s') . '.json';

        header('Content-Description: File Transfer');
        header('Content-Type: application/json');
        header('Content-Disposition: attachment; filename=' . $filename);
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');

        echo json_encode($export_data, JSON_PRETTY_PRINT);
        exit;
    }

    /**
     * Handle the import of settings
     */
    public function handle_import() {
        if (!isset($_POST['movie_engine_import_nonce'])) {
            return;
        }

        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['movie_engine_import_nonce'])), 'movie_engine_import_action')) {
            add_settings_error('movie_engine_import', 'security_failed', esc_html__('Security check failed.', 'cine-movie-engine'), 'error');
            return;
        }

        if (!current_user_can('manage_options')) {
            add_settings_error('movie_engine_import', 'insufficient_perms', esc_html__('Insufficient permissions.', 'cine-movie-engine'), 'error');
            return;
        }

        if (empty($_FILES['movie_engine_import_file']['tmp_name'])) {
            add_settings_error('movie_engine_import', 'no_file', esc_html__('Please select a file to import.', 'cine-movie-engine'), 'error');
            return;
        }

        $import_file = isset($_FILES['movie_engine_import_file']['tmp_name']) ? sanitize_text_field(wp_unslash($_FILES['movie_engine_import_file']['tmp_name'])) : '';
        $import_data = json_decode(file_get_contents($import_file), true);

        if (!$import_data || !isset($import_data['settings'])) {
            add_settings_error('movie_engine_import', 'invalid_file', esc_html__('Invalid import file format.', 'cine-movie-engine'), 'error');
            return;
        }

        $allowed_options = [
            'movie_engine_general_settings',
            'movie_engine_design_settings',
            'movie_engine_api_settings',
            'movie_engine_monetization_settings',
            'movie_engine_payments_settings',
            'movie_engine_email_settings',
            'movie_engine_player_settings',
            'movie_engine_referral_settings',
            'movie_engine_social_settings'
        ];

        foreach ($import_data['settings'] as $option_name => $option_value) {
            if (in_array($option_name, $allowed_options, true) && $option_value !== false) {
                update_option($option_name, $option_value);
            }
        }

        // Clear cache after update
        \MovieEngine\Core\Cache::purge_all();
        \MovieEngine\Core\Cache::update_custom_css();

        add_settings_error('movie_engine_import', 'success', esc_html__('Settings imported successfully! Your pages have been updated and cache cleared.', 'cine-movie-engine'), 'success');
    }
}
