<?php

declare(strict_types=1);

require_once __DIR__ . DIRECTORY_SEPARATOR . 'auth.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_masseur_image.php';

fate_admin_require_login_api();

$csrf = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
if (!fate_admin_csrf_check($csrf)) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => '工作階段逾期，請重新整理。'], JSON_UNESCAPED_UNICODE);
    exit;
}

$action = isset($_POST['action']) && is_string($_POST['action']) ? trim($_POST['action']) : '';
$gender = isset($_POST['gender']) && is_string($_POST['gender']) ? $_POST['gender'] : '';

if ($action === 'save_default_avatar') {
    $data = isset($_POST['photo_data']) && is_string($_POST['photo_data']) ? $_POST['photo_data'] : '';
    $r = fate_masseur_save_default_avatar($gender, $data);
    if (!$r['ok']) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => $r['error'] ?? '無法儲存預設頭像。'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $rel = (string) ($r['rel'] ?? '');
    $g = fate_masseur_default_avatar_gender_norm($gender);
    $label = $g === 'male' ? '男' : ($g === 'female' ? '女' : '其他');
    echo json_encode([
        'ok' => true,
        'rel' => $rel,
        'preview_url' => fate_masseur_photo_admin_url($rel !== '' ? $rel : null, true),
        'message' => '已儲存' . $label . '技師預設頭像。',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'clear_default_avatar') {
    $r = fate_masseur_clear_default_avatar($gender);
    if (!$r['ok']) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => $r['error'] ?? '無法清除預設頭像。'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $g = fate_masseur_default_avatar_gender_norm($gender);
    $label = $g === 'male' ? '男' : ($g === 'female' ? '女' : '其他');
    echo json_encode([
        'ok' => true,
        'preview_url' => null,
        'message' => '已清除' . $label . '技師預設頭像。',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

http_response_code(400);
echo json_encode(['ok' => false, 'error' => '未知操作。'], JSON_UNESCAPED_UNICODE);
