<?php
/**
 * Hub dish helpers for maca Restu Pro (online menu).
 *
 * @package Maca_Menu_List
 */

defined( 'ABSPATH' ) || exit;

/**
 * @return bool
 */
function maca_restu_hub_dishes_available() {
	return function_exists( 'maca_menulist_is_dishes_mode' )
		&& maca_menulist_is_dishes_mode()
		&& function_exists( 'maca_menulist_db_get_dish_categories' );
}

/**
 * @return WP_Error|null
 */
function maca_restu_hub_require_dishes_mode() {
	if ( ! maca_restu_hub_dishes_available() ) {
		return new WP_Error(
			'restu_dishes_unavailable',
			__( 'Onlinemeny (rätter) är inte aktivt på webbplatsen.', 'maca-restu-pro' ),
			array( 'status' => 403 )
		);
	}

	return null;
}

/**
 * @param array<string, mixed> $params Request params.
 * @return array<string, string|null>
 */
function maca_restu_hub_parse_schedule_params( array $params ) {
	$start_raw = ! empty( $params['start_date'] ) ? sanitize_text_field( (string) $params['start_date'] ) : '';
	$end_raw   = ! empty( $params['end_date'] ) ? sanitize_text_field( (string) $params['end_date'] ) : '';
	$start_date = $start_raw !== '' && function_exists( 'maca_menulist_datetime_local_to_mysql' )
		? maca_menulist_datetime_local_to_mysql( $start_raw )
		: ( $start_raw !== '' ? $start_raw : null );
	$end_date = $end_raw !== '' && function_exists( 'maca_menulist_datetime_local_to_mysql' )
		? maca_menulist_datetime_local_to_mysql( $end_raw )
		: ( $end_raw !== '' ? $end_raw : null );
	$time_start = function_exists( 'maca_menulist_normalize_time' )
		? maca_menulist_normalize_time( isset( $params['time_start'] ) ? sanitize_text_field( (string) $params['time_start'] ) : '' )
		: null;
	$time_end = function_exists( 'maca_menulist_normalize_time' )
		? maca_menulist_normalize_time( isset( $params['time_end'] ) ? sanitize_text_field( (string) $params['time_end'] ) : '' )
		: null;
	$days_raw = isset( $params['days_of_week'] ) && is_array( $params['days_of_week'] )
		? array_map( 'sanitize_text_field', $params['days_of_week'] )
		: array();
	$days_of_week = function_exists( 'maca_menulist_format_days_of_week' )
		? maca_menulist_format_days_of_week( $days_raw )
		: implode( ',', $days_raw );

	return array(
		'start_date'   => $start_date,
		'end_date'     => $end_date,
		'time_start'   => $time_start,
		'time_end'     => $time_end,
		'days_of_week' => $days_of_week,
	);
}

/**
 * @param object $category Dish category row.
 * @return array<string, mixed>
 */
function maca_restu_hub_format_dish_category( $category ) {
	$days = function_exists( 'maca_menulist_parse_days_of_week' )
		? maca_menulist_parse_days_of_week( isset( $category->days_of_week ) ? (string) $category->days_of_week : '' )
		: array();

	return array(
		'id'           => (int) $category->id,
		'name'         => (string) $category->name,
		'name_en'      => isset( $category->name_en ) ? (string) $category->name_en : '',
		'sort_order'   => isset( $category->sort_order ) ? (int) $category->sort_order : 0,
		'is_active'    => ! empty( $category->is_active ),
		'start_date'   => ! empty( $category->start_date ) ? (string) $category->start_date : null,
		'end_date'     => ! empty( $category->end_date ) ? (string) $category->end_date : null,
		'time_start'   => ! empty( $category->time_start ) ? substr( (string) $category->time_start, 0, 5 ) : null,
		'time_end'     => ! empty( $category->time_end ) ? substr( (string) $category->time_end, 0, 5 ) : null,
		'days_of_week' => array_values( array_map( 'intval', $days ) ),
	);
}

/**
 * @param object $dish Dish row.
 * @return array<string, mixed>
 */
