<?php

require_once __DIR__ . '/../common/auth.php';
require_once __DIR__ . '/../common/ha.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

$config = custom_config();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = custom_read_request_data();
    $action = $data['action'] ?? 'login';

    if ($action === 'login') {
        $password = (string)($data['password'] ?? '');
        if (custom_verify_password($password)) {
            custom_issue_auth_cookie();
            custom_json(['result' => 'ok']);
        }

        custom_json(['result' => 'fail'], 401);
    }

    if ($action === 'logout') {
        custom_clear_auth_cookie();
        custom_json(['result' => 'ok']);
    }

    if ($action === 'changePassword') {
        $current = (string)($data['currentPassword'] ?? '');
        $next = (string)($data['newPassword'] ?? '');

        if (!custom_verify_password($current)) {
            custom_json(['result' => 'fail', 'message' => 'current_password_invalid'], 401);
        }

        if (mb_strlen($next) < 4) {
            custom_json(['result' => 'fail', 'message' => 'password_too_short'], 422);
        }

        if (!custom_save_password_hash(password_hash($next, PASSWORD_DEFAULT))) {
            custom_json(['result' => 'fail', 'message' => 'password_save_failed'], 500);
        }

        custom_issue_auth_cookie();
        custom_json(['result' => 'ok']);
    }

    if ($action === 'poke') {
        $sender = trim((string)($data['sender'] ?? ''));
        $message = trim((string)($data['message'] ?? ''));
        $ok = custom_ha_webhook('poke', [
            'sender' => $sender !== '' ? $sender : '익명',
            'message' => $message,
        ]);

        custom_json(['result' => $ok ? 'ok' : 'fail'], $ok ? 200 : 502);
    }

    custom_json(['error' => 'not_found'], 404);
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if (isset($_GET['session'])) {
        custom_json(['authenticated' => custom_has_auth_cookie()]);
    }

    if (isset($_GET['failMessages'])) {
        custom_json([
            'failMessages' => [
                '비밀번호가 틀립니다.',
            ],
        ]);
    }

    if (isset($_GET['pokeCount'])) {
        $state = custom_ha_state('main', $config['entities']['poke_count']);
        $count = $state['state'] ?? null;

        if ($count === null) {
            custom_json(['ok' => false, 'error' => 'failed_to_fetch_from_ha'], 502);
        }

        custom_json([
            'ok' => true,
            'count' => is_numeric($count) ? (int)$count : $count,
        ]);
    }

    custom_json(['error' => 'not_found'], 404);
}

custom_json(['error' => 'method_not_allowed'], 405);
