<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit(); }

define('SCORES_FILE', __DIR__ . '/scores.json');
define('LOCK_FILE',   __DIR__ . '/scores.lock');

// GET — baca semua skor
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if (!file_exists(SCORES_FILE)) {
        echo json_encode(['scores' => new stdClass(), 'updated_at' => null, 'updated_by' => null]);
    } else {
        echo file_get_contents(SCORES_FILE);
    }
    exit();
}

// POST — simpan / padam / reset skor
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $raw  = file_get_contents('php://input');
    $data = json_decode($raw, true);

    $lock = fopen(LOCK_FILE, 'w');
    flock($lock, LOCK_EX);

    $current = file_exists(SCORES_FILE)
        ? (json_decode(file_get_contents(SCORES_FILE), true) ?? [])
        : [];
    $scores = $current['scores'] ?? [];

    // RESET semua
    if (!empty($data['reset'])) {
        $scores = [];
    }
    // PADAM satu match
    elseif (!empty($data['delete'])) {
        $id = (string)$data['id'];
        unset($scores[$id]);
    }
    // SIMPAN satu match
    elseif (isset($data['id']) && isset($data['hg']) && isset($data['ag'])) {
        $id = (string)$data['id'];
        $scores[$id] = [
            'hg' => (int)$data['hg'],
            'ag' => (int)$data['ag'],
            'by' => htmlspecialchars($data['updated_by'] ?? 'Admin', ENT_QUOTES),
            'at' => time()
        ];
    } else {
        flock($lock, LOCK_UN);
        fclose($lock);
        http_response_code(400);
        echo json_encode(['error' => 'Data tidak lengkap']);
        exit();
    }

    $save = [
        'scores'     => $scores,
        'updated_at' => time(),
        'updated_by' => htmlspecialchars($data['updated_by'] ?? 'Admin', ENT_QUOTES)
    ];

    file_put_contents(SCORES_FILE, json_encode($save, JSON_PRETTY_PRINT));
    flock($lock, LOCK_UN);
    fclose($lock);

    echo json_encode(['ok' => true, 'updated_at' => $save['updated_at']]);
    exit();
}

http_response_code(405);
echo json_encode(['error' => 'Method tidak dibenarkan']);
