<?php
/**
 * Hub API helpers for maca Restu Pro (shared by REST layer).
 *
 * @package Maca_Menu_List_Pro
 */

defined( 'ABSPATH' ) || exit;

/**
 * Site key stored by maca Sec Hub reporter.
 *
 * @return string
 */
function maca_restu_hub_get_site_key() {
	return trim( (string) get_option( 'maca_sec_hub_site_key', '' ) );
}

/**
 * @param string $key License key.
 * @return string
 */
function maca_restu_hub_mask_license_key( $key ) {
	$key = trim( (string) $key );
	if ( '' === $key ) {
		return '';
	}
	if ( strlen( $key ) <= 8 ) {
		return str_repeat( '*', strlen( $key ) );
	}

	return substr( $key, 0, 4 ) . str_repeat( '*', max( 4, strlen( $key ) - 8 ) ) . substr( $key, -4 );
}

/**
 * Count rows in a plugin table.
 *
 * @param string $table Table name.
 * @param string $where SQL WHERE clause without WHERE keyword.
 * @return int
 */
function maca_restu_hub_count_table_rows( $table, $where = '1=1' ) {
	global $wpdb;

	if ( ! isset( $wpdb ) || '' === $table ) {
		return 0;
	}

	$allowed_tables = array();
	if ( function_exists( 'maca_menulist_db_categories_table' ) ) {
		$allowed_tables[] = maca_menulist_db_categories_table();
		$allowed_tables[] = maca_menulist_db_menus_table();
	}
	if ( function_exists( 'maca_menulist_db_dishes_table' ) ) {
		$allowed_tables[] = maca_menulist_db_dishes_table();
	}

	$matched = false;
	foreach ( $allowed_tables as $allowed_table ) {
		if ( (string) $table === (string) $allowed_table ) {
			$table   = esc_sql( $allowed_table );
			$matched = true;
			break;
		}
	}
	if ( ! $matched ) {
		return 0;
	}

	$allowed_where = array(
		'1=1'           => '1=1',
		'is_active = 1' => 'is_active = 1',
	);
	$where_sql = isset( $allowed_where[ $where ] ) ? $allowed_where[ $where ] : '1=1';

	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name allowlisted + esc_sql; WHERE allowlisted.
	return (int) $wpdb->get_var( "SELECT COUNT(*) FROM `{$table}` WHERE {$where_sql}" );
}

/**
 * Menu/category/dish counts for Hub overview.
 *
 * @return array<string, int>
 */
function maca_restu_hub_get_content_counts() {
	$counts = array(
		'category_count'    => 0,
		'menu_count'        => 0,
		'active_menu_count' => 0,
		'dish_count'        => 0,
		'active_dish_count' => 0,
	);

	if ( function_exists( 'maca_menulist_db_categories_table' ) ) {
		$categories_table = maca_menulist_db_categories_table();
		$menus_table      = maca_menulist_db_menus_table();
		$counts['category_count']    = maca_restu_hub_count_table_rows( $categories_table );
		$counts['menu_count']        = maca_restu_hub_count_table_rows( $menus_table );
		$counts['active_menu_count'] = maca_restu_hub_count_table_rows( $menus_table, 'is_active = 1' );
	}

	if ( function_exists( 'maca_menulist_db_dishes_table' ) ) {
		$dishes_table = maca_menulist_db_dishes_table();
		$counts['dish_count']        = maca_restu_hub_count_table_rows( $dishes_table );
		$counts['active_dish_count'] = maca_restu_hub_count_table_rows( $dishes_table, 'is_active = 1' );
	}

	return $counts;
}

/**
 * Action items for Hub (dashboard todos without admin URLs).
 *
 * @return array<int, array<string, mixed>>
 */
