<?php

declare(strict_types=1);

namespace CliqThemes\StoreLocator\Support;

defined('ABSPATH') || exit;

// A demo refresh may remove one hero assignment from the plugin-owned meta
// table. The composite key makes both statements targeted and deterministic.
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
// phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key

/**
 * Resolves the lightweight hero bundled with plugin-created demo stores.
 *
 * Demo artwork is deliberately not imported into the Media Library. A real
 * hero selected by the user always takes precedence over this fallback.
 */
final class DemoHero
{
    public const META_KEY = '_cliq_sl_demo_store';

    private const FILE = 'assets/demo/sl-demo-hero.jpg';

    public static function url(): string
    {
        return CLIQ_SL_URL . self::FILE;
    }

    /**
     * @param array<string, mixed> $meta
     */
    public static function resolve(?string $explicitUrl, array $meta): ?string
    {
        if ($explicitUrl !== null && trim($explicitUrl) !== '') {
            return $explicitUrl;
        }

        return ! empty($meta[self::META_KEY]) ? self::url() : null;
    }

    /**
     * Detach a hero that a previous demo seeding assigned, without touching a
     * hero the user selected themselves. The orphaned attachment is left in the
     * Media Library because deleting user-visible media during a demo refresh
     * would be unexpectedly destructive.
     */
    public static function detachDemoAssignment(int $storeId): void
    {
        global $wpdb;

        $table = $wpdb->prefix . 'cliq_sl_store_meta';
        $raw = $wpdb->get_var($wpdb->prepare(
            'SELECT meta_value FROM %i WHERE store_id = %d AND meta_key = %s LIMIT 1',
            $table,
            $storeId,
            'hero_media'
        ));
        if (! is_string($raw) || $raw === '') {
            return;
        }

        $media = StoredValue::decode($raw);
        $attachmentId = is_array($media) ? (int) ($media['id'] ?? 0) : 0;
        if ($attachmentId <= 0 || get_post_meta($attachmentId, '_cliq_sl_demo_asset', true) === '') {
            return;
        }

        $wpdb->delete(
            $table,
            ['store_id' => $storeId, 'meta_key' => 'hero_media'],
            ['%d', '%s']
        );
    }
}
