<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 * Remove astra meta box from product
 *
 * @since 1.0.0
 */
function sbuy_remove_astra_settings_meta_box() {
	remove_meta_box( 'astra_settings_meta_box', 'sbuy_product', 'side' );
}

add_action( 'do_meta_boxes', 'sbuy_remove_astra_settings_meta_box' );

/**
 * Widget for cart page content. sbuy_widget_init()
 *
 * @since 1.0.0
 */
function sbuy_widgets_init() {
	register_sidebar( array(
		'id'   => 'simply-buy-cart-description',
		'name' => esc_html__( 'SimplyBuy Cart Description', 'simply-buy' ),
	) );
}

add_action( 'widgets_init', 'sbuy_widgets_init' );

/**
 * Redirect page when cookie not found
 *
 * @since 1.0.0
 */
function sbuy_page_redirect() {
	global $post;
	if ( ! is_singular() ) {
		return;
	}
	$cookie_name      = sbuy_get_cookie_name();
	$checkout_page_id = sbuy_get_localized_page_id( 'simply_buy_checkout_page' );

	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$token = isset( $_GET['token'] ) ? sanitize_text_field( wp_unslash( $_GET['token'] ) ) : '';
	if ( ( (int) $post->ID === (int) $checkout_page_id ) && ( empty( $token ) ) && ( ! isset( $_COOKIE[ $cookie_name ] ) ) ) {
		sbuy_add_log( 'redirect', 'Redirected user from checkout to cart because cookie was missing.' );
		wp_safe_redirect( get_permalink( sbuy_get_localized_page_id( 'simply_buy_cart_page' ) ) );
		exit;
	}
}

add_action( 'template_redirect', 'sbuy_page_redirect' );

/**
 * Add event in google calendar
 *
 * @since 1.0.0
 */
function sbuy_add_google_calendar_event( $date, $message, $shift, $total_price, $address = '', $name = '' ) {
	// No calendar event without a valid shift — and never insert an "all-day" dummy.
	if ( empty( $shift ) || ! in_array( $shift, array( 'morning', 'afternoon' ), true ) ) {
		sbuy_add_log( 'google_calendar_skipped', 'Skipped calendar event — empty or invalid shift (' . (string) $shift . ')' );
		return;
	}

	$google_auth = sbuy_get_options( 'google_service_account_json', 'sbuy_settings_google' );
	$calendar_id = sbuy_get_options( 'calendar_id', 'sbuy_settings_google' );

	if ( ! empty( $google_auth ) && ! empty( $calendar_id ) ) {
		$time_settings = get_option( 'sbuy_settings_time' );
		$day           = gmdate( 'w', $date );
		switch ( $shift ) {
			case 'morning':
				$morning_start_time = $time_settings['slot_time'][ $day ]['morning_from'];
				$morning_end_time   = $time_settings['slot_time'][ $day ]['morning_to'];
				$start_time         = sbuy_format_date_time( $date, $morning_start_time );
				$end_time           = sbuy_format_date_time( $date, $morning_end_time );
				break;

			case 'afternoon':
				$afternoon_start_time = $time_settings['slot_time'][ $day ]['afternoon_from'];
				$afternoon_end_time   = $time_settings['slot_time'][ $day ]['afternoon_to'];
				$start_time           = sbuy_format_date_time( $date, $afternoon_start_time );
				$end_time             = sbuy_format_date_time( $date, $afternoon_end_time );
				break;
		}
		try {
			$google_auth = json_decode( sbuy_get_options( 'google_service_account_json', 'sbuy_settings_google' ), true );
			$client      = new Google\Client();
			$client->setAuthConfig( $google_auth );
			$client->addScope( Google_Service_Calendar::CALENDAR );
			$service    = new Google_Service_Calendar( $client );
			$event      = new Google_Service_Calendar_Event();

			/* translators: %s: total price */
			$event->setSummary( wp_sprintf( esc_html__( '%s - Tour', 'simply-buy' ), sanitize_text_field( $total_price ) ) );
			$start = new Google_Service_Calendar_EventDateTime();
			$start->setDateTime( $start_time );
			$event->setStart( $start );
			$end = new Google_Service_Calendar_EventDateTime();
			$end->setDateTime( $end_time );
			$event->setEnd( $end );
			$event->setDescription( $message );

			if ( ! empty( $address ) ) {
				$event->setLocation( sanitize_text_field( $address ) );
			}

			$service->events->insert( $calendar_id, $event );
			sbuy_add_log( 'google_calendar', 'Added Google Calendar event on ' . $start_time . ' - ' . $end_time );
		} catch ( Exception $e ) {
			sbuy_add_log( 'google_calendar_error', 'Google Calendar API error: ' . $e->getMessage() . ' (Code: ' . $e->getCode() . ')' );

			// Notify the shop admin so they can add the booking manually.
			$to = sbuy_get_options( 'notification_email', 'sbuy_settings_email' );
			if ( empty( $to ) || ! is_email( $to ) ) {
				$to = get_option( 'admin_email' );
			}
			wp_mail(
				$to,
				'⚠️ ' . esc_html__( 'Calendar entry failed - manual action required!', 'simply-buy' ),
				sprintf(
					/* translators: 1: customer name, 2: booking start time, 3: API error message */
					__( "WARNING: The booking from %1\$s on %2\$s was NOT added to Google Calendar.\n\nPlease add it manually!\n\nError: %3\$s", 'simply-buy' ),
					$name ?: __( 'a customer', 'simply-buy' ),
					$start_time ?? '',
					$e->getMessage()
				),
				array( 'Content-Type: text/plain; charset=UTF-8' )
			);
		}
	}
}

