<?php

declare(strict_types=1);

namespace CliqThemes\StoreLocator\Schema;

defined('ABSPATH') || exit;

// Activation seeding intentionally writes plugin-owned reference tables.
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching


/** Seeds reference data that is required before a user imports demo stores. */
final class DemoSeeder
{
    /**
     * Seed non-store reference data only.
     *
     * Store records and their categories belong to the vertical selected in
     * the onboarding demo importer. Activation must never create unrelated
     * Flagship/Boutique stores or assign arbitrary categories to user stores.
     */
    public static function seedAuxiliary(): void
    {
        global $wpdb;

        $now = function_exists('current_time') ? current_time('mysql') : gmdate('Y-m-d H:i:s');
        $prefix = $wpdb->prefix;

        $tableExists = static function (string $table) use ($wpdb): bool {
            return (bool) $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table));
        };
        $isEmpty = static function (string $table) use ($wpdb): bool {
            return (int) $wpdb->get_var($wpdb->prepare('SELECT COUNT(*) FROM %i', $table)) === 0;
        };

        $countriesTable = $prefix . 'cliq_sl_countries';
        if ($tableExists($countriesTable) && $isEmpty($countriesTable)) {
            foreach (
                [
                    ['Australia', 'AU', 'AUS'],
                    ['Canada', 'CA', 'CAN'],
                    ['France', 'FR', 'FRA'],
                    ['Germany', 'DE', 'DEU'],
                    ['India', 'IN', 'IND'],
                    ['Italy', 'IT', 'ITA'],
                    ['United Kingdom', 'GB', 'GBR'],
                    ['United States', 'US', 'USA'],
                ] as [$name, $iso2, $iso3]
            ) {
                $wpdb->insert(
                    $countriesTable,
                    ['name' => $name, 'iso2' => $iso2, 'iso3' => $iso3],
                    ['%s', '%s', '%s']
                );
            }
        }

        /**
         * Seed the reference data a feature of your own needs.
         *
         * @param string $prefix the site's table prefix
         * @param string $now    a shared timestamp, so one pass has one time
         */
        do_action('cliq_sl_seed_reference_data', $prefix, $now);
    }
}
