<?php
/**
 * Hub content helpers for maca Restu (categories, menus, QR, preview).
 *
 * @package Maca_Menu_List
 */

defined( 'ABSPATH' ) || exit;

/**
 * @param object $category Category row.
 * @return array<string, mixed>
 */
function maca_restu_hub_format_category( $category ) {
	return array(
		'id'            => (int) $category->id,
		'name'          => (string) $category->name,
		'thumbnail_url' => isset( $category->thumbnail_url ) ? (string) $category->thumbnail_url : '',
		'description'   => isset( $category->description ) ? (string) $category->description : '',
		'sort_order'    => isset( $category->sort_order ) ? (int) $category->sort_order : 0,
	);
}

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

	return array(
		'id'           => (int) $menu->id,
		'category_id'  => (int) $menu->category_id,
		'title'        => (string) $menu->title,
		'file_url'     => (string) $menu->file_url,
		'file_type'    => (string) ( $menu->file_type ?? 'image' ),
		'start_date'   => ! empty( $menu->start_date ) ? (string) $menu->start_date : null,
		'end_date'     => ! empty( $menu->end_date ) ? (string) $menu->end_date : null,
		'time_start'   => ! empty( $menu->time_start ) ? substr( (string) $menu->time_start, 0, 5 ) : null,
		'time_end'     => ! empty( $menu->time_end ) ? substr( (string) $menu->time_end, 0, 5 ) : null,
		'days_of_week' => array_values( array_map( 'intval', $days ) ),
		'is_active'    => ! empty( $menu->is_active ),
		'category_name'=> isset( $menu->category_name ) ? (string) $menu->category_name : '',
	);
}

/**
 * @return array<int, array<string, mixed>>
 */
function maca_restu_hub_list_categories() {
	if ( ! function_exists( 'maca_menulist_db_get_categories' ) ) {
		return array();
	}

	$rows = maca_menulist_db_get_categories( true );
	$output = array();

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

	return $output;
}

/**
 * @param int $category_id Optional category filter.
 * @return array<int, array<string, mixed>>
 */
function maca_restu_hub_list_menus( $category_id = 0 ) {
	if ( ! function_exists( 'maca_menulist_db_get_menus_with_categories' ) ) {
		return array();
	}

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

	foreach ( $rows as $row ) {
		if ( ! $row ) {
			continue;
		}
		if ( $category_id > 0 && (int) $row->category_id !== $category_id ) {
			continue;
		}
		$output[] = maca_restu_hub_format_menu( $row );
	}

	return $output;
}

/**
 * @param array<string, mixed> $params Request params.
 * @return array<string, mixed>|WP_Error
 */