add_action( 'sbuy_add_google_calendar_event', 'sbuy_add_google_calendar_event', 10, 6 );


/**
 * Insert booking in database.
 *
 * @param string $date Date.
 * @param string $shift Shift/slot.
 *
 * @since 1.0.0
 */
function sbuy_booking_insert_callback( $date, $shift ) {
	global $wpdb;
	$table_name         = $wpdb->prefix . 'sbuy_booking';
	$sbuy_has_available_slot = sbuy_has_available_slot( $date );
	if ( $sbuy_has_available_slot <= 6 ) {
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
		$wpdb->insert( $table_name, array(
			'date' => $date,
			'slot' => $shift,
		) );
		sbuy_add_log( 'booking', 'Inserted booking for date ' . $date . ' and shift ' . $shift );
	}
}

add_action( 'sbuy_booking_insert', 'sbuy_booking_insert_callback', 10, 2 );

/**
 * Send booking to email
 *
 * @param string $message Message.
 * @param string $name Name.
 * @param string $email Email.
 *
 * @since 1.0.0
 */
function sbuy_booking_email_callback( $message, $name, $email ) {
	$site_title         = get_bloginfo( 'name' );
	$site_url           = home_url();
	$domain             = wp_parse_url( $site_url, PHP_URL_HOST );
	$notification_email = sbuy_get_options( 'notification_email', 'sbuy_settings_email' );
	$to                 = apply_filters( 'sbuy_email', ! empty( $notification_email ) ? $notification_email : get_option( 'admin_email' ) );

	/* translators: %s: site title */
	$subject = wp_sprintf( esc_html__( 'New booking for %s', 'simply-buy' ), esc_html( $site_title ) );

	$headers     = array(
		'Content-Type: text/html; charset=UTF-8',
		"From: $site_title <no-reply@$domain>",
	);
	$clean_name  = sanitize_text_field( $name );
	$clean_email = sanitize_email( $email );
	if ( ! empty( $clean_email ) && is_email( $clean_email ) ) {
		$headers[] = ! empty( $clean_name )
			? "Reply-To: $clean_name <$clean_email>"
			: "Reply-To: $clean_email";
	}

	$admin_mail_sent = wp_mail( $to, $subject, $message, $headers );

	$from     = sbuy_get_options( 'email_from', 'sbuy_settings_email' ) ?: 'SimplyBuy';
	$reply_to = sbuy_get_options( 'reply_to_email', 'sbuy_settings_email' );
	$headers  = array( 'Content-Type: text/html; charset=UTF-8', "From: $from <no-reply@$domain>" );
	if ( ! empty( $reply_to ) && is_email( $reply_to ) ) {
		$headers[] = "Reply-To: $reply_to";
	}

	$subject        = sbuy_get_options( 'email_subject', 'sbuy_settings_email' ) ?: $subject;
	$user_mail_sent = wp_mail( $email, $subject, $message, $headers );

	if ( $admin_mail_sent && $user_mail_sent ) {
		sbuy_add_log( 'email', 'Booking email successfully sent to ' . $email );
		wp_send_json_success( array( 'message' => esc_html__( 'Successfully mail send', 'simply-buy' ) ) );
	} else {
		sbuy_add_log( 'email_error', 'Booking email failed for ' . $email );
		wp_send_json_error( array( 'message' => esc_html__( 'Mail send failed', 'simply-buy' ) ) );
	}
}

add_action( 'sbuy_booking_email', 'sbuy_booking_email_callback', 10, 3 );

/**
 * Update option and add table for new site in multisite.
 *
 * @param object $new_site New site object.
 * @param array $args Args.
 *
 * @since 1.0.0
 */