function maca_restu_hub_get_action_items() {
	if ( ! function_exists( 'maca_menulist_get_dashboard_action_items' ) ) {
		require_once MACA_MENULIST_PLUGIN_DIR . 'includes/dashboard-data.php';
	}

	$items = function_exists( 'maca_menulist_get_dashboard_action_items' )
		? maca_menulist_get_dashboard_action_items()
		: array();

	if ( ! function_exists( 'maca_menulist_is_dishes_mode' ) || ! maca_menulist_is_dishes_mode() ) {
		$counts = maca_restu_hub_get_content_counts();
		if ( 0 === $counts['category_count'] ) {
			$items[] = array(
				'key'      => 'no_categories',
				'severity' => 'warning',
				'count'    => 0,
				'label'    => __( 'Inga menykategorier har skapats ännu.', 'maca-restu-pro' ),
			);
		}
		if ( $counts['category_count'] > 0 && 0 === $counts['menu_count'] ) {
			$items[] = array(
				'key'      => 'no_menus',
				'severity' => 'warning',
				'count'    => 0,
				'label'    => __( 'Inga menyer har lagts till ännu.', 'maca-restu-pro' ),
			);
		}
	}

	return $items;
}

/**
 * Strip admin URLs from action items for Hub.
 *
 * @param array<int, array<string, mixed>> $items Action rows.
 * @return array<int, array<string, mixed>>
 */
function maca_restu_hub_format_action_items( array $items ) {
	$output = array();

	foreach ( $items as $item ) {
		if ( ! is_array( $item ) ) {
			continue;
		}

		$severity = isset( $item['severity'] ) ? sanitize_key( (string) $item['severity'] ) : 'info';
		if ( ! in_array( $severity, array( 'warning', 'info', 'error' ), true ) ) {
			$severity = 'info';
		}

		$output[] = array(
			'key'      => isset( $item['key'] ) ? sanitize_key( (string) $item['key'] ) : '',
			'severity' => $severity,
			'count'    => isset( $item['count'] ) ? (int) $item['count'] : 0,
			'label'    => isset( $item['label'] ) ? wp_strip_all_tags( (string) $item['label'] ) : '',
		);
	}

	return $output;
}

/**
 * License summary for maca Hub.
 *
 * @return array<string, mixed>
 */
function maca_restu_hub_get_license_status() {
	if ( ! class_exists( 'Maca_MenuList_License', false ) ) {
		return array(
			'available'     => false,
			'product'       => 'maca_restu_pro',
			'product_label' => 'maca Restu Pro',
		);
	}

	$license  = Maca_MenuList_License::instance();
	$data     = $license->get_stored_license();
	$key      = isset( $data['license_key'] ) ? (string) $data['license_key'] : '';
	$licensed = $license->is_active();
	$expires_ts = $license->get_license_expiry_timestamp( $data );
	$days = null;
	if ( $expires_ts > 0 ) {
		$days = $license->get_calendar_days_until_expiry( $expires_ts );
	}

	$status = isset( $data['status'] ) ? sanitize_key( (string) $data['status'] ) : '';
	if ( $licensed ) {
		$status_label = __( 'Pro aktiv', 'maca-restu-pro' );
	} elseif ( '' !== $key ) {
		$status_label = __( 'Licens ogiltig', 'maca-restu-pro' );
	} else {
		$status_label = __( 'Ingen licens', 'maca-restu-pro' );
	}

	return array(
		'available'        => true,
		'product'          => 'maca_restu_pro',
		'product_label'    => 'maca Restu Pro',
		'has_key'          => '' !== $key,
		'masked_key'       => '' !== $key ? maca_restu_hub_mask_license_key( $key ) : '',
		'licensed'         => $licensed,
		'is_pro'           => $licensed,
		'status'           => $status !== '' ? $status : ( $licensed ? 'active' : 'inactive' ),
		'status_label'     => $status_label,
		'plan'             => isset( $data['plan'] ) ? sanitize_key( (string) $data['plan'] ) : '',
		'expires_at'       => $expires_ts > 0 ? gmdate( 'c', $expires_ts ) : null,
		'days_remaining'   => $days,
		'is_expiring_soon' => $days !== null && $days >= 0 && $days <= 5,
		'upgrade_url'      => method_exists( $license, 'get_subscribe_url' ) ? (string) $license->get_subscribe_url() : 'https://maca.se/restu-pro/',
		'plugin_version'   => defined( 'MACA_MENULIST_VERSION' ) ? MACA_MENULIST_VERSION : '',
	);
}

