<?php
/**
 * Database layer for maca Restu custom tables.
 *
 * @package Maca_Menu_List
 */

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

/**
 * Categories table name.
 *
 * @return string
 */
function maca_menulist_db_categories_table() {
    global $wpdb;

    return $wpdb->prefix . 'maca_menu_categories';
}

/**
 * Menus table name.
 *
 * @return string
 */
function maca_menulist_db_menus_table() {
    global $wpdb;

    return $wpdb->prefix . 'maca_menus';
}

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.SchemaChange

/**
 * Create or update plugin database tables.
 */
function maca_menulist_db_create_tables() {
    global $wpdb;

    if (!isset($wpdb) || empty($wpdb)) {
        return;
    }

    $charset_collate = $wpdb->get_charset_collate();
    $categories_table = maca_menulist_db_categories_table();
    $menus_table = maca_menulist_db_menus_table();

    $sql_categories = "CREATE TABLE $categories_table (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        name varchar(255) NOT NULL,
        thumbnail_url varchar(500) DEFAULT NULL,
        description text DEFAULT NULL,
        sort_order int(11) DEFAULT 0,
        created_at datetime DEFAULT CURRENT_TIMESTAMP,
        updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY  (id)
    ) $charset_collate;";

    $sql_menus = "CREATE TABLE $menus_table (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        category_id mediumint(9) NOT NULL,
        title varchar(255) NOT NULL,
        file_url varchar(500) NOT NULL,
        file_type varchar(50) DEFAULT 'image',
        start_date datetime DEFAULT NULL,
        end_date datetime DEFAULT NULL,
        time_start time DEFAULT NULL,
        time_end time DEFAULT NULL,
        days_of_week varchar(32) DEFAULT NULL,
        is_active tinyint(1) DEFAULT 1,
        created_at datetime DEFAULT CURRENT_TIMESTAMP,
        updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY  (id),
        KEY category_id (category_id)
    ) $charset_collate;";

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta($sql_categories);
    dbDelta($sql_menus);

    require_once dirname(__FILE__) . '/db-dishes.php';
    maca_menulist_db_create_dish_tables();

    require_once dirname(__FILE__) . '/db-campaigns.php';
    maca_menulist_db_create_campaign_tables();

    require_once dirname(__FILE__) . '/db-dish-stats.php';
    maca_menulist_db_create_dish_views_table();

    require_once dirname(__FILE__) . '/db-table-orders.php';
    maca_menulist_db_create_table_order_tables();

    require_once dirname(__FILE__) . '/db-table-bookings.php';
    maca_menulist_db_create_table_booking_tables();

    require_once dirname(__FILE__) . '/db-waiters.php';
    maca_menulist_db_create_waiter_tables();

    require_once dirname(__FILE__) . '/attendance-log.php';
    require_once dirname(__FILE__) . '/db-attendance.php';
    maca_menulist_db_create_attendance_tables();

    require_once dirname(__FILE__) . '/db-info-hub.php';
    maca_menulist_db_create_info_hub_tables();

    require_once dirname(__FILE__) . '/db-info-hub-social.php';
    maca_menulist_db_create_info_social_log_table();

    require_once dirname(__FILE__) . '/db-site-chat.php';
    maca_menulist_db_create_site_chat_tables();
}

/**
 * Ordered schema migration steps (all run in one request after plugin update).
 *
 * @return array<string, callable>
 */
