<?php
/**
 * Templates management page
 *
 * @package SlideMind
 * @since 2.0.0
 */

namespace SlideMind\Admin;

use SlideMind\Core\TemplateManager;

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

class TemplatesPage {

    /**
     * Template manager
     * @var TemplateManager
     */
    private $template_manager;

    /**
     * Constructor
     *
     * @param TemplateManager $template_manager
     */
    public function __construct(TemplateManager $template_manager) {
        $this->template_manager = $template_manager;

        // Templates AJAX
        add_action('wp_ajax_slidemind_get_templates', [$this, 'ajax_get_templates']);
        add_action('wp_ajax_slidemind_save_template', [$this, 'ajax_save_template']);
        add_action('wp_ajax_slidemind_delete_template', [$this, 'ajax_delete_template']);
        add_action('wp_ajax_slidemind_export_template', [$this, 'ajax_export_template']);
        add_action('wp_ajax_slidemind_import_template', [$this, 'ajax_import_template']);
        add_action('wp_ajax_slidemind_reset_default_template', [$this, 'ajax_reset_default_template']);
        add_action('wp_ajax_slidemind_get_template_by_slug', [$this, 'ajax_get_template_by_slug']);
        add_action('wp_ajax_slidemind_toggle_favorite_template', [$this, 'ajax_toggle_favorite_template']);
    }

    /**
     * AJAX: Retrieve all templates
     */
    public function ajax_get_templates() {
        check_ajax_referer('slidemind_admin_nonce', 'nonce');

        if (!current_user_can('manage_slidemind_configs')) {
            wp_send_json_error(['message' => __('Unauthorized access', 'slidemind')]);
        }

        $templates = $this->template_manager->get_all();

        wp_send_json_success(['templates' => $templates]);
    }

    /**
     * AJAX: Save a template (create or update)
     */
    public function ajax_save_template() {
        check_ajax_referer('slidemind_admin_nonce', 'nonce');

        if (!current_user_can('manage_slidemind_configs')) {
            wp_send_json_error(['message' => __('Unauthorized access', 'slidemind')]);
        }

        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- JSON data, sanitized after decode
        $data = isset($_POST['template']) ? wp_unslash($_POST['template']) : [];

        // Validation
        if (empty($data['title'])) {
            wp_send_json_error(['message' => __('Title is required', 'slidemind')]);
        }

        // Process variables (may be a comma-separated string)
        if (isset($data['variables']) && is_string($data['variables'])) {
            $data['variables'] = array_filter(array_map('trim', explode(',', $data['variables'])));
        }

        // Block template creation and editing for free users
        if (!\SlideMind\Core\FeatureGate::is_enabled('custom_templates')) {
            wp_send_json_error([
                'message'       => sprintf(
                    /* translators: %s: plan name */
                    __('This feature requires the %s plan.', 'slidemind'),
                    ucfirst(\SlideMind\Core\FeatureGate::get_required_plan('custom_templates'))
                ),
                'content_limit' => true,
                'upgrade_url'   => \SlideMind\Core\FeatureGate::get_upgrade_url(),
            ]);
        }

        // Create or update
        if (!empty($data['id'])) {
            $result = $this->template_manager->update((int) $data['id'], $data);
            $template_id = (int) $data['id'];
        } else {
            $result = $this->template_manager->create($data);
            $template_id = $result;
        }

        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
        }

        $template = $this->template_manager->get_by_id($template_id);

