<?php
// ====== Simple balance store (file-based) ======
// If you want to disable the key check, set APP_KEY to an empty string.
const APP_KEY = 'sadsad2e2123asd24a';        // <— must match the key in transfer-3.html
const STORE   = __DIR__ . '/balance.json';
const START   = 970491.52;                   // initial balance if file not found

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

// ---- tiny helper ----
function read_balance() {
    if (!file_exists(STORE)) {
        file_put_contents(STORE, json_encode(['balance' => START], JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE));
        return START;
    }
    $json = json_decode(file_get_contents(STORE), true);
    return isset($json['balance']) ? floatval($json['balance']) : START;
}
function write_balance($val) {
    file_put_contents(STORE, json_encode(['balance' => round($val, 2)], JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|LOCK_EX));
}

// ---- app key check (only for POST). GET is public for reading. ----
if ($_SERVER['REQUEST_METHOD'] === 'POST' && APP_KEY !== '') {
    $key = $_SERVER['HTTP_X_APP_KEY'] ?? $_SERVER['HTTP_X_APPKEY'] ?? ($_POST['api_key'] ?? '');
    if ($key !== APP_KEY) {
        http_response_code(401);
        echo json_encode(['ok'=>false,'error'=>'Unauthorized']);
        exit;
    }
}

// ---- routes ----
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    echo json_encode(['ok'=>true, 'balance'=>read_balance()]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $raw = file_get_contents('php://input');
    $data = json_decode($raw, true);
    if (!is_array($data)) $data = $_POST;

    $op = $data['op'] ?? '';
    $amt = isset($data['amount']) ? floatval($data['amount']) : null;

    $bal = read_balance();

    if ($op === 'debit') {
        if ($amt === null || $amt <= 0) {
            http_response_code(400);
            echo json_encode(['ok'=>false,'error'=>'BAD_AMOUNT']);
            exit;
        }
        if ($amt > $bal) {
            http_response_code(400);
            echo json_encode(['ok'=>false,'error'=>'INSUFFICIENT_FUNDS','balance'=>$bal]);
            exit;
        }
        $bal = round($bal - $amt, 2);
        write_balance($bal);
        echo json_encode(['ok'=>true,'balance'=>$bal]);
        exit;
    }

    if ($op === 'set') {
        if ($amt === null) {
            http_response_code(400);
            echo json_encode(['ok'=>false,'error'=>'BAD_AMOUNT']);
            exit;
        }
        write_balance($amt);
        echo json_encode(['ok'=>true,'balance'=>$amt]);
        exit;
    }

    http_response_code(400);
    echo json_encode(['ok'=>false,'error'=>'BAD_OP']);
    exit;
}

http_response_code(405);
echo json_encode(['ok'=>false,'error'=>'METHOD_NOT_ALLOWED']);
