<?php

declare(strict_types=1);

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

final class RC_Restaurant_Repository {

	public static function get(): ?object {
		global $wpdb;
		$table = RC_Database::table( 'restaurant_info' );
		return $wpdb->get_row( "SELECT * FROM {$table} LIMIT 1" ) ?: null;
	}

	public static function save( array $data ): bool {
		global $wpdb;
		$table = RC_Database::table( 'restaurant_info' );

		$row = self::get();
		$record = array(
			'restaurant_name' => $data['restaurant_name'] ?? '',
			'address'         => $data['address'] ?? '',
			'phone'           => $data['phone'] ?? '',
			'logo_url'        => $data['logo_url'] ?? '',
			'sender_name'     => $data['sender_name'] ?? '',
			'sender_email'    => $data['sender_email'] ?? '',
		);

		if ( $row ) {
			$result = $wpdb->update( $table, $record, array( 'id' => $row->id ) );
			RC_Exception::throw_on_db_error( 'update', $table );
			return false !== $result;
		}

		$result = $wpdb->insert( $table, $record );
		RC_Exception::throw_on_db_error( 'insert', $table );
		return false !== $result;
	}
}
