<?php

declare(strict_types=1);

/**
 * 會員回報店況／技師狀態（歇業、更名、已離店）。
 * 預設以 AJAX（ajax=1）回傳 JSON，不導頁。
 */

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app.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_crowd_reports.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_ncoin_settings.php';

fate_public_session_start();

$wantsJson = fate_crowd_report_wants_json();

function fate_crowd_report_fail(string $message, int $status = 400, array $extra = []): void
{
    global $wantsJson;
    if ($wantsJson) {
        fate_crowd_report_json_send(array_merge(['ok' => false, 'error' => $message], $extra), $status);
    }
    $returnTo = isset($_POST['return_to']) && is_string($_POST['return_to']) ? $_POST['return_to'] : '';
    $returnAnchor = isset($_POST['return_anchor']) && is_string($_POST['return_anchor']) ? $_POST['return_anchor'] : '';
    if ($returnTo === '' && isset($_SERVER['HTTP_REFERER'])) {
        $returnTo = (string) $_SERVER['HTTP_REFERER'];
    }
    $_SESSION['fate_crowd_flash_bad'] = $message;
    [$target] = fate_crowd_report_resolve_redirect_target($returnTo, $returnAnchor);
    header('Location: ' . $target, true, 303);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    fate_crowd_report_fail('無效的請求。', 405);
}

$member = fate_public_member_current();
if ($member === null) {
    if ($wantsJson) {
        [, $loginNext] = fate_crowd_report_resolve_redirect_target(
            isset($_SERVER['HTTP_REFERER']) ? (string) $_SERVER['HTTP_REFERER'] : '',
            ''
        );
        fate_crowd_report_json_send([
            'ok' => false,
            'error' => '請先登入。',
            'need_login' => true,
            'login_url' => '../login.php?next=' . rawurlencode($loginNext),
        ], 401);
    }
    fate_crowd_report_fail('請先登入。', 401, ['need_login' => true]);
}

$tok = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
if (!fate_public_member_csrf_check($tok)) {
    fate_crowd_report_fail('工作階段逾期，請重新整理後再試。', 403);
}

if (!fate_public_member_can_interact($pdo)) {
    fate_crowd_report_fail(fate_public_member_interact_denied_message($pdo), 403);
}

$entityType = isset($_POST['entity_type']) && is_string($_POST['entity_type']) ? trim($_POST['entity_type']) : '';
$entityId = isset($_POST['entity_id']) ? (int) $_POST['entity_id'] : 0;
$reportKey = isset($_POST['report_key']) && is_string($_POST['report_key']) ? trim($_POST['report_key']) : '';

if (!in_array($entityType, [FATE_CROWD_ENTITY_STORE, FATE_CROWD_ENTITY_MASSEUR], true)) {
    fate_crowd_report_fail('無效的回報類型。');
}

$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) {
}

if (!$pdo instanceof PDO) {
    fate_crowd_report_fail('資料庫連線失敗。', 500);
}

$memberId = (int) ($member['id'] ?? 0);
$username = (string) ($member['username'] ?? '');
$r = fate_crowd_report_toggle($pdo, $entityType, $entityId, $reportKey, $memberId, $username);
if (!$r['ok']) {
    fate_crowd_report_fail($r['error'] ?? '回報失敗。');
}

$label = fate_crowd_report_label($entityType, $reportKey);
$msg = !empty($r['picked']) ? '已回報「' . $label . '」。' : '已取消「' . $label . '」回報。';
$rewardAmount = (int) ($r['reward_amount'] ?? 0);
$rewardReverted = (int) ($r['reward_reverted'] ?? 0);
if ($rewardAmount > 0) {
    $msg .= '（+' . $rewardAmount . ' ' . fate_ncoin_display_name() . '）';
} elseif ($rewardReverted > 0) {
    $msg .= '（已扣回 ' . $rewardReverted . ' ' . fate_ncoin_display_name() . '）';
}

$batch = fate_crowd_report_batch_payload($pdo, $entityType, [$entityId], $memberId);
$reports = $batch[$entityId] ?? [];
$totalCount = 0;
foreach ($reports as $row) {
    if (is_array($row)) {
        $totalCount += (int) ($row['count'] ?? 0);
    }
}

if ($wantsJson) {
    fate_crowd_report_json_send([
        'ok' => true,
        'picked' => !empty($r['picked']),
        'member_count' => (int) ($r['member_count'] ?? 0),
        'message' => $msg,
        'report_key' => $reportKey,
        'label' => $label,
        'reports' => $reports,
        'total_count' => $totalCount,
        'reward_amount' => $rewardAmount,
        'reward_reverted' => $rewardReverted,
    ]);
}

$returnTo = isset($_POST['return_to']) && is_string($_POST['return_to']) ? $_POST['return_to'] : '';
$returnAnchor = isset($_POST['return_anchor']) && is_string($_POST['return_anchor']) ? $_POST['return_anchor'] : '';
if ($returnTo === '' && isset($_SERVER['HTTP_REFERER'])) {
    $returnTo = (string) $_SERVER['HTTP_REFERER'];
}
$_SESSION['fate_crowd_flash_ok'] = $msg;
[$target] = fate_crowd_report_resolve_redirect_target($returnTo, $returnAnchor);
header('Location: ' . $target, true, 303);
exit;
