<?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_listing.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_masseur_rewards.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_ncoin_settings.php';

fate_admin_require_login();

$ncoinName = fate_ncoin_display_name();
$ncoinNameEsc = htmlspecialchars($ncoinName, ENT_QUOTES, 'UTF-8');

$actingAdminId = (int) ($_SESSION['fate_admin_member_id'] ?? 0);

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

$flashOk = null;
$flashErr = null;

if ($pdo instanceof PDO && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrf = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
    if (!fate_admin_csrf_check($csrf)) {
        $flashErr = '工作階段逾期或驗證失敗，請重新整理後再試。';
    } else {
        $action = isset($_POST['action']) && is_string($_POST['action']) ? $_POST['action'] : '';
        $storeId = isset($_POST['store_id']) ? (int) $_POST['store_id'] : 0;

        if ($storeId <= 0) {
            $flashErr = '無效的店家 ID';
        } elseif ($action === 'approve') {
            try {
                $fetch = $pdo->prepare(
                    "SELECT `created_member_id`, `payload_json`, `is_approved`, `store_name`
                     FROM `spa_store_snapshots`
                     WHERE `spa_store_id` = ? AND `source_type` = 'manual' LIMIT 1"
                );
                $fetch->execute([$storeId]);
                $pending = $fetch->fetch(PDO::FETCH_ASSOC);
                if (!is_array($pending)) {
                    $flashErr = '找不到該推薦店家。';
                } elseif ((int) ($pending['is_approved'] ?? 0) === 1) {
                    $flashOk = '該店家已核准，無需重複操作。';
                } else {
                    $stmt = $pdo->prepare(
                        "UPDATE `spa_store_snapshots` SET `is_approved` = 1, `synced_at` = NOW()
                         WHERE `spa_store_id` = ? AND `source_type` = 'manual' AND `is_approved` = 0"
                    );
                    $stmt->execute([$storeId]);
                    if ($stmt->rowCount() < 1) {
                        $flashErr = '核准失敗：狀態可能已變更。';
                    } else {
                        $creatorId = (int) ($pending['created_member_id'] ?? 0);
                        $kind = fate_store_listing_kind_from_row($pending);
                        $username = '';
                        if ($creatorId > 0) {
                            try {
                                $dbEsc = str_replace('`', '``', FATE_MEMBER_DATABASE);
                                $tblEsc = str_replace('`', '``', FATE_MEMBER_TABLE);
                                $uSt = $pdo->prepare("SELECT `username` FROM `$dbEsc`.`$tblEsc` WHERE `id` = ? LIMIT 1");
                                $uSt->execute([$creatorId]);
                                $username = (string) ($uSt->fetchColumn() ?: '');
                            } catch (Throwable) {
                            }
                        }
                        $rewardAmt = fate_store_recommend_reward_grant($pdo, $creatorId, $storeId, $kind, $username);
                        $flashOk = '已成功核准該店家！現在起，該店家將公開展示於列表與搜尋結果。';
                        if ($rewardAmt > 0) {
                            $flashOk .= ' 已發放 ' . number_format($rewardAmt) . ' ' . $ncoinNameEsc . '給推薦會員。';
                        } elseif ($creatorId > 0) {
                            $flashOk .= ' （未發放 ' . $ncoinNameEsc . '：獎勵金額為 0、無推薦人，或該筆已發過。請至「站內貨幣設定/紀錄」調整店家核准獎勵。）';
                        }
                    }
                }
            } catch (Throwable $e) {
                $flashErr = '核准失敗：' . $e->getMessage();
            }
        } elseif ($action === 'reject') {
            try {
                // Fetch cover photo and interior photos to clean up files from disk
                $stmt = $pdo->prepare(
                    "SELECT `cover_photo_path`, `photos_json`, `payload_json`, `is_approved`
                     FROM `spa_store_snapshots` WHERE `spa_store_id` = ? AND `source_type` = 'manual'"
                );
                $stmt->execute([$storeId]);
                $store = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($store) {
                    if ((int) ($store['is_approved'] ?? 0) === 1) {
                        fate_store_recommend_reward_revert($pdo, $storeId, fate_store_listing_kind_from_row($store));
                    }
                    // Delete cover photo
                    if (!empty($store['cover_photo_path'])) {
                        $coverFile = dirname(__DIR__) . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $store['cover_photo_path']);
                        if (is_file($coverFile)) {
                            @unlink($coverFile);
                        }
                    }
                    // Delete interior photos
                    if (!empty($store['photos_json'])) {
                        $photos = json_decode($store['photos_json'], true);
                        if (is_array($photos)) {
                            foreach ($photos as $ph) {
                                if (!empty($ph['path'])) {
                                    $photoFile = dirname(__DIR__) . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $ph['path']);
                                    if (is_file($photoFile)) {
                                        @unlink($photoFile);
                                    }
                                }
                            }
                        }
                    }
                }

                // Delete store snapshot row
                $stmt = $pdo->prepare("DELETE FROM spa_store_snapshots WHERE spa_store_id = ? AND source_type = 'manual'");
                $stmt->execute([$storeId]);
                $flashOk = '已拒絕並刪除該推薦店家及上傳的圖片檔案。';
            } catch (Throwable $e) {
                $flashErr = '拒絕/刪除失敗：' . $e->getMessage();
            }
        }
    }
}