function maca_restu_hub_format_dish( $dish ) {
	$allergen_ids = function_exists( 'maca_menulist_db_get_dish_allergen_ids' )
		? array_map( 'intval', maca_menulist_db_get_dish_allergen_ids( (int) $dish->id ) )
		: array();

	return array(
		'id'              => (int) $dish->id,
		'category_id'     => (int) $dish->category_id,
		'title'           => (string) $dish->title,
		'title_en'        => isset( $dish->title_en ) ? (string) $dish->title_en : '',
		'description'     => isset( $dish->description ) ? (string) $dish->description : '',
		'description_en'  => isset( $dish->description_en ) ? (string) $dish->description_en : '',
		'price'           => isset( $dish->price ) && $dish->price !== null && $dish->price !== '' ? (float) $dish->price : null,
		'price_takeaway'  => isset( $dish->price_takeaway ) && $dish->price_takeaway !== null && $dish->price_takeaway !== '' ? (float) $dish->price_takeaway : null,
		'takeaway_active' => ! empty( $dish->takeaway_active ),
		'vat_code'        => isset( $dish->vat_code ) ? (string) $dish->vat_code : 'food',
		'image_url'       => isset( $dish->image_url ) ? (string) $dish->image_url : '',
		'sort_order'      => isset( $dish->sort_order ) ? (int) $dish->sort_order : 0,
		'is_active'       => ! empty( $dish->is_active ),
		'category_name'   => isset( $dish->category_name ) ? (string) $dish->category_name : '',
		'allergen_ids'    => $allergen_ids,
	);
}

/**
 * @param object $allergen Allergen row.
 * @return array<string, mixed>
 */
function maca_restu_hub_format_allergen( $allergen ) {
	return array(
		'id'         => (int) $allergen->id,
		'name'       => (string) $allergen->name,
		'name_en'    => isset( $allergen->name_en ) ? (string) $allergen->name_en : '',
		'sort_order' => isset( $allergen->sort_order ) ? (int) $allergen->sort_order : 0,
	);
}

/**
 * @return array<int, array<string, mixed>>
 */
function maca_restu_hub_list_dish_categories() {
	$denied = maca_restu_hub_require_dishes_mode();
	if ( is_wp_error( $denied ) ) {
		return array();
	}

	$rows   = maca_menulist_db_get_dish_categories( false );
	$output = array();

	foreach ( $rows as $row ) {
		if ( ! $row ) {
			continue;
		}
		$output[] = maca_restu_hub_format_dish_category( $row );
	}

	return $output;
}

/**
 * @param int $category_id Optional category filter.
 * @return array<int, array<string, mixed>>
 */
function maca_restu_hub_list_dishes( $category_id = 0 ) {
	$denied = maca_restu_hub_require_dishes_mode();
	if ( is_wp_error( $denied ) ) {
		return array();
	}

	if ( $category_id > 0 ) {
		$rows = maca_menulist_db_get_dishes_by_category( $category_id, false );
	} else {
		$rows = maca_menulist_db_get_dishes( false );
	}

	$output = array();
	foreach ( $rows as $row ) {
		if ( ! $row ) {
			continue;
		}
		$output[] = maca_restu_hub_format_dish( $row );
	}

	return $output;
}

/**
 * @return array<int, array<string, mixed>>
 */
function maca_restu_hub_list_allergens() {
	$denied = maca_restu_hub_require_dishes_mode();
	if ( is_wp_error( $denied ) ) {
		return array();
	}

	if ( ! function_exists( 'maca_menulist_db_get_allergens' ) ) {
		return array();
	}

	$rows   = maca_menulist_db_get_allergens();
	$output = array();

	foreach ( $rows as $row ) {
		if ( ! $row ) {
			continue;
		}
		$output[] = maca_restu_hub_format_allergen( $row );
	}

	return $output;
}

/**
 * @param array<string, mixed> $params Request params.
 * @return array<string, mixed>|WP_Error
 */