function maca_menulist_db_get_migrate_steps() {
    return array(
        'dish_category_columns' => static function () {
            require_once dirname(__FILE__) . '/db-dishes.php';
            maca_menulist_db_ensure_dish_category_columns();
        },
        'bootstrap_tables' => static function () {
            global $wpdb;

            $categories_table = maca_menulist_db_categories_table();
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            if ($wpdb->get_var("SHOW TABLES LIKE '$categories_table'") === $categories_table) {
                return;
            }

            maca_menulist_db_create_tables();
            maca_menulist_db_migrate_schema_mark_all_steps_completed();
        },
        'menu_category_sort' => static function () {
            global $wpdb;

            $categories_table = maca_menulist_db_categories_table();
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            if ($wpdb->get_var("SHOW TABLES LIKE '$categories_table'") !== $categories_table) {
                return;
            }

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            if (!$wpdb->get_var("SHOW COLUMNS FROM $categories_table LIKE 'sort_order'")) {
                $wpdb->query("ALTER TABLE $categories_table ADD COLUMN sort_order int(11) DEFAULT 0 AFTER description");
            }
        },
        'menu_schedule' => static function () {
            global $wpdb;

            $menus_table = maca_menulist_db_menus_table();
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            if ($wpdb->get_var("SHOW TABLES LIKE '$menus_table'") !== $menus_table) {
                return;
            }

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            if (!$wpdb->get_var("SHOW COLUMNS FROM $menus_table LIKE 'time_start'")) {
                $wpdb->query("ALTER TABLE $menus_table ADD COLUMN time_start time DEFAULT NULL AFTER end_date");
            }
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            if (!$wpdb->get_var("SHOW COLUMNS FROM $menus_table LIKE 'time_end'")) {
                $wpdb->query("ALTER TABLE $menus_table ADD COLUMN time_end time DEFAULT NULL AFTER time_start");
            }
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            if (!$wpdb->get_var("SHOW COLUMNS FROM $menus_table LIKE 'days_of_week'")) {
                $wpdb->query("ALTER TABLE $menus_table ADD COLUMN days_of_week varchar(32) DEFAULT NULL AFTER time_end");
            }
        },
        'dish_tables' => static function () {
            require_once dirname(__FILE__) . '/db-dishes.php';
            maca_menulist_db_create_dish_tables();
        },
        'campaign_tables' => static function () {
            require_once dirname(__FILE__) . '/db-campaigns.php';
            maca_menulist_db_create_campaign_tables();
        },
        'dish_ratings' => static function () {
            require_once dirname(__FILE__) . '/db-dishes.php';
            maca_menulist_db_ensure_dish_ratings_table();
        },
        'allergen_columns' => static function () {
            require_once dirname(__FILE__) . '/db-dishes.php';
            maca_menulist_db_ensure_allergen_columns();
        },
        'allergen_seed' => static function () {
            require_once dirname(__FILE__) . '/db-dishes.php';
            maca_menulist_db_seed_default_allergens();
        },
        'dish_schedule' => static function () {
            require_once dirname(__FILE__) . '/db-dishes.php';
            maca_menulist_db_ensure_dish_schedule_columns();
        },
        'dish_category_schedule' => static function () {
            require_once dirname(__FILE__) . '/db-dishes.php';
            maca_menulist_db_ensure_dish_category_schedule_columns();
            maca_menulist_db_migrate_dish_schedule_to_categories();
        },
        'schedule_datetime_format' => static function () {
            require_once dirname(__FILE__) . '/schedule.php';
            maca_menulist_db_migrate_schedule_datetime_format();
        },
        'schedule_datetime_format_v2' => static function () {
            require_once dirname(__FILE__) . '/schedule.php';
            maca_menulist_db_migrate_schedule_datetime_format_v2();
        },
        'dish_vat' => static function () {
            require_once dirname(__FILE__) . '/db-dishes.php';
            maca_menulist_db_ensure_dish_vat_code_column();
        },
        'dish_takeaway' => static function () {
            require_once dirname(__FILE__) . '/db-dishes.php';
            maca_menulist_db_ensure_dish_takeaway_columns();
        },
        'dish_views' => static function () {
            require_once dirname(__FILE__) . '/db-dish-stats.php';
            maca_menulist_db_ensure_dish_views_table();
        },
        'table_orders' => static function () {
            require_once dirname(__FILE__) . '/db-table-orders.php';
            maca_menulist_db_create_table_order_tables();
            maca_menulist_db_ensure_table_order_tables();
        },
        'table_bookings' => static function () {
            require_once dirname(__FILE__) . '/db-table-bookings.php';
            maca_menulist_db_create_table_booking_tables();
            maca_menulist_db_ensure_table_booking_tables();
        },
        'booking_day_split' => static function () {
            require_once dirname(__FILE__) . '/table-booking-day-splits.php';
            maca_menulist_db_ensure_booking_day_split_schema();
        },
        'bilingual_columns' => static function () {
            if (!function_exists('maca_menulist_db_ensure_bilingual_columns')) {
                require_once dirname(__FILE__) . '/i18n.php';
            }
            maca_menulist_db_ensure_bilingual_columns();
        },
        'attendance_tables' => static function () {
            require_once dirname(__FILE__) . '/attendance-log.php';
            require_once dirname(__FILE__) . '/db-attendance.php';
            maca_menulist_db_ensure_attendance_tables();
        },
        'info_hub_tables' => static function () {
            require_once dirname(__FILE__) . '/db-info-hub.php';
            maca_menulist_db_ensure_info_hub_tables();
        },
        'info_hub_social_log' => static function () {
            require_once dirname(__FILE__) . '/db-info-hub-social.php';
            maca_menulist_db_ensure_info_social_log_table();
        },
        'site_chat_tables' => static function () {
            require_once dirname(__FILE__) . '/db-site-chat.php';
            maca_menulist_db_ensure_site_chat_tables();
        },
    );
}