/**
 * Full maca Restu Pro status for maca Hub.
 *
 * @return array<string, mixed>
 */
function maca_restu_hub_get_status() {
	if ( ! function_exists( 'maca_menulist_get_dashboard_metrics' ) ) {
		require_once MACA_MENULIST_PLUGIN_DIR . 'includes/dashboard-data.php';
	}

	$metrics = maca_menulist_get_dashboard_metrics();
	$license = maca_restu_hub_get_license_status();

	$campaign_title = null;
	if ( ! empty( $metrics['campaign']['title'] ) ) {
		$campaign_title = wp_strip_all_tags( (string) $metrics['campaign']['title'] );
	}

	return array_merge(
		array(
			'installed'        => true,
			'plugin_version'   => defined( 'MACA_MENULIST_VERSION' ) ? MACA_MENULIST_VERSION : '',
			'is_pro'           => ! empty( $license['licensed'] ),
			'updated_at'       => (string) ( $metrics['updated_at'] ?? wp_date( 'Y-m-d H:i:s' ) ),
			'updated_at_label' => (string) ( $metrics['updated_at_label'] ?? wp_date( get_option( 'time_format' ) ) ),
			'dishes_mode'      => ! empty( $metrics['dishes_mode'] ),
			'orders_enabled'   => ! empty( $metrics['orders_enabled'] ),
			'bookings_enabled' => ! empty( $metrics['bookings_enabled'] ),
			'campaign_title'   => $campaign_title,
			'orders'           => isset( $metrics['orders'] ) && is_array( $metrics['orders'] ) ? $metrics['orders'] : null,
			'bookings'         => isset( $metrics['bookings'] ) && is_array( $metrics['bookings'] ) ? $metrics['bookings'] : null,
		),
		maca_restu_hub_get_content_counts(),
		array(
			'actions'    => maca_restu_hub_format_action_items( maca_restu_hub_get_action_items() ),
			'license'    => $license,
			'categories' => maca_restu_hub_list_categories(),
			'menus'      => maca_restu_hub_list_menus(),
			'qr'         => maca_restu_hub_get_qr_settings(),
		)
	);
}

/**
 * @param string $license_key License key.
 * @return array<string, mixed>|WP_Error
 */
function maca_restu_hub_activate_license( $license_key ) {
	if ( ! class_exists( 'Maca_MenuList_License', false ) ) {
		return new WP_Error(
			'restu_license_unavailable',
			__( 'Licenshantering är inte tillgänglig på denna webbplats.', 'maca-restu-pro' ),
			array( 'status' => 501 )
		);
	}

	$result = Maca_MenuList_License::instance()->activate( $license_key );
	if ( is_wp_error( $result ) ) {
		return $result;
	}

	return array(
		'ok'      => true,
		'license' => maca_restu_hub_get_license_status(),
	);
}

/**
 * @return array<string, mixed>|WP_Error
 */
function maca_restu_hub_deactivate_license() {
	if ( ! class_exists( 'Maca_MenuList_License', false ) ) {
		return new WP_Error(
			'restu_license_unavailable',
			__( 'Licenshantering är inte tillgänglig på denna webbplats.', 'maca-restu-pro' ),
			array( 'status' => 501 )
		);
	}

	$result = Maca_MenuList_License::instance()->deactivate();
	if ( is_wp_error( $result ) ) {
		return $result;
	}

	return array(
		'ok'      => true,
		'license' => maca_restu_hub_get_license_status(),
	);
}
