<?php

namespace SWPanel\Pages;

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

use SWPanel\SettingsManager;

class StructurePage {
    public function __construct() {
        add_action('admin_menu', [$this, 'register']);
        add_action('admin_post_swpanel_ai_structure_form', [$this, 'handleSubmit']);
        add_action('admin_post_swpanel_ai_structure_back', [$this, 'handleBack']);
        add_action('wp_ajax_swpanel_ai_get_description_keywords', ['SWPanel\\SettingsManager', 'getDescriptionKeywords']);
    }

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

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

        if (get_option('blogname') && get_option('blogdescription') && get_option('swpanel_ai_tone')){
            $structure_type = SettingsManager::getStructureData();
            include SWPANEL_PATH . 'admin/views/structure-form.php';
        }
        else {
            $message = __('Please provide a title, description and tone.', 'swpanel-ai');
            $value_form = 'swpanel_ai_structure_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_structure' ) ) {
            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_concept');
            wp_redirect(admin_url('admin.php?page=swpanel_ai_concept'));
        } elseif ($_POST['form_action'] === 'continue') {
            SettingsManager::saveStructureData(isset($_POST['page_type']) ? sanitize_text_field(wp_unslash($_POST['page_type'])) : '');

            update_option('swpanel_ai_page', 'swpanel_ai_style');
            wp_redirect(admin_url('admin.php?page=swpanel_ai_style'));
        }
        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_concept');
        wp_redirect(admin_url('admin.php?page=swpanel_ai_concept'));
        exit;
    }
}
