<?php
declare(strict_types=1);

/**
 * 產生 Google Places 相容的 place_opening_hours JSON（與 s_add_shop.php 相同邏輯）。
 *
 * @param array<string,string> $multiHours 鍵為英文星期 Monday…Sunday，值為 HH:MM-HH:MM、Closed、空字串或 00:00-00:00
 */
function fate_generate_google_place_hours(array $multiHours): string
{
    $weekdayNames = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    $dayMap = [
        'Sunday' => 0,
        'Monday' => 1,
        'Tuesday' => 2,
        'Wednesday' => 3,
        'Thursday' => 4,
        'Friday' => 5,
        'Saturday' => 6,
    ];

    $result = ['open_now' => false, 'periods' => [], 'weekday_text' => []];

    foreach ($dayMap as $dayKey => $dayNum) {
        $hours = trim((string) ($multiHours[$dayKey] ?? ''));
        $text = $weekdayNames[$dayNum] . ': ';

        if ($hours === '') {
            $text .= '未設定';
        } elseif (strcasecmp($hours, 'Closed') === 0) {
            $text .= '休息';
        } elseif ($hours === '00:00-00:00' || $hours === '0000-0000') {
            $text .= '24小時';
            $result['periods'][] = [
                'open' => ['day' => $dayNum, 'time' => '0000'],
                'close' => ['day' => $dayNum, 'time' => '0000'],
            ];
            $result['open_now'] = true;
        } else {
            $segments = explode(',', $hours);
            $textHours = [];
            foreach ($segments as $segment) {
                $segment = trim($segment);
                if ($segment === '') {
                    continue;
                }
                if (!preg_match('/^(\d{2}):(\d{2})-(\d{2}):(\d{2})$/', $segment, $matches)) {
                    continue;
                }
                $startClean = $matches[1] . $matches[2];
                $endClean = $matches[3] . $matches[4];
                $textHours[] = $matches[1] . ':' . $matches[2] . ' – ' . $matches[3] . ':' . $matches[4];
                $closeDay = ($endClean < $startClean && $endClean !== '0000') ? ($dayNum + 1) % 7 : $dayNum;
                $result['periods'][] = [
                    'open' => ['day' => $dayNum, 'time' => $startClean],
                    'close' => ['day' => $closeDay, 'time' => $endClean],
                ];
            }
            if ($textHours !== []) {
                $text .= implode(', ', $textHours);
                $result['open_now'] = true;
            } else {
                $text .= '未設定';
            }
        }
        $result['weekday_text'][] = $text;
    }

    return json_encode($result, JSON_UNESCAPED_UNICODE);
}

/**
 * @return array<string,string>
 */
function fate_default_multi_hours_week(): array
{
    return [
        'Monday' => '',
        'Tuesday' => '',
        'Wednesday' => '',
        'Thursday' => '',
        'Friday' => '',
        'Saturday' => '',
        'Sunday' => '',
    ];
}

/**
 * @param mixed $json
 * @return array<string,string>
 */
function fate_parse_multi_hours_json($json): array
{
    $base = fate_default_multi_hours_week();
    if (!is_string($json) || trim($json) === '') {
        return $base;
    }
    $decoded = json_decode($json, true);
    if (!is_array($decoded)) {
        return $base;
    }
    foreach ($base as $day => $_) {
        if (isset($decoded[$day]) && is_string($decoded[$day])) {
            $base[$day] = trim($decoded[$day]);
        }
    }

    return $base;
}