function sbuy_setup_multisite_action( $new_site, $args ) {
	if ( is_plugin_active_for_network( 'simply-buy/simply-buy.php' ) ) {
		global $wpdb;

		$blog_id = $new_site->blog_id;
		switch_to_blog( $blog_id );

		$cart_shortcode     = '[simply-buy-cart]';
		$checkout_shortcode = '[simply-buy-checkout]';
		$thankyou_content   = esc_html__( 'Thank you for scheduling.', 'simply-buy' );

		if ( sbuy_is_gutenberg_enable() ) {
			$cart_shortcode     = '<!-- wp:shortcode -->[simply-buy-cart]<!-- /wp:shortcode -->';
			$checkout_shortcode = '<!-- wp:shortcode -->[simply-buy-checkout]<!-- /wp:shortcode -->';
			$thankyou_content   = '<!-- wp:paragraph --><p>' . esc_html__( 'Thank you for scheduling.', 'simply-buy' ) . '</p><!-- /wp:paragraph -->';
		}

		// Create cart page object.
		$cart_page = array(
			'post_title'     => wp_strip_all_tags( esc_html__( 'Cart', 'simply-buy' ) ),
			'post_content'   => $cart_shortcode,
			'post_status'    => 'publish',
			'post_type'      => 'page',
			'comment_status' => 'closed',
			'ping_status'    => 'closed',
		);

		$cart_page_id = ! sbuy_get_options( 'simply_buy_cart_page', 'sbuy_settings_pages' ) ? wp_insert_post( $cart_page ) : sbuy_get_options( 'simply_buy_cart_page', 'sbuy_settings_pages' );

		// Create checkout page object.
		$checkout_page = array(
			'post_title'     => wp_strip_all_tags( esc_html__( 'Checkout', 'simply-buy' ) ),
			'post_content'   => $checkout_shortcode,
			'post_status'    => 'publish',
			'post_type'      => 'page',
			'post_parent'    => $cart_page_id,
			'comment_status' => 'closed',
			'ping_status'    => 'closed',
		);

		$checkout_page_id = ! sbuy_get_options( 'simply_buy_checkout_page', 'sbuy_settings_pages' ) ? wp_insert_post( $checkout_page ) : sbuy_get_options( 'simply_buy_checkout_page', 'sbuy_settings_pages' );

		// Create thank you page object.
		$thankyou_page = array(
			'post_title'     => wp_strip_all_tags( esc_html__( 'Thank you', 'simply-buy' ) ),
			'post_content'   => $thankyou_content,
			'post_status'    => 'publish',
			'post_type'      => 'page',
			'post_parent'    => $cart_page_id,
			'comment_status' => 'closed',
			'ping_status'    => 'closed',
		);

		$thankyou_page_id = ( ! sbuy_get_options( 'simply_buy_thankyou_page', 'sbuy_settings_pages' ) ) ? wp_insert_post( $thankyou_page ) : sbuy_get_options( 'simply_buy_thankyou_page', 'sbuy_settings_pages' );

		$default_pages = array(
			'simply_buy_cart_page'     => $cart_page_id,
			'simply_buy_checkout_page' => $checkout_page_id,
			'simply_buy_thankyou_page' => $thankyou_page_id,
		);

		update_option( 'sbuy_settings_pages', $default_pages );
		sbuy_add_log( 'multisite', 'Initialized default pages and time settings for new site ID ' . $blog_id );

		$default_times = sbuy_create_default_time( 0, 6 );
		update_option( 'sbuy_settings_time', $default_times );

		$table_name = $wpdb->prefix . 'sbuy_booking';

		$charset_collate = $wpdb->get_charset_collate();

		$sql = "CREATE TABLE $table_name (
		id mediumint(9) NOT NULL AUTO_INCREMENT,
		date tinytext NOT NULL,
		slot tinytext NOT NULL,
		PRIMARY KEY  (id)
		) $charset_collate;";

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		dbDelta( $sql );

		restore_current_blog();
	}
}

add_action( 'wp_initialize_site', 'sbuy_setup_multisite_action', 10, 2 );


if ( ! function_exists( 'sbuy_manager_menu_pages' ) ) {
	/**
	 * Menu pages for SimplyBuy Manager
	 *
	 * @since 1.0.1
	 */
	function sbuy_manager_menu_pages() {

		$user = wp_get_current_user();

		if ( in_array( 'sbuy_manager', $user->roles, true ) ) {

			global $menu;

			foreach ( $menu as $single_menu ) {
				if ( isset( $single_menu[2] ) && trim( strlen( $single_menu[2] ) > 0 ) ) {
					$slug = $single_menu[2];
					switch ( $slug ) {
						case 'simply-buy':
						case 'profile.php':
							break;
						default:
							remove_menu_page( $slug );
					}
				}
			}
		}
	}
}
add_action( 'admin_menu', 'sbuy_manager_menu_pages', 9999 );