function maca_restu_hub_save_dish_category( array $params ) {
	$denied = maca_restu_hub_require_dishes_mode();
	if ( is_wp_error( $denied ) ) {
		return $denied;
	}

	$name        = isset( $params['name'] ) ? sanitize_text_field( (string) $params['name'] ) : '';
	$name_en     = isset( $params['name_en'] ) ? sanitize_text_field( (string) $params['name_en'] ) : '';
	$sort_order  = isset( $params['sort_order'] ) ? absint( $params['sort_order'] ) : 0;
	$is_active   = ! empty( $params['is_active'] ) ? 1 : 0;
	$category_id = isset( $params['id'] ) ? absint( $params['id'] ) : 0;

	if ( '' === $name && '' === $name_en ) {
		return new WP_Error(
			'restu_dish_category_name_required',
			__( 'Kategorinamn krävs.', 'maca-restu-pro' ),
			array( 'status' => 400 )
		);
	}

	$schedule = maca_restu_hub_parse_schedule_params( $params );
	$row      = array(
		'name'         => $name,
		'name_en'      => $name_en,
		'sort_order'   => $sort_order,
		'is_active'    => $is_active,
		'start_date'   => $schedule['start_date'],
		'end_date'     => $schedule['end_date'],
		'time_start'   => $schedule['time_start'],
		'time_end'     => $schedule['time_end'],
		'days_of_week' => $schedule['days_of_week'],
	);

	if ( $category_id > 0 ) {
		$result = maca_menulist_db_update_dish_category( $category_id, $row );
	} else {
		$result      = maca_menulist_db_insert_dish_category( $row );
		global $wpdb;
		$category_id = (int) $wpdb->insert_id;
	}

	if ( false === $result ) {
		return new WP_Error(
			'restu_dish_category_save_failed',
			__( 'Kunde inte spara rättkategorin.', 'maca-restu-pro' ),
			array( 'status' => 500 )
		);
	}

	$category = maca_menulist_db_get_dish_category( $category_id );
	if ( ! $category ) {
		return new WP_Error(
			'restu_dish_category_missing',
			__( 'Rättkategorin hittades inte efter sparning.', 'maca-restu-pro' ),
			array( 'status' => 500 )
		);
	}

	do_action( 'maca_menulist_site_chat_content_changed' );

	return array(
		'ok'       => true,
		'category' => maca_restu_hub_format_dish_category( $category ),
		'status'   => maca_restu_hub_get_status(),
	);
}

/**
 * @param array<string, mixed> $params Request params.
 * @return array<string, mixed>|WP_Error
 */
function maca_restu_hub_delete_dish_category( array $params ) {
	$denied = maca_restu_hub_require_dishes_mode();
	if ( is_wp_error( $denied ) ) {
		return $denied;
	}

	$category_id = isset( $params['id'] ) ? absint( $params['id'] ) : 0;
	if ( $category_id <= 0 ) {
		return new WP_Error(
			'restu_dish_category_id_required',
			__( 'Rättkategori-id krävs.', 'maca-restu-pro' ),
			array( 'status' => 400 )
		);
	}

	maca_menulist_db_delete_dish_category( $category_id );
	do_action( 'maca_menulist_site_chat_content_changed' );

	return array(
		'ok'     => true,
		'status' => maca_restu_hub_get_status(),
	);
}

/**
 * @param array<string, mixed> $params Request params.
 * @return array<string, mixed>|WP_Error
 */
