<?php
/**
 * APBGF Setup Wizard
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'APBGF_Wizard' ) ) {

	class APBGF_Wizard {

		private static $instance = null;

		private function __construct() {
			add_action( 'admin_menu', array( $this, 'register_menu' ), 20 );
			add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
			add_action( 'wp_ajax_apbgf_wizard_save_step', array( $this, 'ajax_save_step' ) );
			add_action( 'wp_ajax_apbgf_wizard_complete', array( $this, 'ajax_complete' ) );
			add_action( 'wp_ajax_apbgf_wizard_skip_setup', array( $this, 'ajax_skip_setup' ) );
		}

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

		public function register_menu() {
			add_submenu_page(
				'appointment-and-booking-for-gravity-forms',
				__( 'Setup Wizard - Appointment and Booking for Gravity Forms', 'apbgf' ),
				__( 'Setup Wizard', 'apbgf' ),
				'manage_options',
				'apbgf-setup-wizard',
				array( $this, 'render_page' ),
				0
			);
		}

	public function render_page() {
		$wizard_completed = get_option( 'apbgf_wizard_completed', false );
		
		// Redirect to report page if wizard is already completed
		if ( $wizard_completed ) {
			wp_safe_redirect( admin_url( 'admin.php?page=apbgf-report' ) );
			exit;
		}
		
		echo '<div class="wrap"><div id="apbgf-wizard-root"></div></div>';
	}

		public function enqueue_assets( $hook ) {
			// Check if we're on the setup wizard page
			$page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
			if ( 'apbgf-setup-wizard' !== $page ) {
				return;
			}

			if ( defined( 'APBGF_LIVE_MODE' ) && APBGF_LIVE_MODE ) {
				$minimized = '.min';
				$clear_cache = '';
			} else {
				$minimized = '';
				$clear_cache = '?t=' . gmdate('ymdhis');
			}

			wp_enqueue_style(
				'apbgf-admin-style',
				APBGF_ADMIN_CSS_URL . 'apbgf-admin-style' . $minimized . '.css',
				array(),
				APBGF_VERSION . $clear_cache
			);

			$deps = array( 'wp-element', 'wp-i18n' );
			$ver  = APBGF_VERSION . $clear_cache;

			$asset_path = APBGF_PATH . 'includes/build/index.bundle.asset.php';
			$bundle_url = plugins_url( 'includes/build/index.bundle.js', APBGF_FILE );

			if ( file_exists( $asset_path ) ) {
				$asset = include $asset_path;
				if ( isset( $asset['dependencies'] ) && is_array( $asset['dependencies'] ) ) {
					$deps = array_unique( array_merge( $deps, $asset['dependencies'] ) );
				}
				if ( ! empty( $asset['version'] ) ) {
					$ver = $asset['version'];
				}
			}

			wp_enqueue_script( 'apbgf-wizard-bundle', $bundle_url, $deps, $ver, true );

			$settings = get_option( 'apbgf_settings', array() );

			wp_localize_script( 'apbgf-wizard-bundle', 'apbgf_wizard', array(
				'ajaxurl'      => admin_url( 'admin-ajax.php' ),
				'nonce'        => wp_create_nonce( 'apbgf' ),
				'settings'     => $settings,
			) );
		}

		public function ajax_save_step() {
			check_ajax_referer( 'apbgf', 'nonce' );
			$data = $_POST;
			$type = isset( $data['type'] ) ? sanitize_text_field( $data['type'] ) : '';
			$payload = isset( $data['payload'] ) ? wp_unslash( $data['payload'] ) : array();
			if ( is_string( $payload ) ) {
				$payload = json_decode( $payload, true );
			}

			$settings = get_option( 'apbgf_settings', array() );
			if ( $type && is_array( $payload ) ) {
				$settings[ $type ] = array_merge( isset( $settings[ $type ] ) ? (array) $settings[ $type ] : array(), $payload );
				update_option( 'apbgf_settings', $settings );
			}

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

		public function ajax_complete() {
			check_ajax_referer( 'apbgf', 'nonce' );
			$payload = isset( $_POST['payload'] ) ? wp_unslash( $_POST['payload'] ) : array();
			if ( is_string( $payload ) ) {
				$payload = json_decode( $payload, true );
			}
			
			if ( is_array( $payload ) ) {
				$settings = get_option( 'apbgf_settings', array() );
				
				// Save company data
				if ( isset( $payload['company'] ) && is_array( $payload['company'] ) ) {
					$company_data = array();
					if ( isset( $payload['company']['apbgf_company_name'] ) ) {
						$company_data['apbgf_company_name'] = sanitize_text_field( $payload['company']['apbgf_company_name'] );
					}
					if ( isset( $payload['company']['apbgf_company_address'] ) ) {
						$company_data['apbgf_company_address'] = sanitize_text_field( $payload['company']['apbgf_company_address'] );
					}
					if ( isset( $payload['company']['apbgf_company_number'] ) ) {
						$company_data['apbgf_company_number'] = sanitize_text_field( $payload['company']['apbgf_company_number'] );
					}
					if ( isset( $payload['company']['apbgf_company_email'] ) ) {
						$company_data['apbgf_company_email'] = sanitize_email( $payload['company']['apbgf_company_email'] );
					}
					if ( isset( $payload['company']['apbgf_company_website_url'] ) ) {
						$company_data['apbgf_company_website_url'] = esc_url_raw( $payload['company']['apbgf_company_website_url'] );
					}
					$settings['company'] = $company_data;
				}
				
				// Save general settings
				if ( isset( $payload['general'] ) && is_array( $payload['general'] ) ) {
					$general_data = array();
					if ( isset( $payload['general']['apbgf_start_of_week'] ) ) {
						$general_data['apbgf_start_of_week'] = sanitize_text_field( $payload['general']['apbgf_start_of_week'] );
					}
					if ( isset( $payload['general']['gbf_start_of_week'] ) ) {
						$general_data['gbf_start_of_week'] = sanitize_text_field( $payload['general']['gbf_start_of_week'] );
					}
					if ( isset( $payload['general']['apbgf_calendar_timeslot_format'] ) ) {
						$general_data['apbgf_calendar_timeslot_format'] = sanitize_text_field( $payload['general']['apbgf_calendar_timeslot_format'] );
					}
					if ( isset( $payload['general']['apbgf_time_interval'] ) ) {
						$general_data['apbgf_time_interval'] = sanitize_text_field( $payload['general']['apbgf_time_interval'] );
					}
					if ( isset( $payload['general']['gbf_time_interval'] ) ) {
						$general_data['gbf_time_interval'] = sanitize_text_field( $payload['general']['gbf_time_interval'] );
					}
					if ( isset( $payload['general']['apbgf_time_duration'] ) ) {
						$general_data['apbgf_time_duration'] = sanitize_text_field( $payload['general']['apbgf_time_duration'] );
					}
					if ( isset( $payload['general']['gbf_time_duration'] ) ) {
						$general_data['gbf_time_duration'] = sanitize_text_field( $payload['general']['gbf_time_duration'] );
					}
					$settings['general'] = $general_data;
				}
				
				update_option( 'apbgf_settings', $settings );
			}

			$default_term = term_exists( 'Uncategorized', 'apbgf-service-category' );
			if ( 0 === $default_term || null === $default_term ) {
				$default_term = wp_insert_term( 'Uncategorized', 'apbgf-service-category' );
			}
			$default_term_id = is_array( $default_term ) ? $default_term['term_id'] : (int) $default_term;

			$default_location = false;
			if ( class_exists( 'APBGF_Location' ) ) {
				$default_location = \APBGF_Location::all_location();
			}
			if ( ! $default_location ) {
				$existing = get_posts( array(
					'post_type'   => 'apbgf-location',
					'meta_key'    => '_apbgf_default_location',
					'meta_value'  => '1',
					'numberposts' => 1,
				) );
				if ( ! empty( $existing ) ) {
					$default_location = $existing[0];
				} else {
					$location_id = wp_insert_post( array(
						'post_title'   => 'Default Location',
						'post_content' => '',
						'post_status'  => 'publish',
						'post_type'    => 'apbgf-location',
					) );
					if ( $location_id && ! is_wp_error( $location_id ) ) {
						update_post_meta( $location_id, '_apbgf_default_location', '1' );
						$default_location = get_post( $location_id );
					}
				}
			}
			$default_location_id = $default_location ? (int) $default_location->ID : 0;

            $created_service_ids = array();
			if ( isset( $payload['services'] ) && is_array( $payload['services'] ) ) {
				foreach ( $payload['services'] as $service ) {
					$name  = isset( $service['name'] ) ? sanitize_text_field( $service['name'] ) : '';
					$price = isset( $service['price'] ) ? sanitize_text_field( $service['price'] ) : '';
					if ( '' !== $name ) {
						$post_id = wp_insert_post( array(
							'post_title' => $name,
							'post_type' => 'apbgf-service',
							'post_status' => 'publish',
							'meta_input' => array( 'price' => $price, 'category' => $default_term_id ),
						) );
						if ( $post_id && ! is_wp_error( $post_id ) ) {
							wp_set_post_terms( $post_id, array( $default_term_id ), 'apbgf-service-category' );
							if ( $default_location_id > 0 ) {
								update_post_meta( $post_id, 'location', array( $default_location_id ) );
							}
                            $created_service_ids[] = (int) $post_id;
						}
					}
				}
			}

			$user_id = get_current_user_id();
			if ( $user_id ) {
				$user = new WP_User( $user_id );
				$user->add_role( 'apbgf-staff' );
				$exists = get_user_meta( $user_id, 'apbgf_user', true );
				$staff_post_id = 0;
				if ( empty( $exists ) ) {
					$staff_name = trim( $user->first_name . ' ' . $user->last_name );
					if ( empty( $staff_name ) ) {
						$staff_name = ! empty( $user->display_name ) ? $user->display_name : $user->user_login;
					}
					$staff_post = wp_insert_post( array(
						'post_title'  => $staff_name,
						'post_type'   => 'apbgf-staff',
						'post_status' => 'publish',
						'meta_input'  => array( 'wp_user' => $user_id ),
					) );
					if ( $staff_post && ! is_wp_error( $staff_post ) ) {
						update_user_meta( $user_id, 'apbgf_user', $staff_post );
                        $staff_post_id = (int) $staff_post;
					}
				} else {
                    $staff_post_id = (int) $exists;
					$existing_staff_post = get_post( $staff_post_id );
					if ( $existing_staff_post && empty( trim( $existing_staff_post->post_title ) ) ) {
						$staff_name = trim( $user->first_name . ' ' . $user->last_name );
						if ( empty( $staff_name ) ) {
							$staff_name = ! empty( $user->display_name ) ? $user->display_name : $user->user_login;
						}
						wp_update_post( array(
							'ID' => $staff_post_id,
							'post_title' => $staff_name,
						) );
					}
                }

                if ( $staff_post_id && ! empty( $created_service_ids ) ) {
                    $services_map = array();
                    foreach ( $created_service_ids as $sid ) {
                        $svc_price = get_post_meta( $sid, 'price', true );
                        $services_map[ $sid ] = array( 'available' => 'yes', 'price' => $svc_price );
                    }
                    update_post_meta( $staff_post_id, 'services', $services_map );
                }

                if ( $staff_post_id && isset( $payload['staff'] ) && is_array( $payload['staff'] ) ) {
                    $booking_type = isset( $payload['staff']['apbgf_booking_type'] ) ? sanitize_text_field( $payload['staff']['apbgf_booking_type'] ) : 'custom';
                    $timings_in   = isset( $payload['staff']['timings'] ) && is_array( $payload['staff']['timings'] ) ? $payload['staff']['timings'] : array();
                    $timings_save = array();
                    foreach ( $timings_in as $day => $t ) {
                        $start    = isset( $t['start'] ) ? sanitize_text_field( $t['start'] ) : '';
                        $end      = isset( $t['end'] ) ? sanitize_text_field( $t['end'] ) : '';
                        $capacity = isset( $t['capacity'] ) ? intval( $t['capacity'] ) : 1;
                        $switch   = isset( $t['switch'] ) ? (bool) $t['switch'] : true;
                        $breaks   = array();
                        if ( isset( $t['breaks'] ) && is_array( $t['breaks'] ) ) {
                            foreach ( $t['breaks'] as $b ) {
                                $breaks[] = sanitize_text_field( $b );
                            }
                        }
                        if ( $switch ) {
                            $timings_save[ $day ] = array(
								'switch'   => true,
                                'start'    => $start ?: '09:00',
                                'end'      => $end ?: '17:00',
                                'capacity' => max( 1, $capacity ),
                                'break'    => $breaks,
                            );
                        }
                    }
					
                    update_post_meta( $staff_post_id, 'timings', $timings_save );
                    update_post_meta( $staff_post_id, 'booking_type', in_array( $booking_type, array( 'custom', 'fullday' ), true ) ? $booking_type : 'custom' );

                    if ( isset( $payload['general']['apbgf_time_duration'] ) ) {
                        update_post_meta( $staff_post_id, 'time_duration', sanitize_text_field( $payload['general']['apbgf_time_duration'] ) );
                    }
                    if ( isset( $payload['general']['apbgf_time_interval'] ) ) {
                        update_post_meta( $staff_post_id, 'time_interval', sanitize_text_field( $payload['general']['apbgf_time_interval'] ) );
                    }
                }

				if ( $staff_post_id && class_exists( 'APBGF_Staff' ) ) {
                    \APBGF_Staff::get_staff_data_by_id( $staff_post_id );
                }
			}

			$form_id = $this->maybe_create_booking_form();
			if ( $form_id ) {
				$this->maybe_set_default_apbgf_form_settings( $form_id );
				if ( class_exists( 'GFAPI' ) ) {
					$form = \GFAPI::get_form( $form_id );
					if ( is_array( $form ) && isset( $form['fields'] ) && is_array( $form['fields'] ) ) {
						$updated = false;
						foreach ( $form['fields'] as &$field ) {
							if ( isset( $field->type ) && 'apbgf_appointment_calendar' === $field->type ) {
								$field->apbgf_service_category = array( (int) $default_term_id );
								$field->apbgf_service_category_hide = true;
								$field->apbgf_location_hide = true;
								if ( $default_location_id > 0 ) {
									$field->apbgf_location = $default_location_id;
								}
								$updated = true;
								break;
							}
						}
						if ( $updated ) {
							\GFAPI::update_form( $form );
						}
					}
				}
			}
			$page_ids = $this->maybe_create_pages( $form_id );

			$pages = array();
			if ( ! empty( $page_ids['form_page'] ) ) {
				$form_page_id = (int) $page_ids['form_page'];
				$pages['form'] = array(
					'id'        => $form_page_id,
					'url'       => get_permalink( $form_page_id ),
					'shortcode' => $form_id ? sprintf( '[gravityform id="%d"]', $form_id ) : '',
				);
			}

			if ( ! empty( $page_ids['appointments_page'] ) ) {
				$app_page_id = (int) $page_ids['appointments_page'];
				$pages['appointments'] = array(
					'id'        => $app_page_id,
					'url'       => get_permalink( $app_page_id ),
					'shortcode' => '[apbgf_customer_appointments]',
				);
			}

			update_option( 'apbgf_wizard_completed', true );

			wp_send_json_success( array( 'form_id' => $form_id, 'pages' => $pages ) );
		}

		public function ajax_skip_setup() {
			check_ajax_referer( 'apbgf', 'nonce' );
			update_option( 'apbgf_wizard_completed', true );
			wp_send_json_success( array( 'skipped' => true ) );
		}

		private function maybe_create_booking_form() {
			if ( ! class_exists( 'GFAPI' ) ) {
				return 0;
			}
			$forms = GFAPI::get_forms();
			foreach ( $forms as $form ) {
				if ( isset( $form['title'] ) && 'Booking Form' === $form['title'] ) {
					return (int) $form['id'];
				}
			}

			$form = array(
				'title'  => 'Booking Form',
				'fields' => array(
					array(
						'type'  => 'name',
						'id'    => 1,
						'label' => 'Name',
						'inputs' => array(
							array( 'id' => '1.3', 'label' => 'First' ),
							array( 'id' => '1.6', 'label' => 'Last' ),
						),
					),
					array( 'type' => 'email', 'id' => 2, 'label' => 'Email' ),
					array( 'type' => 'phone', 'id' => 3, 'label' => 'Phone Number' ),
					array( 'type' => 'apbgf_appointment_calendar', 'id' => 4, 'label' => 'APBGF Calendar' ),
					array( 'type' => 'total', 'id' => 5, 'label' => 'Total' ),
				),
			);
			$result = GFAPI::add_form( $form );
			return is_wp_error( $result ) ? 0 : (int) $result;
		}

		private function maybe_create_pages( $form_id ) {
			$created = array();
			$slug = 'booking-form';
			$existing = get_page_by_path( $slug );
			if ( ! $existing ) {
				$content = $form_id ? sprintf( '[gravityform id="%d" title="false" description="false" ajax="true"]', $form_id ) : '';
				$page_id = wp_insert_post( array(
					'post_title'   => 'Booking Form',
					'post_name'    => $slug,
					'post_type'    => 'page',
					'post_status'  => 'publish',
					'post_content' => $content,
				) );
				$created['form_page'] = $page_id;
			} else {
				$created['form_page'] = $existing->ID;
			}

			$slug2 = 'booking-appointments';
			$existing2 = get_page_by_path( $slug2 );
			if ( ! $existing2 ) {
				$page_id2 = wp_insert_post( array(
					'post_title'   => 'Booking Appointments',
					'post_name'    => $slug2,
					'post_type'    => 'page',
					'post_status'  => 'publish',
					'post_content' => '[apbgf_customer_appointments]',
				) );
				$created['appointments_page'] = $page_id2;
			} else {
				$created['appointments_page'] = $existing2->ID;
			}
			return $created;
		}

		private function maybe_set_default_apbgf_form_settings( $form_id ) {
			$option_key = 'apbgf_form_settings_' . (int) $form_id;
			$settings = get_option( $option_key );
			if ( false === $settings || ! is_array( $settings ) ) {
				$settings = array();
			}
			$settings['registration_field'] = array(
				'fname' => '1.3',
				'lname' => '1.6',
				'email' => '2',
				'phone' => '3',
			);
			update_option( $option_key, $settings );
		}
	}

	APBGF_Wizard::get_instance();
}