<?php

declare(strict_types=1);

/**
 * 會員推薦店家（spa_store_snapshots.source_type = manual）。
 */

require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_store_listing.php';

/** 組合列表用地址字串。 */
function fate_member_store_format_address(array $row): string
{
    $display = trim((string) ($row['display_address'] ?? ''));
    if ($display !== '') {
        return $display;
    }
    $place = trim((string) ($row['place_formatted_address'] ?? ''));
    if ($place !== '') {
        return $place;
    }
    $parts = array_filter([
        trim((string) ($row['city_name'] ?? '')),
        trim((string) ($row['district_name'] ?? '')),
        trim((string) ($row['street_address'] ?? '')),
    ], static fn (string $p): bool => $p !== '');

    return implode('', $parts);
}

/**
 * @return list<array{spa_store_id:int,store_name:string,display_address:string,location_text:string,listing_kind:string,listing_label:string,is_approved:int,synced_at:string}>
 */
function fate_member_stores_for_member(PDO $pdo, int $memberId): array
{
    if ($memberId <= 0) {
        return [];
    }

    try {
        $st = $pdo->prepare(
            'SELECT `spa_store_id`, `store_name`, `display_address`, `place_formatted_address`,
                    `city_name`, `district_name`, `street_address`, `payload_json`,
                    `is_approved`, `synced_at`
             FROM `spa_store_snapshots`
             WHERE `created_member_id` = ? AND `source_type` = ?
             ORDER BY `synced_at` DESC, `spa_store_id` DESC'
        );
        $st->execute([$memberId, 'manual']);
        $rows = $st->fetchAll(PDO::FETCH_ASSOC);
        if (!is_array($rows)) {
            return [];
        }

        $out = [];
        foreach ($rows as $row) {
            if (!is_array($row)) {
                continue;
            }
            $kind = fate_store_listing_kind_from_row($row);
            $out[] = [
                'spa_store_id' => (int) ($row['spa_store_id'] ?? 0),
                'store_name' => (string) ($row['store_name'] ?? ''),
                'display_address' => fate_member_store_format_address($row),
                'location_text' => fate_store_listing_location_text($row),
                'listing_kind' => $kind,
                'listing_label' => fate_store_listing_label($kind),
                'is_approved' => (int) ($row['is_approved'] ?? 0),
                'synced_at' => (string) ($row['synced_at'] ?? ''),
            ];
        }

        return $out;
    } catch (Throwable $e) {
        error_log('fate_member_stores_for_member: ' . $e->getMessage());

        return [];
    }
}

function fate_member_stores_count_for_member(PDO $pdo, int $memberId): int
{
    if ($memberId <= 0) {
        return 0;
    }
    try {
        $st = $pdo->prepare(
            'SELECT COUNT(*) FROM `spa_store_snapshots`
             WHERE `created_member_id` = ? AND `source_type` = ?'
        );
        $st->execute([$memberId, 'manual']);

        return (int) $st->fetchColumn();
    } catch (Throwable) {
        return 0;
    }
}