/**
 * @return array<string, int>
 */
function maca_menulist_db_migrate_schema_get_completed() {
    $completed = get_option('maca_menulist_db_migrate_completed', array());

    return is_array($completed) ? $completed : array();
}

/**
 * @return void
 */
function maca_menulist_db_migrate_schema_mark_all_steps_completed() {
    $completed = array();

    foreach (array_keys(maca_menulist_db_get_migrate_steps()) as $step_id) {
        $completed[$step_id] = 1;
    }

    update_option('maca_menulist_db_migrate_completed', $completed, false);
}

/**
 * Reset step tracking when plugin DB version changes.
 *
 * @param string $target_version Target plugin version.
 * @return void
 */
function maca_menulist_db_migrate_schema_prepare_for_version($target_version) {
    if (get_option('maca_menulist_db_migrate_target') !== $target_version) {
        delete_option('maca_menulist_db_migrate_completed');
        update_option('maca_menulist_db_migrate_target', $target_version, false);
    }
}

/**
 * @return bool
 */
function maca_menulist_db_migrate_schema_is_complete() {
    $completed = maca_menulist_db_migrate_schema_get_completed();

    foreach (array_keys(maca_menulist_db_get_migrate_steps()) as $step_id) {
        if (empty($completed[$step_id])) {
            return false;
        }
    }

    return true;
}

/**
 * Count remaining migration steps.
 *
 * @return int
 */
function maca_menulist_db_migrate_schema_remaining_count() {
    $completed = maca_menulist_db_migrate_schema_get_completed();
    $remaining = 0;

    foreach (array_keys(maca_menulist_db_get_migrate_steps()) as $step_id) {
        if (empty($completed[$step_id])) {
            ++$remaining;
        }
    }

    return $remaining;
}

/**
 * Run the next pending migration step.
 *
 * @return string|null Step ID that ran, or null if already complete.
 */
function maca_menulist_db_migrate_schema_run_next_step() {
    $steps = maca_menulist_db_get_migrate_steps();
    $completed = maca_menulist_db_migrate_schema_get_completed();

    foreach ($steps as $step_id => $callback) {
        if (!empty($completed[$step_id])) {
            continue;
        }

        call_user_func($callback);
        $completed[$step_id] = 1;
        update_option('maca_menulist_db_migrate_completed', $completed, false);

        return $step_id;
    }

    return null;
}

/**
 * Run all idempotent schema upgrades (no per-step option tracking).
 *
 * @return void
 */
function maca_menulist_db_apply_pending_schema_upgrades() {
    foreach (maca_menulist_db_get_migrate_steps() as $step_id => $callback) {
        try {
            call_user_func($callback);
        } catch (Throwable $e) {
            maca_menulist_debug_log(
                'schema upgrade step failed (' . $step_id . '): ' . $e->getMessage()
            );
        }
    }
}

/**
 * Run schema migrations for existing installations (all pending steps).
 */
function maca_menulist_db_migrate_schema() {
    maca_menulist_db_migrate_schema_complete();
}

/**
 * Run all pending migration steps (backup import / activation).
 *
 * @return void
 */
