<?php
/**
 * Food type data access.
 *
 * @package RestaurantCosting
 */

declare(strict_types=1);

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

final class RC_Food_Type_Repository {

	public static function get_all(): array {
		global $wpdb;
		$table = RC_Database::table( 'food_types' );
		return $wpdb->get_results( "SELECT id, name FROM {$table} ORDER BY sort_order ASC, name ASC" ) ?: array();
	}

	public static function find_or_create( string $name ): int {
		global $wpdb;
		$table = RC_Database::table( 'food_types' );
		$name  = trim( $name );
		if ( '' === $name ) {
			$name = 'Other';
		}

		$id = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$table} WHERE name = %s", $name ) );
		if ( $id ) {
			return (int) $id;
		}

		$max = (int) $wpdb->get_var( "SELECT COALESCE(MAX(sort_order), 0) FROM {$table}" );
		$wpdb->insert( $table, array(
			'name'       => $name,
			'sort_order' => $max + 1,
		), array( '%s', '%d' ) );
		RC_Exception::throw_on_db_error( 'insert', $table );

		return (int) $wpdb->insert_id;
	}

	public static function get_name( int $id ): string {
		global $wpdb;
		$table = RC_Database::table( 'food_types' );
		$name  = $wpdb->get_var( $wpdb->prepare( "SELECT name FROM {$table} WHERE id = %d", $id ) );
		return $name ?: '';
	}
}