// Filters & Pagination
$page = isset($_GET['page']) ? max(1, (int) $_GET['page']) : 1;
$perPage = 20;
$offset = ($page - 1) * $perPage;

$statusFilter = isset($_GET['status']) ? strtolower(trim((string) $_GET['status'])) : '';
if (!in_array($statusFilter, ['pending', 'approved'], true)) {
    $statusFilter = '';
}

$whereClause = "WHERE s.source_type = 'manual'";
$params = [];

if ($statusFilter === 'pending') {
    $whereClause .= " AND s.is_approved = 0";
} elseif ($statusFilter === 'approved') {
    $whereClause .= " AND s.is_approved = 1";
}

$total = 0;
$pages = 1;
$storesList = [];

if ($pdo instanceof PDO) {
    try {
        // Count
        $countStmt = $pdo->prepare("SELECT COUNT(*) FROM spa_store_snapshots s $whereClause");
        $countStmt->execute($params);
        $total = (int) $countStmt->fetchColumn();
        $pages = max(1, (int) ceil($total / $perPage));
        if ($page > $pages) {
            $page = $pages;
        }

        // Query
        $dbEsc = str_replace('`', '``', FATE_MEMBER_DATABASE);
        $tblEsc = str_replace('`', '``', FATE_MEMBER_TABLE);
        $selectSql = "SELECT s.spa_store_id, s.store_name, s.city_name, s.district_name, s.street_address,
                             s.display_address, s.payload_json, s.phone, s.mobile, s.line, s.wechat,
                             s.cover_photo_path, s.is_approved, s.synced_at, s.created_member_id,
                             m.display_name AS member_display_name, m.username AS member_username
                      FROM spa_store_snapshots s
                      LEFT JOIN `$dbEsc`.`$tblEsc` m ON s.created_member_id = m.id
                      $whereClause 
                      ORDER BY s.is_approved ASC, s.synced_at DESC 
                      LIMIT $perPage OFFSET $offset";
        $selectStmt = $pdo->prepare($selectSql);
        $selectStmt->execute($params);
        $storesList = $selectStmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        $dbErr = $e->getMessage();
    }
}

$csrf = fate_admin_csrf_token();
$hasActiveFilters = $statusFilter !== '';

$buildListUrl = static function (int $p, ?array $filterOverrides = null) use ($statusFilter): string {
    $sf = $statusFilter;
    if (is_array($filterOverrides) && array_key_exists('status', $filterOverrides)) {
        $sf = (string) $filterOverrides['status'];
    }
    
    $qs = ['page' => (string) $p];
    if ($sf !== '') {
        $qs['status'] = $sf;
    }
    
    return 'approve_stores.php?' . http_build_query($qs);
};

fate_admin_layout_start(['page' => '審核推薦店家', 'active' => 'approve_stores']);
?>