function maca_menulist_db_migrate_schema_complete() {
    delete_transient('maca_menulist_db_migrating');
    maca_menulist_db_apply_pending_schema_upgrades();
    maca_menulist_db_migrate_schema_mark_all_steps_completed();
}

/**
 * Finish DB version bookkeeping after all steps succeeded.
 *
 * @return void
 */
function maca_menulist_db_migrate_schema_finalize_version() {
    if (!maca_menulist_db_migrate_schema_is_complete()) {
        return;
    }

    update_option('maca_menulist_db_version', MACA_MENULIST_VERSION);
    delete_option('maca_menulist_db_migrate_target');
    delete_option('maca_menulist_db_migrate_completed');

    if (function_exists('maca_menulist_flush_rewrite_rules')) {
        maca_menulist_flush_rewrite_rules();
    }
}

/**
 * @param bool $prefer_sort_order Whether to order by sort_order first.
 * @return array<int, object>
 */
function maca_menulist_db_get_categories($prefer_sort_order = true) {
    global $wpdb;

    $table = maca_menulist_db_categories_table();

    if ($prefer_sort_order) {
        try {
            return $wpdb->get_results("SELECT * FROM $table ORDER BY sort_order ASC, name ASC");
        } catch (Exception $e) {
            return $wpdb->get_results("SELECT * FROM $table ORDER BY name ASC");
        }
    }

    return $wpdb->get_results("SELECT * FROM $table ORDER BY name ASC");
}

/**
 * @param int $category_id Category ID.
 * @return object|null
 */
function maca_menulist_db_get_category($category_id) {
    global $wpdb;

    $table = maca_menulist_db_categories_table();

    return $wpdb->get_row(
        $wpdb->prepare(
            "SELECT * FROM $table WHERE id = %d",
            intval($category_id)
        )
    );
}

/**
 * @param int $category_id Category ID.
 * @return string|null
 */
function maca_menulist_db_get_category_name_by_id($category_id) {
    global $wpdb;

    $table = maca_menulist_db_categories_table();

    return $wpdb->get_var(
        $wpdb->prepare(
            "SELECT name FROM $table WHERE id = %d",
            intval($category_id)
        )
    );
}

/**
 * @param string $category_name Category name.
 * @return int
 */
function maca_menulist_db_get_category_id_by_name($category_name) {
    global $wpdb;

    $table = maca_menulist_db_categories_table();
    $category = $wpdb->get_row(
        $wpdb->prepare(
            "SELECT id FROM $table WHERE name = %s",
            $category_name
        )
    );

    return $category ? intval($category->id) : 0;
}

/**
 * @param array<string, mixed> $data Row data.
 * @return int|false
 */
function maca_menulist_db_insert_category($data) {
    global $wpdb;

    $schema = array(
        'name' => '%s',
        'name_en' => '%s',
        'thumbnail_url' => '%s',
        'description' => '%s',
        'description_en' => '%s',
        'sort_order' => '%d',
    );

    list($row, $formats) = maca_menulist_db_prepare_row($data, $schema);

    if (empty($row)) {
        return false;
    }

    return $wpdb->insert(
        maca_menulist_db_categories_table(),
        $row,
        $formats
    );
}

/**
 * @param int                  $category_id Category ID.
 * @param array<string, mixed> $data Row data.
 * @return int|false
 */
function maca_menulist_db_update_category($category_id, $data) {
    global $wpdb;

    $schema = array(
        'name' => '%s',
        'name_en' => '%s',
        'thumbnail_url' => '%s',
        'description' => '%s',
        'description_en' => '%s',
        'sort_order' => '%d',
    );

    list($row, $formats) = maca_menulist_db_prepare_row($data, $schema);

    if (empty($row)) {
        return false;
    }

    return $wpdb->update(
        maca_menulist_db_categories_table(),
        $row,
        array('id' => intval($category_id)),
        $formats,
        array('%d')
    );
}

/**
 * @param int $category_id Category ID.
 * @return int|false
 */
function maca_menulist_db_delete_category($category_id) {
    global $wpdb;

    return $wpdb->delete(
        maca_menulist_db_categories_table(),
        array('id' => intval($category_id)),
        array('%d')
    );
}

