<?php

namespace SWPanel\Pages;

defined('ABSPATH') || die('No direct access.');

use SWPanel\SettingsManager;

class TemplatePage {
    public function __construct() {
        add_action('admin_menu', [$this, 'register']);
        add_action('admin_post_swpanel_ai_template_form', [$this, 'handleSubmit']);
        add_action('admin_post_swpanel_ai_template_back', [$this, 'handleBack']);
        add_action('wp_ajax_swpanel_ai_create_template_pages', ['SWPanel\\SettingsManager', 'createPreviewPages']);
    }

    public function register() {
        add_submenu_page(null, __('SWPanel Template', 'swpanel-ai'), __('SWPanel Template', 'swpanel-ai'), 'manage_options', 'swpanel_ai_template', [$this, 'render']);
    }

    public function render() {
        update_option('swpanel_ai_page', 'swpanel_ai_template');

        if (get_option('swpanel_ai_headers') && get_option('swpanel_ai_images')){
            SettingsManager::setTemplatePages();
            $structure = get_option('swpanel_ai_page_type', 'single');
            include SWPANEL_PATH . 'admin/views/template-form.php';
        }
        else {
            $message = __('Please choose a style for your page.', 'swpanel-ai');
            $value_form = 'swpanel_ai_template_back';
            include SWPANEL_PATH . 'admin/views/missing-conf.php';
        }
    }

    public function handleSubmit() {
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ) : '';
        if ( ! $nonce || ! wp_verify_nonce( $nonce, 'swpanel_ai_template' ) ) {
            wp_die( 'Invalid nonce' );
        }
        if(!isset($_POST['form_action'])){
            wp_die('Invalid post');
        }

        if ($_POST['form_action'] === 'back') {
            update_option('swpanel_ai_page', 'swpanel_ai_style');
            wp_redirect(admin_url('admin.php?page=swpanel_ai_style'));
        } elseif ($_POST['form_action'] === 'continue') {
            SettingsManager::saveTemplatePagesData(isset($_POST['preview_id']) ? sanitize_text_field(wp_unslash($_POST['preview_id'])) : '');
            update_option('swpanel_ai_page', 'swpanel_ai_creating');
            wp_redirect(admin_url('admin.php?page=swpanel_ai_creating'));
        }
        exit;
    }

    public function handleBack() {
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ) : '';
        if ( ! $nonce || ! wp_verify_nonce( $nonce, 'swpanel_ai_back' ) ) {
            wp_die( 'Invalid nonce' );
        }

        update_option('swpanel_ai_page', 'swpanel_ai_style');
        wp_redirect(admin_url('admin.php?page=swpanel_ai_style'));
        exit;
    }
}
