<?php

namespace SWPanel\Pages;

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

use SWPanel\SettingsManager;

class StylePage {
    public function __construct() {
        add_action('admin_menu', [$this, 'register']);
        add_action('admin_post_swpanel_ai_style_form', [$this, 'handleSubmit']);
        add_action('admin_post_swpanel_ai_style_back', [$this, 'handleBack']);
        add_action('wp_ajax_swpanel_ai_get_headers', ['SWPanel\\SettingsManager', 'getHeaders']);
    }

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

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

        if (get_option('swpanel_ai_improved_description') && get_option('swpanel_ai_keywords') && get_option('swpanel_ai_page_type')){
            $data = SettingsManager::getStyleData();
            wp_localize_script('swpanel_ai_style', 'swpanel_ai_style_data', $data);
            include SWPANEL_PATH . 'admin/views/style-form.php';
        }
        else {
            $message = __('Please select a structure for your page.', 'swpanel-ai');
            $value_form = 'swpanel_ai_style_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_style' ) ) {
            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_structure');
            wp_redirect(admin_url('admin.php?page=swpanel_ai_structure'));
        } elseif ($_POST['form_action'] === 'continue') {
            SettingsManager::saveStyleData(isset($_POST['site_style']) ? sanitize_text_field(wp_unslash($_POST['site_style'])) : '');
            update_option('swpanel_ai_page', 'swpanel_ai_template');
            wp_redirect(admin_url('admin.php?page=swpanel_ai_template'));
        }
        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_structure');
        wp_redirect(admin_url('admin.php?page=swpanel_ai_structure'));
        exit;
    }
}