/**
 * @param int $menu_id Menu ID.
 * @return object|null
 */
function maca_menulist_db_get_menu($menu_id) {
    global $wpdb;

    $table = maca_menulist_db_menus_table();

    return $wpdb->get_row(
        $wpdb->prepare(
            "SELECT * FROM $table WHERE id = %d",
            intval($menu_id)
        )
    );
}

/**
 * @param array<string, mixed> $data Row data.
 * @return int|false
 */
function maca_menulist_db_insert_menu($data) {
    global $wpdb;

    $schema = array(
        'category_id' => '%d',
        'title' => '%s',
        'title_en' => '%s',
        'file_url' => '%s',
        'file_type' => '%s',
        'start_date' => '%s',
        'end_date' => '%s',
        'time_start' => '%s',
        'time_end' => '%s',
        'days_of_week' => '%s',
        'is_active' => '%d',
    );

    list($row, $formats) = maca_menulist_db_prepare_row($data, $schema);

    if (empty($row)) {
        return false;
    }

    return $wpdb->insert(
        maca_menulist_db_menus_table(),
        $row,
        $formats
    );
}

/**
 * @param int                  $menu_id Menu ID.
 * @param array<string, mixed> $data Row data.
 * @return int|false
 */
function maca_menulist_db_update_menu($menu_id, $data) {
    global $wpdb;

    $schema = array(
        'category_id' => '%d',
        'title' => '%s',
        'title_en' => '%s',
        'file_url' => '%s',
        'file_type' => '%s',
        'start_date' => '%s',
        'end_date' => '%s',
        'time_start' => '%s',
        'time_end' => '%s',
        'days_of_week' => '%s',
        'is_active' => '%d',
    );

    list($row, $formats) = maca_menulist_db_prepare_row($data, $schema);

    if (empty($row)) {
        return false;
    }

    return $wpdb->update(
        maca_menulist_db_menus_table(),
        $row,
        array('id' => intval($menu_id)),
        $formats,
        array('%d')
    );
}

/**
 * @param int $menu_id Menu ID.
 * @return int|false
 */
function maca_menulist_db_delete_menu($menu_id) {
    global $wpdb;

    return $wpdb->delete(
        maca_menulist_db_menus_table(),
        array('id' => intval($menu_id)),
        array('%d')
    );
}

/**
 * @param int $menu_id Menu ID.
 * @return int|false New menu ID, or false on failure.
 */
function maca_menulist_db_duplicate_menu($menu_id) {
    global $wpdb;

    $menu = maca_menulist_db_get_menu($menu_id);
    if (!$menu) {
        return false;
    }

    $copy_suffix = ' (' . __('Copy', 'maca-restu-pro') . ')';
    $max_title_len = 255;
    $base_title = (string) $menu->title;
    if (strlen($base_title) + strlen($copy_suffix) > $max_title_len) {
        $base_title = substr($base_title, 0, $max_title_len - strlen($copy_suffix));
    }

    $row = array(
        'category_id' => (int) $menu->category_id,
        'title' => $base_title . $copy_suffix,
        'file_url' => (string) $menu->file_url,
        'file_type' => (string) $menu->file_type,
        'start_date' => $menu->start_date,
        'end_date' => $menu->end_date,
        'time_start' => $menu->time_start,
        'time_end' => $menu->time_end,
        'days_of_week' => $menu->days_of_week,
        'is_active' => (int) $menu->is_active,
    );

    if (isset($menu->title_en) && (string) $menu->title_en !== '') {
        $base_en = (string) $menu->title_en;
        if (strlen($base_en) + strlen($copy_suffix) > $max_title_len) {
            $base_en = substr($base_en, 0, $max_title_len - strlen($copy_suffix));
        }
        $row['title_en'] = $base_en . $copy_suffix;
    }

    $result = maca_menulist_db_insert_menu($row);
    if ($result === false) {
        return false;
    }

    return (int) $wpdb->insert_id;
}

/**
 * @return array<int, object>
 */
