<?php

declare(strict_types=1);

/**
 * 店家文字評論：發表。
 */

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_session.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_member_auth.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_store_reviews.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_plugins.php';

fate_public_session_start();

function fate_store_review_back(int $storeId, string $okMsg = '', string $badMsg = ''): void
{
    if ($okMsg !== '') {
        $_SESSION['fate_store_review_flash_ok'] = $okMsg;
    }
    if ($badMsg !== '') {
        $_SESSION['fate_store_review_flash_bad'] = $badMsg;
    }
    header('Location: ../store.php?id=' . $storeId . '#store-reviews', true, 303);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../index.php', true, 302);
    exit;
}

$storeId = isset($_POST['store_id']) ? (int) $_POST['store_id'] : 0;
$csrf = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
if (!fate_public_member_csrf_check($csrf)) {
    fate_store_review_back($storeId, '', '工作階段逾期，請重新整理。');
}

if (fate_store_forum_plugin_active()) {
    fate_store_review_back($storeId, '', '討論區已啟用，請改至店家討論串發文。');
}

if (!fate_store_reviews_enabled()) {
    fate_store_review_back($storeId, '', '本站暫停店家文字評論。');
}

$pdo = 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) {
    $pdo = null;
}
if (!$pdo instanceof PDO) {
    fate_store_review_back($storeId, '', '資料庫連線失敗。');
}

$member = fate_public_member_current();
if ($member === null) {
    fate_store_review_back($storeId, '', '請先登入。');
}
$memberId = (int) ($member['id'] ?? 0);
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_store_masseurs.php';
fate_public_member_ensure_admin_flag($pdo);

if (!fate_public_member_can_interact($pdo)) {
    fate_store_review_back($storeId, '', fate_public_member_interact_denied_message($pdo));
}

$body = isset($_POST['body']) && is_string($_POST['body']) ? $_POST['body'] : '';
$username = (string) ($member['username'] ?? '');
$r = fate_store_review_create($pdo, $storeId, $memberId, $body, $username);
if ($r['ok']) {
    fate_store_review_back($storeId, '店家評論已送出，感謝您的分享！', '');
}
fate_store_review_back($storeId, '', $r['error'] ?? '評論失敗。');
