<?php
declare(strict_types=1);

require_once __DIR__ . DIRECTORY_SEPARATOR . 'auth.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'layout.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'dashboard_icons.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_store_geocode.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'spa_stores_write.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'spa_store_sync.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'google_place_opening_hours.php';

fate_admin_require_login();

$adminSiteName = fate_admin_site_main_name();

$fatePdo = null;
$dbErr = null;
try {
    require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'pdo.php';
    if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
        $fatePdo = $GLOBALS['pdo'];
    }
} catch (Throwable $e) {
    $dbErr = $e->getMessage();
}

$error = null;
$success = null;
$newStoreId = 0;

$defaults = [
    'store_name' => '',
    'city_name' => '',
    'district_name' => '',
    'zip_code' => '',
    'street_address' => '',
    'place_formatted_address' => '',
    'google_map_location' => '',
    'phone' => '',
    'mobile' => '',
    'line' => '',
    'wechat' => '',
    'website' => '',
    'facebook' => '',
    'description' => '',
    'spa_type' => '',
    'business_type' => '',
    'payment_method' => '',
    'parking' => '',
    'basic_charge' => '',
    'business_hours_start' => '',
    'business_hours_end' => '',
    'service_target' => 'both_customers',
    'appointment_required' => '非預約制',
    'multi_hours_json' => '{}',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $dbErr === null) {
    $csrf = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
    if (!fate_admin_csrf_check($csrf)) {
        $error = '工作階段逾期，請重新整理後再試。';
    } else {
        foreach (array_keys($defaults) as $k) {
            if (isset($_POST[$k]) && is_string($_POST[$k])) {
                $defaults[$k] = trim($_POST[$k]);
            }
        }
        $defaults['appointment_required'] = !empty($_POST['appointment_required']) ? '預約' : '非預約制';

        $multiHoursRaw = isset($_POST['multi_hours_json']) && is_string($_POST['multi_hours_json'])
            ? trim($_POST['multi_hours_json'])
            : '{}';
        $multiHours = fate_parse_multi_hours_json($multiHoursRaw);
        $defaults['multi_hours_json'] = json_encode($multiHours, JSON_UNESCAPED_UNICODE);

        $storeName = $defaults['store_name'];
        $city = $defaults['city_name'];
        $district = $defaults['district_name'];
        $street = $defaults['street_address'];

        if ($storeName === '' || $city === '' || $district === '' || $street === '') {
            $error = '請填寫店名、城市、地區與街道地址。';
        } elseif (!isset($_FILES['cover_photo_path']) || (int) ($_FILES['cover_photo_path']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
            $error = '請上傳封面照片。';
        } else {
            try {
                $geoQuery = fate_build_geocode_query($city, $district, $street);
                $manualGml = fate_parse_manual_gps($defaults['google_map_location']);
                if ($manualGml !== null) {
                    $geo = [
                        'ok' => true,
                        'google_map_location' => $manualGml,
                        'display_name' => $geoQuery,
                    ];
                } else {
                    $geo = fate_store_geocode_address($city, $district, $street, $defaults['zip_code']);
                    if (empty($geo['ok'])) {
                        throw new RuntimeException(
                            (string) ($geo['error'] ?? '無法由地址取得 GPS')
                            . '（可手動填入 GPS 欄位：緯度,經度）'
                        );
                    }
                }

                $gml = (string) ($geo['google_map_location'] ?? '');
                $placeAddr = trim((string) ($defaults['place_formatted_address'] ?? ''));
                if ($placeAddr === '' && !empty($geo['display_name'])) {
                    $placeAddr = (string) $geo['display_name'];
                }
                if ($placeAddr === '') {
                    $placeAddr = $geoQuery;
                }

                $coverPath = fate_spa_stores_save_uploaded_image($_FILES['cover_photo_path'], 'fate_cover');
                $photoPaths = [];
                if (isset($_FILES['interior_images']) && is_array($_FILES['interior_images']['name'])) {
                    $n = count($_FILES['interior_images']['name']);
                    for ($i = 0; $i < $n && $i < 4; $i++) {
                        if ((int) ($_FILES['interior_images']['error'][$i] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
                            continue;
                        }
                        $one = [
                            'name' => $_FILES['interior_images']['name'][$i],
                            'type' => $_FILES['interior_images']['type'][$i] ?? '',
                            'tmp_name' => $_FILES['interior_images']['tmp_name'][$i],
                            'error' => $_FILES['interior_images']['error'][$i],
                            'size' => $_FILES['interior_images']['size'][$i] ?? 0,
                        ];
                        try {
                            $photoPaths[] = fate_spa_stores_save_uploaded_image($one, 'fate_int');
                        } catch (Throwable $eUp) {
                            error_log('fate add_store interior: ' . $eUp->getMessage());
                        }
                    }
                }

                $basicCharge = $defaults['basic_charge'];
                $basicVal = ($basicCharge !== '' && is_numeric($basicCharge)) ? (float) $basicCharge : null;

                $insertFields = [
                    'store_name' => $storeName,
                    'city_name' => $city,
                    'district_name' => $district,
                    'zip_code' => $defaults['zip_code'],
                    'street_address' => $street,
                    'place_formatted_address' => $placeAddr,
                    'google_map_location' => $gml,
                    'static_gps_location' => $gml,
                    'phone' => $defaults['phone'],
                    'mobile' => $defaults['mobile'],
                    'line' => $defaults['line'],
                    'wechat' => $defaults['wechat'],
                    'website' => $defaults['website'],
                    'facebook' => $defaults['facebook'],
                    'spa_type' => $defaults['spa_type'],
                    'description' => $defaults['description'],
                    'payment_method' => $defaults['payment_method'],
                    'parking' => $defaults['parking'],
                    'business_hours_start' => $defaults['business_hours_start'],
                    'business_hours_end' => $defaults['business_hours_end'],
                    'place_opening_hours' => fate_generate_google_place_hours($multiHours),
                    'service_target' => $defaults['service_target'],
                    'business_type' => $defaults['business_type'],
                    'basic_charge' => $basicVal,
                    'appointment_required' => $defaults['appointment_required'],
                    'registrant' => $adminSiteName . '後台',
                    'user_ip_address' => (string) ($_SERVER['REMOTE_ADDR'] ?? ''),
                    'cover_photo_path' => $coverPath,
                    'photo_paths' => json_encode($photoPaths, JSON_UNESCAPED_SLASHES),
                    'is_approved' => 1,
                    'created_at' => date('Y-m-d H:i:s'),
                ];

                $newStoreId = fate_spa_stores_insert($insertFields);

                $syncNote = '';
                if ($fatePdo instanceof PDO) {
                    $sync = fate_spa_sync_snapshot_for_store($fatePdo, $newStoreId);
                    if (empty($sync['ok'])) {
                        $syncNote = '（已寫入新手村，但同步至 ' . $adminSiteName . ' 快照失敗：' . ($sync['error'] ?? '') . '，請至「同步店家」手動更新）';
                    }
                }

                $success = '已新增店家 #' . $newStoreId . '，GPS：' . $gml . $syncNote;
            } catch (Throwable $e) {
                $error = $e->getMessage();
                error_log('fate admin add_store: ' . $e->getMessage());
            }
        }
    }
}

$csrf = fate_admin_csrf_token();
$citiesApi = fate_admin_asset_url('cities_api.php');
$geocodeApi = fate_admin_asset_url('geocode_api.php');
$weekdaysEn = ['Monday' => '一', 'Tuesday' => '二', 'Wednesday' => '三', 'Thursday' => '四', 'Friday' => '五', 'Saturday' => '六', 'Sunday' => '日'];
$parkingOptions = ['路邊停車', '備專用停車場', '收費停車場（100M）'];

$dbOk = $dbErr === null && $fatePdo instanceof PDO;

fate_admin_layout_start(['page' => '新增店家', 'active' => 'add_store', 'body_class' => 'admin-body--add-store page-add-store']);
?>
        <div class="add-store">
            <header class="add-store-hero" aria-label="新增店家">
                <div class="add-store-hero__glow" aria-hidden="true"></div>
                <div class="add-store-hero__inner">
                    <div class="add-store-hero__lead">
                        <span class="add-store-hero__icon" aria-hidden="true"><?= fate_admin_dashboard_icon('add_store') ?></span>
                        <div class="add-store-hero__copy">
                            <h1 class="add-store-hero__title">新增店家</h1>
                            <p class="add-store-hero__sub">手動建立店家並寫入新手村；成功後自動嘗試更新本站快照，失敗請至 <a href="sync.php">同步店家</a> 手動更新。</p>
                        </div>
                    </div>
                    <span class="sync-pill<?= $dbOk ? ' sync-pill--ok' : ' sync-pill--bad' ?>"><?= $dbOk ? '可新增' : '資料庫異常' ?></span>
                </div>
            </header>

            <?php if ($dbErr !== null): ?>
                <div class="sync-banner sync-banner--bad" role="alert">
                    <span class="sync-banner__icon"><?= fate_admin_dashboard_icon('alert-bad') ?></span>
                    <p class="sync-banner__text">無法連線資料庫：<?= htmlspecialchars($dbErr, ENT_QUOTES, 'UTF-8') ?></p>
                </div>
            <?php endif; ?>

            <?php if ($success !== null): ?>
                <div class="sync-banner sync-banner--ok" role="status">
                    <span class="sync-banner__icon"><?= fate_admin_dashboard_icon('check') ?></span>
                    <div class="sync-banner__body">
                        <p class="sync-banner__text"><?= htmlspecialchars($success, ENT_QUOTES, 'UTF-8') ?></p>
                        <?php if ($newStoreId > 0): ?>
                            <p class="sync-banner__links">
                                <a href="../store.php?id=<?= (int) $newStoreId ?>">預覽 <?= htmlspecialchars($adminSiteName, ENT_QUOTES, 'UTF-8') ?> 店家頁</a>
                                <span aria-hidden="true">·</span>
                                <a href="sync.php">同步店家</a>
                            </p>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>

            <?php if ($error !== null): ?>
                <div class="sync-banner sync-banner--bad" role="alert">
                    <span class="sync-banner__icon"><?= fate_admin_dashboard_icon('alert-bad') ?></span>
                    <p class="sync-banner__text"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></p>
                </div>
            <?php endif; ?>

        <form method="post" action="add_store.php" enctype="multipart/form-data" class="stack-form add-store-form" id="fateAddStoreForm">
            <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">

            <section class="sync-panel add-store-section">
                <header class="sync-panel__head">
                    <h2 class="sync-panel__title">基本資料</h2>
                    <p class="add-store-section-hint">店名、城市、地區、街道為必填；選城市後自動帶入郵遞區號。</p>
                </header>
                <div class="field-grid">
                    <label class="field field--full">
                        <span class="field-label">店名 <em>*</em></span>
                        <input type="text" name="store_name" required maxlength="255" value="<?= htmlspecialchars($defaults['store_name'], ENT_QUOTES, 'UTF-8') ?>">
                    </label>
                    <label class="field">
                        <span class="field-label">城市 <em>*</em></span>
                        <select name="city_name" id="citySelector" required>
                            <option value="">載入中…</option>
                        </select>
                    </label>
                    <label class="field">
                        <span class="field-label">地區 <em>*</em></span>
                        <select name="district_name" id="districtSelector" required disabled>
                            <option value="">請先選擇城市</option>
                        </select>
                    </label>
                    <label class="field">
                        <span class="field-label">郵遞區號</span>
                        <input type="text" name="zip_code" id="zipCode" maxlength="10" value="<?= htmlspecialchars($defaults['zip_code'], ENT_QUOTES, 'UTF-8') ?>" readonly>
                    </label>
                    <label class="field field--full">
                        <span class="field-label">街道地址 <em>*</em></span>
                        <input type="text" name="street_address" id="streetAddress" required value="<?= htmlspecialchars($defaults['street_address'], ENT_QUOTES, 'UTF-8') ?>">
                    </label>
                    <label class="field field--full">
                        <span class="field-label">格式化地址（選填）</span>
                        <input type="text" name="place_formatted_address" id="placeFormattedAddress" value="<?= htmlspecialchars($defaults['place_formatted_address'], ENT_QUOTES, 'UTF-8') ?>">
                    </label>
                </div>
                <p class="add-store-hint" id="cityDistrictStatus" role="status"></p>
                <div class="add-store-geocode">
                    <button type="button" class="sync-btn" id="btnGeocodePreview">由地址預覽 GPS</button>
                    <span id="geocodeStatus" class="add-store-hint"></span>
                </div>
                <label class="field field--full">
                    <span class="field-label">GPS</span>
                    <input type="text" name="google_map_location" id="gpsLocation" value="<?= htmlspecialchars($defaults['google_map_location'], ENT_QUOTES, 'UTF-8') ?>" placeholder="預覽自動填入，或手動輸入 25.033964,121.564468" autocomplete="off">
                </label>
            </section>

            <section class="sync-panel add-store-section">
                <header class="sync-panel__head">
                    <h2 class="sync-panel__title">照片</h2>
                    <p class="add-store-section-hint">封面必填；店內照片最多 4 張。</p>
                </header>
                <label class="field field--full">
                    <span class="field-label">封面照片 <em>*</em></span>
                    <input type="file" name="cover_photo_path" id="coverPhotoInput" accept="image/jpeg,image/png,image/gif,image/webp" required>
                    <div class="photo-preview photo-preview--cover" id="coverPhotoPreview" hidden></div>
                </label>
                <label class="field field--full">
                    <span class="field-label">店內照片（最多 4 張，選填）</span>
                    <input type="file" name="interior_images[]" id="interiorImagesInput" accept="image/jpeg,image/png,image/gif,image/webp" multiple>
                    <div class="photo-preview photo-preview--grid" id="interiorPhotoPreview" hidden></div>
                </label>
            </section>

            <section class="sync-panel add-store-section">
                <header class="sync-panel__head">
                    <h2 class="sync-panel__title">聯絡與營業</h2>
                    <p class="add-store-section-hint">其餘欄位選填；營業時間可設起迄，或使用多時段（Google 格式）。</p>
                </header>
                <div class="field-grid">
                    <label class="field">
                        <span class="field-label">電話</span>
                        <input type="text" name="phone" value="<?= htmlspecialchars($defaults['phone'], ENT_QUOTES, 'UTF-8') ?>">
                    </label>
                    <label class="field">
                        <span class="field-label">手機</span>
                        <input type="text" name="mobile" value="<?= htmlspecialchars($defaults['mobile'], ENT_QUOTES, 'UTF-8') ?>">
                    </label>
                    <label class="field">
                        <span class="field-label">LINE</span>
                        <input type="text" name="line" value="<?= htmlspecialchars($defaults['line'], ENT_QUOTES, 'UTF-8') ?>">
                    </label>
                    <label class="field">
                        <span class="field-label">WeChat</span>
                        <input type="text" name="wechat" value="<?= htmlspecialchars($defaults['wechat'], ENT_QUOTES, 'UTF-8') ?>">
                    </label>
                    <label class="field">
                        <span class="field-label">網站</span>
                        <input type="url" name="website" value="<?= htmlspecialchars($defaults['website'], ENT_QUOTES, 'UTF-8') ?>">
                    </label>
                    <label class="field">
                        <span class="field-label">Facebook</span>
                        <input type="url" name="facebook" value="<?= htmlspecialchars($defaults['facebook'], ENT_QUOTES, 'UTF-8') ?>">
                    </label>
                    <label class="field">
                        <span class="field-label">服務對象</span>
                        <select name="service_target">
                            <option value="male_customers" <?= $defaults['service_target'] === 'male_customers' ? 'selected' : '' ?>>男性專屬</option>
                            <option value="female_customers" <?= $defaults['service_target'] === 'female_customers' ? 'selected' : '' ?>>女性專屬</option>
                            <option value="both_customers" <?= $defaults['service_target'] === 'both_customers' ? 'selected' : '' ?>>男女皆可</option>
                        </select>
                    </label>
                    <label class="field">
                        <span class="field-label">業態</span>
                        <input type="text" name="business_type" value="<?= htmlspecialchars($defaults['business_type'], ENT_QUOTES, 'UTF-8') ?>" placeholder="例：按摩、SPA">
                    </label>
                    <label class="field">
                        <span class="field-label">SPA 類型</span>
                        <input type="text" name="spa_type" value="<?= htmlspecialchars($defaults['spa_type'], ENT_QUOTES, 'UTF-8') ?>" placeholder="多項以逗號分隔">
                    </label>
                    <label class="field">
                        <span class="field-label">起價（元）</span>
                        <input type="number" name="basic_charge" min="0" step="1" value="<?= htmlspecialchars($defaults['basic_charge'], ENT_QUOTES, 'UTF-8') ?>">
                    </label>
                    <label class="field">
                        <span class="field-label">營業起</span>
                        <input type="time" name="business_hours_start" id="businessHoursStart" value="<?= htmlspecialchars($defaults['business_hours_start'], ENT_QUOTES, 'UTF-8') ?>">
                    </label>
                    <label class="field">
                        <span class="field-label">營業迄</span>
                        <input type="time" name="business_hours_end" id="businessHoursEnd" value="<?= htmlspecialchars($defaults['business_hours_end'], ENT_QUOTES, 'UTF-8') ?>">
                    </label>
                    <div class="field field--hours-actions">
                        <span class="field-label">營業時間</span>
                        <div class="hours-btn-row">
                            <button type="button" class="btn btn--sm" id="btnSetSimple24Hours">簡易 24 小時</button>
                            <button type="button" class="btn btn--sm" id="btnOpenHoursModal">多時段（Google 格式）</button>
                        </div>
                        <p class="hours-summary sub" id="hoursSummary">尚未設定（可留空）</p>
                        <input type="hidden" name="multi_hours_json" id="multiHoursJson" value="<?= htmlspecialchars($defaults['multi_hours_json'], ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                    <label class="field">
                        <span class="field-label">付款方式</span>
                        <input type="text" name="payment_method" value="<?= htmlspecialchars($defaults['payment_method'], ENT_QUOTES, 'UTF-8') ?>">
                    </label>
                    <label class="field">
                        <span class="field-label">停車</span>
                        <select name="parking" id="parkingSelect">
                            <option value="">請選擇（選填）</option>
                            <?php
                            $parkCurrent = $defaults['parking'];
                            if ($parkCurrent !== '' && !in_array($parkCurrent, $parkingOptions, true)):
                            ?>
                                <option value="<?= htmlspecialchars($parkCurrent, ENT_QUOTES, 'UTF-8') ?>" selected><?= htmlspecialchars($parkCurrent, ENT_QUOTES, 'UTF-8') ?>（舊值）</option>
                            <?php endif; ?>
                            <?php foreach ($parkingOptions as $parkOpt): ?>
                                <option value="<?= htmlspecialchars($parkOpt, ENT_QUOTES, 'UTF-8') ?>" <?= $parkCurrent === $parkOpt ? 'selected' : '' ?>><?= htmlspecialchars($parkOpt, ENT_QUOTES, 'UTF-8') ?></option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                    <label class="field field--check">
                        <input type="checkbox" name="appointment_required" value="1" <?= $defaults['appointment_required'] === '預約' ? 'checked' : '' ?>>
                        <span>需預約</span>
                    </label>
                    <label class="field field--full">
                        <span class="field-label">簡介</span>
                        <textarea name="description" rows="4"><?= htmlspecialchars($defaults['description'], ENT_QUOTES, 'UTF-8') ?></textarea>
                    </label>
                </div>
            </section>

            <div class="add-store-submit">
                <button type="submit" class="sync-btn sync-btn--primary">
                    <?= fate_admin_dashboard_icon('add_store') ?>
                    <span>新增店家</span>
                </button>
                <a href="index.php" class="sync-btn">返回概覽</a>
            </div>
        </form>

            <details class="add-store-more">
                <summary class="add-store-more__title">補充說明</summary>
                <ul class="add-store-more__list">
                    <li>「由地址預覽 GPS」優先使用 Google Geocoding；未設定金鑰時改以 OpenStreetMap 備援，亦可手動填 <code>緯度,經度</code>。</li>
                    <li>Geocoding 金鑰於 <a href="template.php">網站與模版</a> 設定。</li>
                    <li>大量店家建議使用 <a href="sync.php">同步店家</a> 從新手村更新，而非逐筆手動新增。</li>
                </ul>
            </details>
        </div>

        <dialog class="hours-dialog" id="multiHoursModal" aria-labelledby="multiHoursModalTitle">
            <form method="dialog" class="hours-dialog__inner" onsubmit="return false;">
                <header class="hours-dialog__head">
                    <h2 id="multiHoursModalTitle">多時段設定</h2>
                    <button type="button" class="hours-dialog__close" id="btnCancelMultiHours" aria-label="關閉">×</button>
                </header>
                <p class="sub add-store-dialog-hint">格式 <code>09:00-18:00</code>；休息 <code>Closed</code>；24 小時 <code>00:00-00:00</code>。</p>
                <table class="hours-table">
                    <thead>
                        <tr><th>星期</th><th>時間</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach ($weekdaysEn as $dayKey => $dayLabel): ?>
                        <tr>
                            <td>週<?= htmlspecialchars($dayLabel, ENT_QUOTES, 'UTF-8') ?></td>
                            <td>
                                <div class="hours-row-input">
                                    <input type="text" class="multi-hours-input" data-day="<?= htmlspecialchars($dayKey, ENT_QUOTES, 'UTF-8') ?>" placeholder="09:00-18:00" autocomplete="off">
                                    <button type="button" class="btn btn--xs hours-set-closed" data-day="<?= htmlspecialchars($dayKey, ENT_QUOTES, 'UTF-8') ?>">休息</button>
                                    <button type="button" class="btn btn--xs hours-set-24h" data-day="<?= htmlspecialchars($dayKey, ENT_QUOTES, 'UTF-8') ?>">24h</button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <footer class="hours-dialog__foot">
                    <button type="button" class="btn" id="btnCancelMultiHoursFoot">取消</button>
                    <button type="button" class="btn" id="btnSaveMultiHours">套用</button>
                </footer>
            </form>
        </dialog>

        <?php
        $addStoreJs = __DIR__ . DIRECTORY_SEPARATOR . 'static' . DIRECTORY_SEPARATOR . 'add_store.js';
        $addStoreJsVer = is_file($addStoreJs) ? (string) filemtime($addStoreJs) : '1';
        ?>
        <script>
        window.FATE_ADD_STORE_CFG = <?= json_encode([
            'citiesApi' => $citiesApi,
            'geocodeApi' => $geocodeApi,
            'initialCity' => $defaults['city_name'],
            'initialDistrict' => $defaults['district_name'],
            'multiHoursJson' => $defaults['multi_hours_json'],
        ], JSON_UNESCAPED_UNICODE) ?>;
        </script>
        <script src="<?= htmlspecialchars(fate_admin_asset_url('static/add_store.js'), ENT_QUOTES, 'UTF-8') ?>?v=<?= htmlspecialchars($addStoreJsVer, ENT_QUOTES, 'UTF-8') ?>"></script>
<?php
fate_admin_layout_end();
