<?php
// PATCH DONI: API Running Text lokal tanpa Firebase
// Letakkan file ini di: public_html/runingtex/apiruning.php
// Setting otomatis disimpan ke: public_html/runingtex/runing-setting.json

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

$settingFile = __DIR__ . '/runing-setting.json';

$defaultSetting = [
    "aktif" => false,
    "text1" => "Selamat datang di Pandawa Digital",
    "text2" => "",
    "baris" => 1,
    "model" => "biasa",
    "warnaText" => "#ffffff",
    "warnaPelangi" => false,
    "backgroundTransparan" => false,
    "warnaBackground" => "#0f172a",
    "animasi" => "left",
    "kecepatan" => 14,
    "jeda" => 1,
    "updatedAt" => null
];

function send_json($data, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function bool_value($value) {
    if (is_bool($value)) return $value;
    if (is_numeric($value)) return ((int)$value) === 1;
    if (is_string($value)) {
        $value = strtolower(trim($value));
        return in_array($value, ['true', '1', 'yes', 'on'], true);
    }
    return false;
}

function clean_hex_color($value, $fallback) {
    $value = trim((string)$value);
    if (preg_match('/^#[0-9a-fA-F]{6}$/', $value)) {
        return $value;
    }
    if (preg_match('/^#[0-9a-fA-F]{3}$/', $value)) {
        return $value;
    }
    return $fallback;
}

function clean_text($value, $maxLength = 300) {
    $value = (string)$value;
    $value = strip_tags($value);
    $value = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $value);
    $value = trim($value);

    if (function_exists('mb_substr')) {
        return mb_substr($value, 0, $maxLength, 'UTF-8');
    }

    return substr($value, 0, $maxLength);
}

function normalize_setting($input, $defaultSetting) {
    $allowedModel = ['biasa', 'led'];
    $allowedAnimasi = ['left', 'right', 'bounce', 'blink', 'wave', 'bus', 'neon', 'fade'];

    $setting = $defaultSetting;

    $setting['aktif'] = bool_value($input['aktif'] ?? $defaultSetting['aktif']);

    $setting['text1'] = clean_text(
        $input['text1'] ?? $input['isiText'] ?? $input['text'] ?? $defaultSetting['text1'],
        300
    );

    $setting['text2'] = clean_text(
        $input['text2'] ?? $defaultSetting['text2'],
        300
    );

    $baris = (int)($input['baris'] ?? $defaultSetting['baris']);
    $setting['baris'] = ($baris === 2) ? 2 : 1;

    $model = strtolower(trim((string)($input['model'] ?? $defaultSetting['model'])));
    $setting['model'] = in_array($model, $allowedModel, true) ? $model : 'biasa';

    $setting['warnaText'] = clean_hex_color(
        $input['warnaText'] ?? $defaultSetting['warnaText'],
        $defaultSetting['warnaText']
    );

    $setting['warnaPelangi'] = bool_value($input['warnaPelangi'] ?? $defaultSetting['warnaPelangi']);

    $setting['backgroundTransparan'] = bool_value(
        $input['backgroundTransparan'] ?? $defaultSetting['backgroundTransparan']
    );

    $setting['warnaBackground'] = clean_hex_color(
        $input['warnaBackground'] ?? $defaultSetting['warnaBackground'],
        $defaultSetting['warnaBackground']
    );

    $animasi = strtolower(trim((string)($input['animasi'] ?? $defaultSetting['animasi'])));
    $setting['animasi'] = in_array($animasi, $allowedAnimasi, true) ? $animasi : 'left';

    $kecepatan = (float)($input['kecepatan'] ?? $defaultSetting['kecepatan']);
    if ($kecepatan < 3) $kecepatan = 3;
    if ($kecepatan > 60) $kecepatan = 60;
    $setting['kecepatan'] = $kecepatan;

    $jeda = (float)($input['jeda'] ?? $defaultSetting['jeda']);
    if ($jeda < 0) $jeda = 0;
    if ($jeda > 20) $jeda = 20;
    $setting['jeda'] = $jeda;

    $setting['updatedAt'] = date('Y-m-d H:i:s');

    return $setting;
}

function ensure_setting_file($settingFile, $defaultSetting) {
    if (!is_dir(dirname($settingFile))) {
        if (!mkdir(dirname($settingFile), 0755, true)) {
            send_json([
                "success" => false,
                "message" => "Folder runingtex tidak dapat dibuat."
            ], 500);
        }
    }

    if (!file_exists($settingFile)) {
        $initial = $defaultSetting;
        $initial['updatedAt'] = date('Y-m-d H:i:s');

        $saved = file_put_contents(
            $settingFile,
            json_encode($initial, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            LOCK_EX
        );

        if ($saved === false) {
            send_json([
                "success" => false,
                "message" => "File setting JSON tidak dapat dibuat."
            ], 500);
        }

        @chmod($settingFile, 0644);
    }
}

$action = $_GET['action'] ?? 'get';
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

if ($method === 'OPTIONS') {
    send_json(["success" => true]);
}

try {
    ensure_setting_file($settingFile, $defaultSetting);

    if ($action === 'get') {
        $raw = file_get_contents($settingFile);
        $data = json_decode($raw, true);

        if (!is_array($data)) {
            $data = $defaultSetting;
        }

        $data = array_merge($defaultSetting, $data);

        send_json([
            "success" => true,
            "data" => $data
        ]);
    }

    if ($action === 'save') {
        if ($method !== 'POST') {
            send_json([
                "success" => false,
                "message" => "Gunakan method POST untuk menyimpan setting."
            ], 405);
        }

        $rawInput = file_get_contents('php://input');
        $input = json_decode($rawInput, true);

        if (!is_array($input)) {
            $input = $_POST;
        }

        if (!is_array($input)) {
            send_json([
                "success" => false,
                "message" => "Data setting tidak valid."
            ], 400);
        }

        $setting = normalize_setting($input, $defaultSetting);

        $saved = file_put_contents(
            $settingFile,
            json_encode($setting, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            LOCK_EX
        );

        if ($saved === false) {
            send_json([
                "success" => false,
                "message" => "Gagal menyimpan setting ke file JSON. Periksa permission folder runingtex."
            ], 500);
        }

        @chmod($settingFile, 0644);

        send_json([
            "success" => true,
            "message" => "Setting Running Text berhasil disimpan.",
            "data" => $setting
        ]);
    }

    send_json([
        "success" => false,
        "message" => "Action tidak dikenal."
    ], 400);

} catch (Throwable $e) {
    send_json([
        "success" => false,
        "message" => "Terjadi error: " . $e->getMessage()
    ], 500);
}