<?php
/**
 * Admin Menu Class
 *
 * Handles admin menu registration and page routing.
 *
 * @package PCFormBuilder
 */

class PCFB_Admin_Menu {

    private static $instance = null;

    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
        add_action( 'admin_init', array( $this, 'handle_form_actions' ) );
        add_action( 'wp_ajax_pcfb_add_field', array( $this, 'ajax_add_field' ) );
    }

    public function add_admin_menu() {
        add_menu_page(
            __( 'Form Builder', 'pc-form-builder-xyz123' ),
            __( 'Form Builder', 'pc-form-builder-xyz123' ),
            'manage_options',
            'pcfb-form-builder',
            array( $this, 'render_form_builder_page' ),
            'dashicons-feedback',
            30
        );

        add_submenu_page(
            'pcfb-form-builder',
            __( 'Form Builder', 'pc-form-builder-xyz123' ),
            __( 'Form Builder', 'pc-form-builder-xyz123' ),
            'manage_options',
            'pcfb-form-builder',
            array( $this, 'render_form_builder_page' )
        );

        add_submenu_page(
            'pcfb-form-builder',
            __( 'All Forms', 'pc-form-builder-xyz123' ),
            __( 'All Forms', 'pc-form-builder-xyz123' ),
            'manage_options',
            'pcfb-all-forms',
            array( $this, 'render_all_forms_page' )
        );

        add_submenu_page(
            'pcfb-form-builder',
            __( 'Responses', 'pc-form-builder-xyz123' ),
            __( 'Responses', 'pc-form-builder-xyz123' ),
            'manage_options',
            'pcfb-responses',
            array( $this, 'render_responses_page' )
        );
    }

    public function render_form_builder_page() {
        require_once PCFB_PLUGIN_DIR . 'admin/class-admin-helper.php';
        $helper = PCFB_Admin_Helper::get_instance();

        $form_id = isset( $_GET['form_id'] ) ? intval( $_GET['form_id'] ) : 0;

        if ( $form_id > 0 ) {
            include PCFB_PLUGIN_DIR . 'admin/page-form-builder.php';
        } else {
            include PCFB_PLUGIN_DIR . 'admin/page-form-builder.php';
        }
    }

    public function render_all_forms_page() {
        include PCFB_PLUGIN_DIR . 'admin/page-all-forms.php';
    }

    public function render_responses_page() {
        $form_id = isset( $_GET['form_id'] ) ? intval( $_GET['form_id'] ) : 0;
        $response_id = isset( $_GET['response_id'] ) ? intval( $_GET['response_id'] ) : 0;

        if ( $response_id > 0 ) {
            include PCFB_PLUGIN_DIR . 'admin/page-response-detail.php';
        } elseif ( $form_id > 0 ) {
            include PCFB_PLUGIN_DIR . 'admin/page-form-responses.php';
        } else {
            include PCFB_PLUGIN_DIR . 'admin/page-responses.php';
        }
    }

    public function handle_form_actions() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        if ( ! isset( $_POST['pcfb_action'] ) ) {
            return;
        }

        if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'pcfb_admin_action' ) ) {
            return;
        }

        $action = sanitize_text_field( $_POST['pcfb_action'] );

        switch ( $action ) {
            case 'save_form':
                $this->handle_save_form();
                break;
            case 'delete_form':
                $this->handle_delete_form();
                break;
            case 'toggle_status':
                $this->handle_toggle_status();
                break;
        }
    }

    private function handle_save_form() {
        $form_data = isset( $_POST['form'] ) ? $_POST['form'] : array();
        $fields = isset( $_POST['fields'] ) ? $_POST['fields'] : array();

        $handler = PC_Form_Handler::get_instance();
        $form_id = $handler->save_form( $form_data, $fields );

        if ( $form_id ) {
            $edit_url = admin_url( 'admin.php?page=pcfb-form-builder&form_id=' . $form_id );
            $shortcode = '[pcfb-form id="' . $form_id . '"]';
            
            add_action( 'admin_notices', function() use ( $edit_url, $shortcode ) {
                echo '<div class="notice notice-success is-dismissible"><p>';
                echo sprintf( __( 'Form saved successfully!', 'pc-form-builder-xyz123' ) );
                echo '</p><p><strong>' . esc_html__( 'Shortcode:', 'pc-form-builder-xyz123' ) . '</strong> <code onclick="this.select(); document.execCommand(\'copy\');" style="background: #f0f0f1; padding: 4px 8px; border-radius: 4px; cursor: pointer; font-size: 14px;">' . esc_html( $shortcode ) . '</code></p>';
                echo '<p><a href="' . esc_url( $edit_url ) . '" class="button button-primary" style="margin-top: 10px;">' . esc_html__( 'Go to Form Builder', 'pc-form-builder-xyz123' ) . '</a></p></div>';
            } );
            
            wp_redirect( admin_url( 'admin.php?page=pcfb-form-builder&form_id=' . $form_id ) );
            exit;
        } else {
            add_action( 'admin_notices', function() {
                echo '<div class="notice notice-error is-dismissible"><p>';
                echo esc_html__( 'Failed to save form. Please try again.', 'pc-form-builder-xyz123' );
                echo '</p></div>';
            } );
        }
    }

    private function handle_delete_form() {
        $form_id = isset( $_POST['form_id'] ) ? intval( $_POST['form_id'] ) : 0;

        if ( $form_id > 0 && PC_Form_Handler::delete_form( $form_id ) ) {
            add_action( 'admin_notices', function() {
                echo '<div class="notice notice-success is-dismissible"><p>';
                echo esc_html__( 'Form deleted successfully.', 'pc-form-builder-xyz123' );
                echo '</p></div>';
            } );
        } else {
            add_action( 'admin_notices', function() {
                echo '<div class="notice notice-error is-dismissible"><p>';
                echo esc_html__( 'Failed to delete form. Please try again.', 'pc-form-builder-xyz123' );
                echo '</p></div>';
            } );
        }
    }

    private function handle_toggle_status() {
        global $wpdb;
        $form_id = isset( $_POST['form_id'] ) ? intval( $_POST['form_id'] ) : 0;

        if ( $form_id > 0 ) {
            $form = PC_Form_Handler::get_form_by_id( $form_id );
            if ( $form ) {
                $new_status = 'active' === $form->status ? 'inactive' : 'active';
                $table_name = $wpdb->prefix . 'pcfb_forms';
                $wpdb->update( $table_name, array( 'status' => $new_status ), array( 'id' => $form_id ) );
            }
        }
    }

    public function ajax_add_field() {
        check_ajax_referer( 'pcfb_admin_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied.', 'pc-form-builder-xyz123' ) ) );
        }

        $field_type = isset( $_POST['field_type'] ) ? sanitize_text_field( $_POST['field_type'] ) : 'text';
        $field_index = isset( $_POST['field_index'] ) ? intval( $_POST['field_index'] ) : 0;

        require_once PCFB_PLUGIN_DIR . 'admin/class-admin-helper.php';
        $helper = PCFB_Admin_Helper::get_instance();

        ob_start();
        $helper->render_new_field_item( $field_type, $field_index );
        $html = ob_get_clean();

        wp_send_json_success( array( 'html' => $html ) );
    }
}