function maca_menulist_db_get_menus_with_categories() {
    global $wpdb;

    $menus_table = maca_menulist_db_menus_table();
    $categories_table = maca_menulist_db_categories_table();

    return $wpdb->get_results(
        "SELECT m.*, c.name AS category_name
        FROM $menus_table m
        LEFT JOIN $categories_table c ON m.category_id = c.id
        ORDER BY m.created_at DESC"
    );
}

/**
 * @param int $category_id Category ID.
 * @return array<int, object>
 */
function maca_menulist_db_get_menus_for_category($category_id) {
    global $wpdb;

    $menus_table = maca_menulist_db_menus_table();

    return $wpdb->get_results(
        $wpdb->prepare(
            "SELECT * FROM $menus_table
            WHERE category_id = %d
            ORDER BY created_at DESC",
            intval($category_id)
        )
    );
}

/**
 * @param int    $category_id Category ID.
 * @param string $mysql_now Current datetime in site timezone.
 * @return array<int, object>
 */
function maca_menulist_db_get_candidate_menus($category_id, $mysql_now) {
    global $wpdb;

    $menus_table = maca_menulist_db_menus_table();

    return $wpdb->get_results(
        $wpdb->prepare(
            "SELECT * FROM $menus_table
            WHERE category_id = %d
            AND is_active = 1
            AND (start_date IS NULL OR start_date <= %s)
            AND (end_date IS NULL OR end_date >= %s)
            ORDER BY created_at DESC",
            intval($category_id),
            $mysql_now,
            $mysql_now
        )
    );
}

/**
 * @return array<int, object>
 */
function maca_menulist_db_get_menus_with_http_file_urls() {
    global $wpdb;

    $menus_table = maca_menulist_db_menus_table();

    return $wpdb->get_results(
        "SELECT id, file_url FROM $menus_table WHERE file_url LIKE 'http://%'"
    );
}

/**
 * @return array<int, object>
 */
function maca_menulist_db_get_categories_with_http_thumbnails() {
    global $wpdb;

    $categories_table = maca_menulist_db_categories_table();

    return $wpdb->get_results(
        "SELECT id, thumbnail_url FROM $categories_table WHERE thumbnail_url LIKE 'http://%'"
    );
}

/**
 * @param int    $menu_id Menu ID.
 * @param string $file_url Normalized file URL.
 * @return int|false
 */
function maca_menulist_db_update_menu_file_url($menu_id, $file_url) {
    global $wpdb;

    return $wpdb->update(
        maca_menulist_db_menus_table(),
        array('file_url' => $file_url),
        array('id' => intval($menu_id)),
        array('%s'),
        array('%d')
    );
}

/**
 * @param int    $category_id Category ID.
 * @param string $thumbnail_url Normalized thumbnail URL.
 * @return int|false
 */
function maca_menulist_db_update_category_thumbnail($category_id, $thumbnail_url) {
    global $wpdb;

    return $wpdb->update(
        maca_menulist_db_categories_table(),
        array('thumbnail_url' => $thumbnail_url),
        array('id' => intval($category_id)),
        array('%s'),
        array('%d')
    );
}

/**
 * Drop plugin tables on uninstall.
 */
function maca_menulist_db_drop_tables() {
    global $wpdb;

    foreach (array(maca_menulist_db_categories_table(), maca_menulist_db_menus_table()) as $table) {
        $wpdb->query("DROP TABLE IF EXISTS {$table}");
    }

    require_once dirname(__FILE__) . '/db-dishes.php';
    maca_menulist_db_drop_dish_tables();

    require_once dirname(__FILE__) . '/db-table-orders.php';
    maca_menulist_db_drop_table_order_tables();

    require_once dirname(__FILE__) . '/db-table-bookings.php';
    maca_menulist_db_drop_table_booking_tables();

    require_once dirname(__FILE__) . '/attendance-log.php';
    require_once dirname(__FILE__) . '/db-attendance.php';
    maca_menulist_db_drop_attendance_tables();

    require_once dirname(__FILE__) . '/db-info-hub.php';
    maca_menulist_db_drop_info_hub_tables();

    require_once dirname(__FILE__) . '/db-info-hub-social.php';
    maca_menulist_db_drop_info_social_log_table();
}

// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.SchemaChange