<header class="page-head page-head--compact">
    <h1 class="page-title">審核推薦店家</h1>
    <p class="sub">審核會員提交的定點店家與非定點服務。核准後即公開展示於對應首頁分類，並依獎勵設定發放 <?= $ncoinNameEsc ?>。</p>
</header>

<?php if ($flashOk !== null): ?>
    <div class="msg ok"><?= htmlspecialchars($flashOk, ENT_QUOTES, 'UTF-8') ?></div>
<?php endif; ?>
<?php if ($flashErr !== null): ?>
    <div class="msg bad"><?= htmlspecialchars($flashErr, ENT_QUOTES, 'UTF-8') ?></div>
<?php endif; ?>

<?php if ($dbErr !== null || !$pdo instanceof PDO): ?>
    <div class="msg bad">無法連線資料庫<?= $dbErr !== null ? '：<code>' . htmlspecialchars($dbErr, ENT_QUOTES, 'UTF-8') . '</code>' : '' ?>。</div>
<?php else: ?>

    <nav class="member-quick-filters" aria-label="快速篩選">
        <a class="member-quick-filters__chip<?= $statusFilter === 'pending' ? ' is-active' : '' ?>"
           href="<?= htmlspecialchars($buildListUrl(1, ['status' => 'pending']), ENT_QUOTES, 'UTF-8') ?>">
            待審核
        </a>
        <a class="member-quick-filters__chip<?= $statusFilter === 'approved' ? ' is-active' : '' ?>"
           href="<?= htmlspecialchars($buildListUrl(1, ['status' => 'approved']), ENT_QUOTES, 'UTF-8') ?>">
            已通過
        </a>
        <a class="member-quick-filters__chip<?= !$hasActiveFilters ? ' is-active' : '' ?>"
           href="<?= htmlspecialchars($buildListUrl(1, ['status' => '']), ENT_QUOTES, 'UTF-8') ?>">
            全部推薦
        </a>
    </nav>

    <p class="sub member-list-meta">
        共 <strong><?= htmlspecialchars(number_format($total), ENT_QUOTES, 'UTF-8') ?></strong> 筆
        <?php if ($pages > 1): ?>
            · 第 <?= (int) $page ?> / <?= (int) $pages ?> 頁
        <?php endif; ?>
    </p>

    <?php if (empty($storesList)): ?>
        <div class="msg warn">沒有符合條件的推薦店家。</div>
    <?php else: ?>
        <div class="table-wrap">
            <table class="table table--members">
                <thead>
                    <tr>
                        <th scope="col" style="width: 80px;">圖片</th>
                        <th scope="col" style="width: 100px;">ID</th>
                        <th scope="col">店名</th>
                        <th scope="col">型態</th>
                        <th scope="col">位置／聯絡</th>
                        <th scope="col">推薦會員</th>
                        <th scope="col">送審時間</th>
                        <th scope="col" style="width: 100px;">狀態</th>
                        <th scope="col" style="width: 180px;">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($storesList as $store):
                        $imgUrl = '../' . htmlspecialchars($store['cover_photo_path'], ENT_QUOTES, 'UTF-8');
                        $isApproved = (int)$store['is_approved'] === 1;
                        $storeId = (int)$store['spa_store_id'];
                        $listingKind = fate_store_listing_kind_from_row($store);
                        $listingLabel = fate_store_listing_tab_label($listingKind);
                        $locationText = fate_store_listing_location_text($store);
                        $contactBits = [];
                        foreach (['phone', 'mobile'] as $ck) {
                            $cv = trim((string) ($store[$ck] ?? ''));
                            if ($cv !== '') {
                                $contactBits[] = $cv;
                            }
                        }
                        if (trim((string) ($store['line'] ?? '')) !== '') {
                            $contactBits[] = 'LINE';
                        }
                        if (trim((string) ($store['wechat'] ?? '')) !== '') {
                            $contactBits[] = 'WeChat';
                        }
                    ?>
                        <tr class="member-row<?= !$isApproved ? ' member-row--pending' : '' ?>">
                            <td>
                                <img src="<?= $imgUrl ?>" alt="Cover" style="width: 64px; height: 48px; object-fit: cover; border-radius: 4px; border: 1px solid var(--line);">
                            </td>
                            <td class="col-id"><?= $storeId ?></td>
                            <td>
                                <a href="../store.php?id=<?= $storeId ?>" target="_blank" style="color: var(--accent-color, #ffaa00); text-decoration: underline; font-weight: bold;">
                                    <?= htmlspecialchars($store['store_name'], ENT_QUOTES, 'UTF-8') ?>
                                </a>
                            </td>
                            <td>
                                <?php if ($listingKind === FATE_STORE_LISTING_MOBILE): ?>
                                <span class="badge badge--admin" style="background:#335588;color:white;">
                                    <?= htmlspecialchars($listingLabel, ENT_QUOTES, 'UTF-8') ?>
                                </span>
                                <?php else: ?>
                                <span style="color:var(--muted);font-size:0.85rem;"><?= htmlspecialchars($listingLabel, ENT_QUOTES, 'UTF-8') ?></span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div><?= htmlspecialchars($locationText, ENT_QUOTES, 'UTF-8') ?></div>
                                <?php if ($contactBits !== []): ?>
                                    <div style="font-size:0.8rem;color:var(--muted);margin-top:0.25rem;">
                                        聯絡：<?= htmlspecialchars(implode(' · ', $contactBits), ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($store['created_member_id']): ?>
                                    <?= htmlspecialchars($store['member_display_name'] ?? '', ENT_QUOTES, 'UTF-8') ?> 
                                    <span style="font-size: 0.8rem; color: var(--muted);">(@<?= htmlspecialchars($store['member_username'] ?? '', ENT_QUOTES, 'UTF-8') ?>)</span>
                                <?php else: ?>
                                    <span style="color: var(--muted);">未知</span>
                                <?php endif; ?>
                            </td>
                            <td class="col-time"><?= htmlspecialchars(substr($store['synced_at'], 0, 16), ENT_QUOTES, 'UTF-8') ?></td>
                            <td>
                                <?php if ($isApproved): ?>
                                    <span class="badge badge--admin" style="background-color: #008833; color: white;">已核准</span>
                                <?php else: ?>
                                    <span class="badge badge--warn" style="background-color: #bb8800; color: white;">待審核</span>
                                <?php endif; ?>
                            </td>
                            <td class="col-actions">
                                <div class="member-action-btns">
                                    <?php if (!$isApproved): ?>
                                        <form method="post" action="" style="display: inline;" onsubmit="return confirm('確定要通過該推薦店家嗎？');">
                                            <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                            <input type="hidden" name="action" value="approve">
                                            <input type="hidden" name="store_id" value="<?= $storeId ?>">
                                            <button type="submit" class="btn btn--sm btn--approve" style="background: #008833; border: none; color: white; cursor: pointer; padding: 4px 8px; border-radius: 4px;">核准</button>
                                        </form>
                                    <?php endif; ?>
                                    <form method="post" action="" style="display: inline;" onsubmit="return confirm('確定要拒絕並刪除該推薦店家嗎？此操作不可逆。');">
                                        <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                        <input type="hidden" name="action" value="reject">
                                        <input type="hidden" name="store_id" value="<?= $storeId ?>">
                                        <button type="submit" class="btn btn--sm btn--ghost" style="border: 1px solid #ff3333; color: #ff3333; cursor: pointer; padding: 4px 8px; border-radius: 4px; background: transparent;">拒絕</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <?php if ($pages > 1): ?>
            <nav class="pagination" aria-label="推薦店家列表分頁">
                <?php if ($page > 1): ?>
                    <a class="btn btn--ghost" href="<?= htmlspecialchars($buildListUrl($page - 1), ENT_QUOTES, 'UTF-8') ?>">上一頁</a>
                <?php endif; ?>
                <?php if ($page < $pages): ?>
                    <a class="btn btn--ghost" href="<?= htmlspecialchars($buildListUrl($page + 1), ENT_QUOTES, 'UTF-8') ?>">下一頁</a>
                <?php endif; ?>
            </nav>
        <?php endif; ?>
    <?php endif; ?>

<?php endif; ?>

<?php
fate_admin_layout_end();
