<?php
/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://webequipe.com
 * @since      1.0.0
 *
 * @package    Webequipe_Spin_Win_Wheel
 * @subpackage Webequipe_Spin_Win_Wheel/admin
 */

// If this file is called directly, abort.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Webequipe_Spin_Win_Wheel
 * @subpackage Webequipe_Spin_Win_Wheel/admin
 * @author     Webequipe <support@webequipe.com>
 */

require_once __DIR__ . '/../includes/class-webequipe-spin-win-wheel-functions.php';

use Webequipe\SpinWinWheel\Traits\Form_Error;

/**
 * Spin Handler class
 */
class Webequipe_Spin_Win_Wheel_Spin
{

    use Form_Error;

    
	/**
	 * Plugin page handler.
	 *
	 * @return void
	 */
	public function plugin_page() {
		// Check user capabilities.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'webequipe-spin-win-wheel' ) );
		}

		// Extract and sanitize GET parameters.
		$action = isset( $_GET['action'] ) ? sanitize_key( wp_unslash( $_GET['action'] ) ) : 'list';
		$id     = isset( $_GET['id'] ) ? absint( wp_unslash( $_GET['id'] ) ) : 0;

		// List view is read-only and doesn't require a nonce to prevent redirect loops.
		// Only actions that modify data (edit, new, view) require nonce verification.
		if ( 'list' === $action && 0 === $id ) {
			$template = __DIR__ . '/partials/webequipe-spin-win-wheel-spin-list.php';
			if ( file_exists( $template ) ) {
				include $template;
			}
			return;
		}

		// For edit, new, and view actions, require a valid nonce.
		if ( ! isset( $_GET['_wpnonce'] ) ) {
			wp_die( esc_html__( 'Security check failed. Missing nonce.', 'webequipe-spin-win-wheel' ) );
		}