function maca_restu_hub_save_dish( array $params ) {
	$denied = maca_restu_hub_require_dishes_mode();
	if ( is_wp_error( $denied ) ) {
		return $denied;
	}

	$title           = isset( $params['title'] ) ? sanitize_text_field( (string) $params['title'] ) : '';
	$title_en        = isset( $params['title_en'] ) ? sanitize_text_field( (string) $params['title_en'] ) : '';
	$description     = isset( $params['description'] ) ? sanitize_textarea_field( (string) $params['description'] ) : '';
	$description_en  = isset( $params['description_en'] ) ? sanitize_textarea_field( (string) $params['description_en'] ) : '';
	$category_id     = isset( $params['category_id'] ) ? absint( $params['category_id'] ) : 0;
	$price_raw       = isset( $params['price'] ) ? str_replace( ',', '.', trim( (string) $params['price'] ) ) : '';
	$price           = $price_raw !== '' ? floatval( $price_raw ) : null;
	$takeaway_raw    = isset( $params['price_takeaway'] ) ? str_replace( ',', '.', trim( (string) $params['price_takeaway'] ) ) : '';
	$price_takeaway  = $takeaway_raw !== '' ? floatval( $takeaway_raw ) : null;
	$takeaway_active = ! empty( $params['takeaway_active'] ) ? 1 : 0;
	$image_url       = function_exists( 'maca_menulist_normalize_url' )
		? maca_menulist_normalize_url( esc_url_raw( (string) ( $params['image_url'] ?? '' ) ) )
		: esc_url_raw( (string) ( $params['image_url'] ?? '' ) );
	$is_active       = ! empty( $params['is_active'] ) ? 1 : 0;
	$dish_id         = isset( $params['id'] ) ? absint( $params['id'] ) : 0;
	$allergen_ids    = isset( $params['allergen_ids'] ) && is_array( $params['allergen_ids'] )
		? array_map( 'absint', $params['allergen_ids'] )
		: array();
	$campaign_ids    = isset( $params['campaign_ids'] ) && is_array( $params['campaign_ids'] )
		? array_map( 'absint', $params['campaign_ids'] )
		: array();
	$vat_code        = isset( $params['vat_code'] ) && function_exists( 'maca_menulist_sanitize_dish_vat_code' )
		? maca_menulist_sanitize_dish_vat_code( (string) $params['vat_code'] )
		: 'food';

	if ( '' === $title && '' === $title_en ) {
		return new WP_Error(
			'restu_dish_title_required',
			__( 'Rättens titel krävs.', 'maca-restu-pro' ),
			array( 'status' => 400 )
		);
	}

	if ( $category_id <= 0 ) {
		return new WP_Error(
			'restu_dish_category_required',
			__( 'Rättkategori krävs.', 'maca-restu-pro' ),
			array( 'status' => 400 )
		);
	}

	if ( $dish_id > 0 ) {
		$existing   = maca_menulist_db_get_dish( $dish_id );
		$sort_order = $existing ? (int) $existing->sort_order : 0;
	} else {
		global $wpdb;
		$dishes_table = maca_menulist_db_dishes_table();
		$max_sort     = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT MAX(sort_order) FROM $dishes_table WHERE category_id = %d",
				$category_id
			)
		);
		$sort_order = ( $max_sort !== null && $max_sort !== '' ) ? ( (int) $max_sort + 1 ) : 0;
	}

	$row = array(
		'category_id'     => $category_id,
		'title'           => $title,
		'title_en'        => $title_en,
		'description'     => $description,
		'description_en'  => $description_en,
		'price'           => $price,
		'price_takeaway'  => $price_takeaway,
		'takeaway_active' => $takeaway_active,
		'vat_code'        => $vat_code,
		'image_url'       => $image_url !== '' ? $image_url : null,
		'sort_order'      => $sort_order,
		'is_active'       => $is_active,
	);

	if ( $dish_id > 0 ) {
		$result        = maca_menulist_db_update_dish( $dish_id, $row );
		$saved_dish_id = $dish_id;
	} else {
		$result = maca_menulist_db_insert_dish( $row );
		global $wpdb;
		$saved_dish_id = (int) $wpdb->insert_id;
	}

	if ( false === $result ) {
		return new WP_Error(
			'restu_dish_save_failed',
			__( 'Kunde inte spara rätten.', 'maca-restu-pro' ),
			array( 'status' => 500 )
		);
	}

	if ( $saved_dish_id > 0 ) {
		maca_menulist_db_set_dish_allergens( $saved_dish_id, $allergen_ids );
		if ( function_exists( 'maca_menulist_db_set_dish_campaigns' ) ) {
			maca_menulist_db_set_dish_campaigns( $saved_dish_id, $campaign_ids );
		}
	}

	$dish = maca_menulist_db_get_dish( $saved_dish_id );
	if ( ! $dish ) {
		return new WP_Error(
			'restu_dish_missing',
			__( 'Rätten hittades inte efter sparning.', 'maca-restu-pro' ),
			array( 'status' => 500 )
		);
	}

	$category = maca_menulist_db_get_dish_category( (int) $dish->category_id );
	if ( $category ) {
		$dish->category_name = (string) $category->name;
	}

	do_action( 'maca_menulist_site_chat_content_changed' );

	return array(
		'ok'     => true,
		'dish'   => maca_restu_hub_format_dish( $dish ),
		'status' => maca_restu_hub_get_status(),
	);
}

/**
 * @param array<string, mixed> $params Request params.
 * @return array<string, mixed>|WP_Error
 */
function maca_restu_hub_delete_dish( array $params ) {
	$denied = maca_restu_hub_require_dishes_mode();
	if ( is_wp_error( $denied ) ) {
		return $denied;
	}

	$dish_id = isset( $params['id'] ) ? absint( $params['id'] ) : 0;
	if ( $dish_id <= 0 ) {
		return new WP_Error(
			'restu_dish_id_required',
			__( 'Rätt-id krävs.', 'maca-restu-pro' ),
			array( 'status' => 400 )
		);
	}

	maca_menulist_db_delete_dish( $dish_id );
	do_action( 'maca_menulist_site_chat_content_changed' );

	return array(
		'ok'     => true,
		'status' => maca_restu_hub_get_status(),
	);
}