        wp_send_json_success([
            'message'     => __('Template saved', 'slidemind'),
            'template_id' => $template_id,
            'template'    => $template,
        ]);
    }

    /**
     * AJAX: Delete a template
     */
    public function ajax_delete_template() {
        check_ajax_referer('slidemind_admin_nonce', 'nonce');

        if (!current_user_can('manage_slidemind_configs')) {
            wp_send_json_error(['message' => __('Unauthorized access', 'slidemind')]);
        }

        $template_id = isset($_POST['template_id']) ? (int) $_POST['template_id'] : 0;

        if (!$template_id) {
            wp_send_json_error(['message' => __('Invalid template ID', 'slidemind')]);
        }

        $result = $this->template_manager->delete($template_id);

        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
        }

        if (!$result) {
            wp_send_json_error(['message' => __('Cannot delete the template', 'slidemind')]);
        }

        wp_send_json_success(['message' => __('Template deleted', 'slidemind')]);
    }

    /**
     * AJAX: Export a template as JSON
     */
    public function ajax_export_template() {
        check_ajax_referer('slidemind_admin_nonce', 'nonce');

        if (!current_user_can('manage_slidemind_configs')) {
            wp_send_json_error(['message' => __('Unauthorized access', 'slidemind')]);
        }

        $template_id = isset($_POST['template_id']) ? (int) $_POST['template_id'] : 0;

        if (!$template_id) {
            wp_send_json_error(['message' => __('Invalid template ID', 'slidemind')]);
        }

        $json = $this->template_manager->export($template_id);

        if (is_wp_error($json)) {
            wp_send_json_error(['message' => $json->get_error_message()]);
        }

        $template = $this->template_manager->get_by_id($template_id);
        $filename = 'template-' . ($template['slug'] ?? 'export') . '.json';

        wp_send_json_success([
            'json'     => $json,
            'filename' => $filename,
        ]);
    }

    /**
     * AJAX: Import a template from JSON
     */
    public function ajax_import_template() {
        check_ajax_referer('slidemind_admin_nonce', 'nonce');

        if (!current_user_can('manage_slidemind_configs')) {
            wp_send_json_error(['message' => __('Unauthorized access', 'slidemind')]);
        }

        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- JSON data, sanitized after decode
        $json = isset($_POST['json']) ? wp_unslash($_POST['json']) : '';

        if (empty($json)) {
            wp_send_json_error(['message' => __('JSON data required', 'slidemind')]);
        }

        // Block template import for free users
        if (!\SlideMind\Core\FeatureGate::is_enabled('custom_templates')) {
            wp_send_json_error([
                'message'       => sprintf(
                    /* translators: %s: plan name */
                    __('This feature requires the %s plan.', 'slidemind'),
                    ucfirst(\SlideMind\Core\FeatureGate::get_required_plan('custom_templates'))
                ),
                'content_limit' => true,
                'upgrade_url'   => \SlideMind\Core\FeatureGate::get_upgrade_url(),
            ]);
        }

        $result = $this->template_manager->import($json);

        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
        }

        $template = $this->template_manager->get_by_id($result);

        wp_send_json_success([
            'message'     => __('Template imported successfully', 'slidemind'),
            'template_id' => $result,
            'template'    => $template,
        ]);
    }

    /**
     * AJAX: Reset a default template
     */
    public function ajax_reset_default_template() {
        check_ajax_referer('slidemind_admin_nonce', 'nonce');

        if (!current_user_can('manage_slidemind_configs')) {
            wp_send_json_error(['message' => __('Unauthorized access', 'slidemind')]);
        }

        $slug = isset($_POST['slug']) ? sanitize_text_field(wp_unslash($_POST['slug'])) : '';

        if (empty($slug)) {
            wp_send_json_error(['message' => __('Template slug required', 'slidemind')]);
        }

        $result = $this->template_manager->reset_default($slug);

        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
        }

        wp_send_json_success(['message' => __('Template reset', 'slidemind')]);
    }

    /**
     * AJAX: Retrieve a template by its slug
     */
    public function ajax_get_template_by_slug() {
        check_ajax_referer('slidemind_admin_nonce', 'nonce');

        if (!current_user_can('manage_slidemind_configs')) {
            wp_send_json_error(['message' => __('Unauthorized access', 'slidemind')]);
        }

        $slug = isset($_POST['slug']) ? sanitize_text_field(wp_unslash($_POST['slug'])) : '';

        if (empty($slug)) {
            wp_send_json_error(['message' => __('Slug required', 'slidemind')]);
        }

        $template = $this->template_manager->get_by_slug($slug);

        if (!$template) {
            wp_send_json_error(['message' => __('Template not found', 'slidemind')]);
        }

        wp_send_json_success(['template' => $template]);
    }

    /**
     * AJAX: Toggle a template as favorite
     */
    public function ajax_toggle_favorite_template() {
        check_ajax_referer('slidemind_admin_nonce', 'nonce');

        if (!current_user_can('manage_slidemind_configs')) {
            wp_send_json_error(['message' => __('Unauthorized access', 'slidemind')]);
        }

        $slug = isset($_POST['slug']) ? sanitize_text_field(wp_unslash($_POST['slug'])) : '';
        if (empty($slug)) {
            wp_send_json_error(['message' => __('Slug required', 'slidemind')]);
        }

        $settings = get_option('slidemind_settings', []);
        $favorites = isset($settings['favorite_templates']) ? $settings['favorite_templates'] : [];

        $index = array_search($slug, $favorites);
        if ($index !== false) {
            // Remove
            array_splice($favorites, $index, 1);
            $is_favorite = false;
        } else {
            // Add (max 5)
            if (count($favorites) >= 6) {
                wp_send_json_error(['message' => __('Maximum 6 favorite templates', 'slidemind')]);
            }
            $favorites[] = $slug;
            $is_favorite = true;
        }

        $settings['favorite_templates'] = $favorites;
        update_option('slidemind_settings', $settings);

        wp_send_json_success([
            'is_favorite' => $is_favorite,
            'favorites'   => $favorites,
        ]);
    }
}