		$nonce = sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) );
		if ( ! wp_verify_nonce( $nonce, 'wsww_spin_action' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'webequipe-spin-win-wheel' ) );
		}

		switch ( $action ) {
			case 'new':
				$template = __DIR__ . '/partials/webequipe-spin-win-wheel-spin-new.php';
				break;

		case 'edit':
			$spin     = webequipe_sww_get_spin( $id );
			$template = __DIR__ . '/partials/webequipe-spin-win-wheel-spin-edit.php';
			break;

			case 'view':
				$spin     = webequipe_sww_get_spin( $id );
				$template = __DIR__ . '/partials/webequipe-spin-win-wheel-spin-view.php';
				break;

			default:
				$template = __DIR__ . '/partials/webequipe-spin-win-wheel-spin-list.php';
				break;
		}

		if ( file_exists( $template ) ) {
			include $template;
		}
	}

    /**
     * Handle the form
     *
     * @return void
     */



    public function form_handler() {
        if ( ! isset( $_POST['submit_spin_settings'] ) ) {
            return;
        }

        if ( ! isset( $_POST['_wpnonce'] ) ) {
            wp_die( esc_html__( 'Missing nonce.', 'webequipe-spin-win-wheel' ) );
        }

        $nonce = sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) );

        if ( ! wp_verify_nonce( $nonce, 'new-spin' ) ) {
            wp_die( esc_html__( 'Security check failed. Please try again.', 'webequipe-spin-win-wheel' ) );
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have permission to perform this action.', 'webequipe-spin-win-wheel' ) );
        }
        $id   = isset($_POST['id']) ? intval($_POST['id']) : 0;
        $spin_title = isset( $_POST['spin_title'] )
            ? sanitize_text_field( wp_unslash( $_POST['spin_title'] ) )
            : '';

        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Repeater array; each field sanitized in the loop below.
        $spins = isset( $_POST['spins'] ) ? wp_unslash( $_POST['spins'] ) : [];
        $spins_new = [];

        if (is_array($spins)) {
            foreach ($spins as $key => $value) {
                $label = sanitize_text_field($value['spin_label'] ?? '');
                if (!empty($label)) {
                    // Persistent unique ID: use existing if present, otherwise generate once.
                    $existing_id = isset( $value['spin_item_unique_id'] ) ? preg_replace( '/[^0-9]/', '', (string) $value['spin_item_unique_id'] ) : '';
                    $spin_item_unique_id = ( '' !== $existing_id && strlen( $existing_id ) >= 8 ) ? substr( $existing_id, 0, 20 ) : webequipe_sww_generate_spin_item_unique_id();

                    $spins_new[$key] = [
                        'spin_item_unique_id' => $spin_item_unique_id,
                        'is_win'          => sanitize_text_field($value['is_win'] ?? 'no'),
                        'spin_label'      => $label,
                        'spin_value'      => sanitize_text_field($value['spin_value'] ?? ''),
                        'spin_probability'=> floatval($value['spin_probability'] ?? 0),
                        'spin_bgcolor'    => sanitize_hex_color($value['spin_bgcolor'] ?? ''),
                        'spin_textcolor'  => sanitize_hex_color($value['spin_textcolor'] ?? ''),
                    ];
                }
            }
        }

        if (isset($_POST['submit_spin_settings'])) {


                $custom_image_url = '';

                if (
                    isset($_POST['wsww_upload_wheel_image_nonce']) &&
                    wp_verify_nonce(
                        sanitize_text_field( wp_unslash( $_POST['wsww_upload_wheel_image_nonce'] ) ),
                        'wsww_upload_wheel_image'
                    )
                ) {
                    if ( ! empty($_FILES['custom_wheel_center_image_icon']['name']) ) {
                        require_once ABSPATH . 'wp-admin/includes/file.php';

                        // Safe to process the uploaded file (wp_handle_upload validates the temp file).
                        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
                        $uploaded_file = $_FILES['custom_wheel_center_image_icon'];
                        $upload_overrides = [ 'test_form' => false ];

                        $movefile = wp_handle_upload( $uploaded_file, $upload_overrides );

                        if ( $movefile && ! isset( $movefile['error'] ) ) {
                            $custom_image_url = esc_url_raw( $movefile['url'] );
                        }
                    } else {
						$custom_image_url = isset( $_POST['existing_custom_image'] )
							? sanitize_text_field( wp_unslash( $_POST['existing_custom_image'] ) )
							: '';
					}
                } else {
                    // Nonce failed â€” you may log or handle error
                    wp_die( esc_html__( 'Security check failed. Please try again.', 'webequipe-spin-win-wheel' ) );
                }


            // Sanitize spin_display_setting
            $spin_display_setting = [];
            if ( isset( $_POST['spin_display_setting'] ) && is_array( $_POST['spin_display_setting'] ) ) {
                $spin_display_setting = array_map( 'sanitize_text_field', wp_unslash( $_POST['spin_display_setting'] ) );
            }

            // Sanitize display_field_setting
            $display_field_setting = [];
            if ( isset( $_POST['display_field_setting'] ) && is_array( $_POST['display_field_setting'] ) ) {
                $display_field_setting = array_map( 'sanitize_text_field', wp_unslash( $_POST['display_field_setting'] ) );
            }

            $args = [
                'spin_title'                      => $spin_title,
                'spin_description'                => isset( $_POST['spin_description'] ) ? sanitize_text_field( wp_unslash( $_POST['spin_description'] ) ) : '',
                'spin_status'                     => isset( $_POST['spin_status'] ) ? sanitize_text_field( wp_unslash( $_POST['spin_status'] ) ) : 'inactive',

                'spin_type'                       => isset( $_POST['spin_type'] ) ? sanitize_text_field( wp_unslash( $_POST['spin_type'] ) ) : '',
                'spin_position'                   => isset( $_POST['spin_position'] ) ? sanitize_text_field( wp_unslash( $_POST['spin_position'] ) ) : '',
                'spin_display_setting'            => wp_json_encode( $spin_display_setting ),
                'display_field_setting'           => wp_json_encode( $display_field_setting ),
                

                'auto_minute'                     => isset( $_POST['auto_minute'] ) ? intval( wp_unslash( $_POST['auto_minute'] ) ) : 0,
                'spin_duration'                   => isset( $_POST['spin_duration'] ) ? intval( wp_unslash( $_POST['spin_duration'] ) ) : 0,
                'display_after'                   => isset( $_POST['display_after'] ) ? intval( wp_unslash( $_POST['display_after'] ) ) : 0,
                'display_after_same_email'        => isset( $_POST['display_after_same_email'] ) ? intval( wp_unslash( $_POST['display_after_same_email'] ) ) : 0,
                'spins'                           => wp_json_encode( $spins_new ),
                'template_setting'                => isset( $_POST['template_setting'] ) ? sanitize_text_field( wp_unslash( $_POST['template_setting'] ) ) : '',
                'card_background'                 => isset( $_POST['card_background'] ) ? sanitize_hex_color( wp_unslash( $_POST['card_background'] ) ) : '',
                'card_color'                      => isset( $_POST['card_color'] ) ? sanitize_hex_color( wp_unslash( $_POST['card_color'] ) ) : '',
                'card_boder_radius'               => isset( $_POST['card_boder_radius'] ) ? intval( wp_unslash( $_POST['card_boder_radius'] ) ) : 0,
                'card_boder_padding'              => isset( $_POST['card_boder_padding'] ) ? intval( wp_unslash( $_POST['card_boder_padding'] ) ) : 0,
                'wheel_center_background'         => isset( $_POST['wheel_center_background'] ) ? sanitize_hex_color( wp_unslash( $_POST['wheel_center_background'] ) ) : '',
                'wheel_center_boder_color'        => isset( $_POST['wheel_center_boder_color'] ) ? sanitize_hex_color( wp_unslash( $_POST['wheel_center_boder_color'] ) ) : '',
                'wheel_center_boder_width'        => isset( $_POST['wheel_center_boder_width'] ) ? intval( wp_unslash( $_POST['wheel_center_boder_width'] ) ) : 0,
                'wheel_center_image_icon'         => isset( $_POST['wheel_center_image_icon'] ) ? sanitize_text_field( wp_unslash( $_POST['wheel_center_image_icon'] ) ) : '',
                'custom_wheel_center_image_icon'  => $custom_image_url,
                'wheel_stroke_border_color'       => isset( $_POST['wheel_stroke_border_color'] ) ? sanitize_hex_color( wp_unslash( $_POST['wheel_stroke_border_color'] ) ) : '',
                'wheel_stroke_border_size'        => isset( $_POST['wheel_stroke_border_size'] ) ? intval( wp_unslash( $_POST['wheel_stroke_border_size'] ) ) : 0,
                'wheel_stroke_font_size'          => isset( $_POST['wheel_stroke_font_size'] ) ? intval( wp_unslash( $_POST['wheel_stroke_font_size'] ) ) : 0,
                'wheel_stroke_font_family'        => isset( $_POST['wheel_stroke_font_family'] ) ? sanitize_text_field( wp_unslash( $_POST['wheel_stroke_font_family'] ) ) : '',
                'wheel_stroke_font_style'         => isset( $_POST['wheel_stroke_font_style'] ) ? sanitize_text_field( wp_unslash( $_POST['wheel_stroke_font_style'] ) ) : '',
                'from_design_alinment'            => isset( $_POST['from_design_alinment'] ) ? sanitize_text_field( wp_unslash( $_POST['from_design_alinment'] ) ) : '',
                'from_button_text'                => isset( $_POST['from_button_text'] ) ? sanitize_text_field( wp_unslash( $_POST['from_button_text'] ) ) : '',
                'from_button_color'               => isset( $_POST['from_button_color'] ) ? sanitize_hex_color( wp_unslash( $_POST['from_button_color'] ) ) : '',
                'from_button_background_color'    => isset( $_POST['from_button_background_color'] ) ? sanitize_hex_color( wp_unslash( $_POST['from_button_background_color'] ) ) : '',
                'initial_button_text'             => isset( $_POST['initial_button_text'] ) ? sanitize_text_field( wp_unslash( $_POST['initial_button_text'] ) ) : '',
                'initial_button_color'            => isset( $_POST['initial_button_color'] ) ? sanitize_hex_color( wp_unslash( $_POST['initial_button_color'] ) ) : '',
                'initial_button_background_color' => isset( $_POST['initial_button_background_color'] ) ? sanitize_hex_color( wp_unslash( $_POST['initial_button_background_color'] ) ) : '',
                'win_message'                     => isset( $_POST['win_message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['win_message'] ) ) : '',
                'loss_message'                    => isset( $_POST['loss_message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['loss_message'] ) ) : '',
                'send_email'                      => isset( $_POST['send_email'] ) ? sanitize_text_field( wp_unslash( $_POST['send_email'] ) ) : 'no',
                'from_name'                       => isset( $_POST['from_name'] ) ? sanitize_text_field( wp_unslash( $_POST['from_name'] ) ) : '',
                'from_address'                    => isset( $_POST['from_address'] ) ? sanitize_email( wp_unslash( $_POST['from_address'] ) ) : '',
                'from_subject'                    => isset( $_POST['from_subject'] ) ? sanitize_text_field( wp_unslash( $_POST['from_subject'] ) ) : '',
                'from_message'                    => isset( $_POST['from_message'] ) ? wp_kses_post( wp_unslash( $_POST['from_message'] ) ) : '',
                'admin_geting_email'              => isset( $_POST['admin_geting_email'] ) ? sanitize_text_field( wp_unslash( $_POST['admin_geting_email'] ) ) : 'no',
            ];

        if (empty($spin_title)) {
            $this->errors['name'] = __('Please insert title', 'webequipe-spin-win-wheel');
        }

        if (!empty($this->errors)) {
            return;
        }

        if ($id) {
            $args['id'] = $id;
        }

        $insert_id = $this->webequipe_sww_insert_spin($args);

        if ( is_wp_error( $insert_id ) ) {
            wp_die( esc_html( $insert_id->get_error_message() ) );
        } 

        $is_new_spin = empty( $id );
        $redirected_id = $id ? $id : $insert_id;
        $active_tab = isset( $_POST['active_tab'] ) ? sanitize_text_field( wp_unslash( $_POST['active_tab'] ) ) : 'General';

        $allowed_sync_providers = [ 'mailchimp', 'klaviyo', 'hubspot', 'activecampaign' ];
        $allowed_capture_modes  = [ 'both', 'win', 'lose' ];

        $sync_enabled = isset( $_POST['sync_with_email_cms'] ) ? 1 : 0;
        $sync_provider = isset( $_POST['sync_provider'] ) ? sanitize_key( wp_unslash( $_POST['sync_provider'] ) ) : 'mailchimp';
        if ( ! in_array( $sync_provider, $allowed_sync_providers, true ) ) {
            $sync_provider = 'mailchimp';
        }

        $sync_capture_mode = isset( $_POST['sync_capture_mode'] ) ? sanitize_key( wp_unslash( $_POST['sync_capture_mode'] ) ) : 'both';
        if ( ! in_array( $sync_capture_mode, $allowed_capture_modes, true ) ) {
            $sync_capture_mode = 'both';
        }

        $sync_settings_map = get_option( 'wsww_spin_sync_settings', [] );
        if ( ! is_array( $sync_settings_map ) ) {
            $sync_settings_map = [];
        }

        $sync_settings_map[ $redirected_id ] = [
            'enabled'      => $sync_enabled,
            'provider'     => $sync_provider,
            'capture_mode' => $sync_capture_mode,
        ];

        update_option( 'wsww_spin_sync_settings', $sync_settings_map );

        // Build redirect URL with all parameters
        $redirect_url = admin_url( 'admin.php' );
        $redirect_url = add_query_arg(
            [
                'page'          => 'wsww-spin',
                'action'         => 'edit',
                'spin-updated'   => $is_new_spin ? 'false' : 'true',
                'spin-created'   => $is_new_spin ? 'true' : 'false',
                'id'             => $redirected_id,
                'active_tab'     => $active_tab,
                '_wpnonce'       => wp_create_nonce( 'wsww_spin_action' ),
            ],
            $redirect_url
        );
        
        wp_safe_redirect( $redirect_url );
        exit();
        }
    }


    
    public function webequipe_sww_insert_spin($args) {
        global $wpdb;
        $table = $wpdb->prefix . 'spin_posts';


        if (!empty($args['id'])) {
            $result = $wpdb->update($table, $args, ['id' => intval($args['id'])]);
            return $args['id'];
        } else {
            $result = $wpdb->insert($table, $args);
            return $wpdb->insert_id;
        }
    }

    public function delete_spin() {

        if ( ! isset( $_REQUEST['_wpnonce'] ) ) {
            wp_die( esc_html__( 'Missing nonce.', 'webequipe-spin-win-wheel' ) );
        }
        $nonce = sanitize_text_field( wp_unslash( $_REQUEST['_wpnonce'] ) );
        if ( ! wp_verify_nonce( $nonce, 'wsww-spin-delete' ) ) {
            wp_die( esc_html__( 'Are you cheating?', 'webequipe-spin-win-wheel' ) );
        }
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Are you cheating?', 'webequipe-spin-win-wheel' ) );
        }
        $id = isset( $_REQUEST['id'] ) ? intval( $_REQUEST['id'] ) : 0;
        if ( webequipe_sww_delete_spin( $id ) ) {
            $redirected_to = admin_url( 'admin.php?page=wsww-spin&spin-deleted=true' );
        } else {
            $redirected_to = admin_url( 'admin.php?page=wsww-spin&spin-deleted=false' );
        }
        // Add nonce to redirect URL for security
        $redirected_to = wp_nonce_url( $redirected_to, 'wsww-message-display', '_wpnonce' );
        wp_safe_redirect( $redirected_to );
        exit;
    }
}