function maca_restu_hub_save_category( array $params ) {
	$name = isset( $params['name'] ) ? sanitize_text_field( (string) $params['name'] ) : '';
	if ( '' === $name ) {
		return new WP_Error( 'restu_category_name_required', __( 'Kategorinamn krävs.', 'maca-restu-pro' ), array( 'status' => 400 ) );
	}

	$category_id = isset( $params['id'] ) ? absint( $params['id'] ) : 0;
	$row         = array(
		'name'          => $name,
		'thumbnail_url' => function_exists( 'maca_menulist_normalize_url' )
			? maca_menulist_normalize_url( esc_url_raw( (string) ( $params['thumbnail_url'] ?? '' ) ) )
			: esc_url_raw( (string) ( $params['thumbnail_url'] ?? '' ) ),
		'description'   => isset( $params['description'] ) ? sanitize_textarea_field( (string) $params['description'] ) : '',
		'sort_order'    => isset( $params['sort_order'] ) ? (int) $params['sort_order'] : 0,
	);

	if ( $category_id > 0 ) {
		$result = maca_menulist_db_update_category( $category_id, $row );
		if ( false === $result ) {
			return new WP_Error( 'restu_category_update_failed', __( 'Kunde inte uppdatera kategorin.', 'maca-restu-pro' ), array( 'status' => 500 ) );
		}
	} else {
		$result = maca_menulist_db_insert_category( $row );
		if ( false === $result ) {
			return new WP_Error( 'restu_category_create_failed', __( 'Kunde inte skapa kategorin.', 'maca-restu-pro' ), array( 'status' => 500 ) );
		}
		global $wpdb;
		$category_id = (int) $wpdb->insert_id;
	}

	$category = maca_menulist_db_get_category( $category_id );
	if ( ! $category ) {
		return new WP_Error( 'restu_category_missing', __( 'Kategorin hittades inte efter sparning.', 'maca-restu-pro' ), array( 'status' => 500 ) );
	}

	return array(
		'ok'       => true,
		'category' => maca_restu_hub_format_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_category( array $params ) {
	$category_id = isset( $params['id'] ) ? absint( $params['id'] ) : 0;
	if ( $category_id <= 0 ) {
		return new WP_Error( 'restu_category_id_required', __( 'Kategori-id krävs.', 'maca-restu-pro' ), array( 'status' => 400 ) );
	}

	maca_menulist_db_delete_category( $category_id );

	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_menu( array $params ) {
	$category_id = isset( $params['category_id'] ) ? absint( $params['category_id'] ) : 0;
	$title       = isset( $params['title'] ) ? sanitize_text_field( (string) $params['title'] ) : '';
	$file_url    = function_exists( 'maca_menulist_normalize_url' )
		? maca_menulist_normalize_url( esc_url_raw( (string) ( $params['file_url'] ?? '' ) ) )
		: esc_url_raw( (string) ( $params['file_url'] ?? '' ) );

	if ( $category_id <= 0 ) {
		return new WP_Error( 'restu_menu_category_required', __( 'Kategori krävs för menyn.', 'maca-restu-pro' ), array( 'status' => 400 ) );
	}
	if ( '' === $title ) {
		return new WP_Error( 'restu_menu_title_required', __( 'Menytitel krävs.', 'maca-restu-pro' ), array( 'status' => 400 ) );
	}
	if ( '' === $file_url ) {
		return new WP_Error( 'restu_menu_file_required', __( 'Fil-URL krävs (PDF eller bild).', 'maca-restu-pro' ), array( 'status' => 400 ) );
	}

	$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 );

	$row = array(
		'category_id'  => $category_id,
		'title'        => $title,
		'file_url'     => $file_url,
		'file_type'    => sanitize_text_field( (string) ( $params['file_type'] ?? 'image' ) ),
		'start_date'   => ! empty( $params['start_date'] ) ? sanitize_text_field( (string) $params['start_date'] ) : null,
		'end_date'     => ! empty( $params['end_date'] ) ? sanitize_text_field( (string) $params['end_date'] ) : 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_of_week' => $days_of_week,
		'is_active'    => ! empty( $params['is_active'] ) ? 1 : 0,
	);

	$menu_id = isset( $params['id'] ) ? absint( $params['id'] ) : 0;
	if ( $menu_id > 0 ) {
		$result = maca_menulist_db_update_menu( $menu_id, $row );
		if ( false === $result ) {
			return new WP_Error( 'restu_menu_update_failed', __( 'Kunde inte uppdatera menyn.', 'maca-restu-pro' ), array( 'status' => 500 ) );
		}
	} else {
		$result = maca_menulist_db_insert_menu( $row );
		if ( false === $result ) {
			return new WP_Error( 'restu_menu_create_failed', __( 'Kunde inte skapa menyn.', 'maca-restu-pro' ), array( 'status' => 500 ) );
		}
		global $wpdb;
		$menu_id = (int) $wpdb->insert_id;
	}

	$menu = maca_menulist_db_get_menu( $menu_id );
	if ( ! $menu ) {
		return new WP_Error( 'restu_menu_missing', __( 'Menyn hittades inte efter sparning.', 'maca-restu-pro' ), array( 'status' => 500 ) );
	}

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

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

/**
 * @param array<string, mixed> $params Request params.
 * @return array<string, mixed>|WP_Error
 */
function maca_restu_hub_delete_menu( array $params ) {
	$menu_id = isset( $params['id'] ) ? absint( $params['id'] ) : 0;
	if ( $menu_id <= 0 ) {
		return new WP_Error( 'restu_menu_id_required', __( 'Meny-id krävs.', 'maca-restu-pro' ), array( 'status' => 400 ) );
	}

	maca_menulist_db_delete_menu( $menu_id );

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

/**
 * @return array<string, mixed>
 */
function maca_restu_hub_get_qr_settings() {
	$category_id = (int) get_option( 'maca_menulist_qr_category', 0 );
	$slug        = function_exists( 'maca_menulist_get_qr_slug' ) ? maca_menulist_get_qr_slug() : 'qrmeny';
	$url         = function_exists( 'maca_menulist_get_qr_url' )
		? maca_menulist_get_qr_url( $category_id > 0 ? $category_id : 0 )
		: home_url( '/' . $slug . '/' );

	return array(
		'slug'        => $slug,
		'url'         => $url,
		'title'       => (string) get_option( 'maca_menulist_qr_title', '' ),
		'subtitle'    => (string) get_option( 'maca_menulist_qr_subtitle', '' ),
		'category_id' => $category_id > 0 ? $category_id : null,
		'logo_url'    => (string) get_option( 'maca_menulist_qr_logo', '' ),
	);
}

/**
 * @param array<string, mixed> $params Request params.
 * @return array<string, mixed>|WP_Error
 */
function maca_restu_hub_update_qr_settings( array $params ) {
	$slug = isset( $params['slug'] ) ? sanitize_title( (string) $params['slug'] ) : '';
	if ( '' === $slug ) {
		$slug = 'qrmeny';
	}

	$old_slug = get_option( 'maca_menulist_qr_slug', 'qrmeny' );
	update_option( 'maca_menulist_qr_slug', $slug );
	if ( $old_slug !== $slug && function_exists( 'maca_menulist_flush_rewrite_rules' ) ) {
		maca_menulist_flush_rewrite_rules();
	}

	if ( array_key_exists( 'title', $params ) ) {
		update_option( 'maca_menulist_qr_title', sanitize_text_field( (string) $params['title'] ) );
	}
	if ( array_key_exists( 'subtitle', $params ) ) {
		update_option( 'maca_menulist_qr_subtitle', sanitize_text_field( (string) $params['subtitle'] ) );
	}
	if ( array_key_exists( 'category_id', $params ) ) {
		$category_id = absint( $params['category_id'] );
		update_option( 'maca_menulist_qr_category', $category_id > 0 ? $category_id : '' );
	}

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

/**
 * @param string $datetime Local datetime string (Y-m-d H:i or Y-m-dTH:i).
 * @return array<string, mixed>|WP_Error
 */
function maca_restu_hub_get_preview( $datetime = '' ) {
	if ( ! function_exists( 'maca_menulist_build_schedule_preview' ) ) {
		require_once MACA_MENULIST_PLUGIN_DIR . 'includes/schedule-preview.php';
	}

	$datetime = trim( (string) $datetime );
	if ( '' === $datetime ) {
		$timestamp = current_time( 'timestamp' );
	} else {
		$datetime = str_replace( 'T', ' ', $datetime );
		$timestamp = strtotime( $datetime );
		if ( false === $timestamp ) {
			return new WP_Error( 'restu_preview_invalid_datetime', __( 'Ogiltigt datum/tid för förhandsgranskning.', 'maca-restu-pro' ), array( 'status' => 400 ) );
		}
	}

	$preview = maca_menulist_build_schedule_preview( $timestamp );
	$categories = isset( $preview['diagnostics']['categories'] ) && is_array( $preview['diagnostics']['categories'] )
		? $preview['diagnostics']['categories']
		: array();

	return array(
		'label'          => (string) ( $preview['label'] ?? '' ),
		'datetime_local' => (string) ( $preview['datetime_local'] ?? '' ),
		'categories'     => array_values( $categories ),
	);
}

/**
 * QR print/view payload for maca Hub.
 *
 * @return array<string, mixed>
 */
function maca_restu_hub_get_qr_print_info() {
	$qr = maca_restu_hub_get_qr_settings();

	return array(
		'menu_url'   => (string) ( $qr['url'] ?? '' ),
		'title'      => (string) ( $qr['title'] ?? '' ),
		'subtitle'   => (string) ( $qr['subtitle'] ?? '' ),
		'logo_url'   => (string) ( $qr['logo_url'] ?? '' ),
		'paper_size' => (string) get_option( 'maca_menulist_qr_paper_size', 'a4' ),
		'slug'       => (string) ( $qr['slug'] ?? 'qrmeny' ),
	);
}

/**
 * Upload a menu file (PDF or image) from base64 payload.
 *
 * @param array<string, mixed> $params Request body.
 * @return array<string, mixed>|WP_Error
 */
function maca_restu_hub_upload_menu_file_from_base64( array $params ) {
	$file_base64 = (string) ( $params['file_base64'] ?? $params['image_base64'] ?? '' );
	if ( '' === $file_base64 ) {
		return new WP_Error(
			'restu_file_required',
			__( 'Ingen fil angiven.', 'maca-restu-pro' ),
			array( 'status' => 400 )
		);
	}

	$decoded = base64_decode( $file_base64, true );
	if ( false === $decoded ) {
		return new WP_Error(
			'restu_invalid_base64',
			__( 'Filen kunde inte läsas.', 'maca-restu-pro' ),
			array( 'status' => 400 )
		);
	}

	$mime = sanitize_text_field( (string) ( $params['mime_type'] ?? 'image/jpeg' ) );
	$allowed = array(
		'image/jpeg',
		'image/png',
		'image/gif',
		'application/pdf',
	);

	if ( ! in_array( $mime, $allowed, true ) ) {
		return new WP_Error(
			'restu_invalid_mime',
			__( 'Ogiltig filtyp. Tillåtna format: JPG, PNG, GIF, PDF.', 'maca-restu-pro' ),
			array( 'status' => 400 )
		);
	}

	$filename = sanitize_file_name( (string) ( $params['filename'] ?? 'restu-menu.jpg' ) );
	if ( '' === $filename ) {
		$filename = 'application/pdf' === $mime ? 'restu-menu.pdf' : 'restu-menu.jpg';
	}

	$upload_dir = wp_upload_dir();
	if ( ! empty( $upload_dir['error'] ) ) {
		return new WP_Error(
			'restu_upload_failed',
			(string) $upload_dir['error'],
			array( 'status' => 500 )
		);
	}

	$tmp_file = wp_tempnam( $filename );
	if ( ! $tmp_file ) {
		return new WP_Error(
			'restu_upload_failed',
			__( 'Kunde inte skapa temporär fil.', 'maca-restu-pro' ),
			array( 'status' => 500 )
		);
	}

	// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
	if ( false === file_put_contents( $tmp_file, $decoded ) ) {
		wp_delete_file( $tmp_file );
		return new WP_Error(
			'restu_upload_failed',
			__( 'Kunde inte skriva temporär fil.', 'maca-restu-pro' ),
			array( 'status' => 500 )
		);
	}

	$file_array = array(
		'name'     => $filename,
		'tmp_name' => $tmp_file,
	);

	require_once ABSPATH . 'wp-admin/includes/file.php';

	$upload = wp_handle_sideload(
		$file_array,
		array(
			'test_form' => false,
			'mimes'     => array(
				'jpg|jpeg|jpe' => 'image/jpeg',
				'png'          => 'image/png',
				'gif'          => 'image/gif',
				'pdf'          => 'application/pdf',
			),
		)
	);

	if ( ! empty( $upload['error'] ) ) {
		return new WP_Error(
			'restu_upload_failed',
			(string) $upload['error'],
			array( 'status' => 500 )
		);
	}

	$file_url = (string) ( $upload['url'] ?? '' );
	if ( '' === $file_url ) {
		return new WP_Error(
			'restu_upload_failed',
			__( 'Kunde inte hämta fil-URL.', 'maca-restu-pro' ),
			array( 'status' => 500 )
		);
	}

	$file_type = 'application/pdf' === $mime ? 'pdf' : 'image';

	return array(
		'ok'        => true,
		'url'       => $file_url,
		'file_type' => $file_type,
	);
}
