<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

// ── CONFIG ──
define('SOUNDS_DIR',   __DIR__ . '/sounds/');
define('DATA_FILE',    __DIR__ . '/sounds_data.json');
define('HISTORY_FILE', __DIR__ . '/sounds_history.json');
define('MAX_HISTORY',  100);
define('TWITCH_CLIENT_ID', '2x0r4yvw01qy0bm48icvxnspyd36vf');
$ALLOWED_USERS = ['sooow_19', 'frizzz_tv', '0wlsoo', 'tiazelite'];

// Crée le dossier sons si besoin
if (!is_dir(SOUNDS_DIR)) mkdir(SOUNDS_DIR, 0755, true);

// ── HELPERS ──
function loadData() {
    if (!file_exists(DATA_FILE)) return ['sounds' => []];
    return json_decode(file_get_contents(DATA_FILE), true) ?: ['sounds' => []];
}
function saveData($data) {
    file_put_contents(DATA_FILE, json_encode($data, JSON_PRETTY_PRINT));
}
function loadHistory() {
    if (!file_exists(HISTORY_FILE)) return [];
    return json_decode(file_get_contents(HISTORY_FILE), true) ?: [];
}
function saveHistory($history) {
    file_put_contents(HISTORY_FILE, json_encode($history));
}
function authCheck() {
    global $ALLOWED_USERS;
    $token     = $_GET['twitch_token'] ?? $_POST['twitch_token'] ?? '';
    $client_id = $_GET['twitch_client_id'] ?? $_POST['twitch_client_id'] ?? TWITCH_CLIENT_ID;

    if (!$token) {
        // Fallback : accepte TWITCH_AUTH pour list_all depuis l'admin
        $pwd = $_GET['pwd'] ?? $_POST['pwd'] ?? '';
        if ($pwd === 'TWITCH_AUTH') return; // autorisé via session côté client
        http_response_code(403);
        echo json_encode(['error' => 'Token manquant']);
        exit;
    }

    // Vérifie le token auprès de Twitch
    $ch = curl_init('https://api.twitch.tv/helix/users');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer $token",
            "Client-Id: $client_id"
        ]
    ]);
    $res  = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($code !== 200) {
        http_response_code(403);
        echo json_encode(['error' => 'Token invalide']);
        exit;
    }

    $data  = json_decode($res, true);
    $login = strtolower($data['data'][0]['login'] ?? '');

    if (!in_array($login, $ALLOWED_USERS)) {
        http_response_code(403);
        echo json_encode(['error' => 'Utilisateur non autorisé']);
        exit;
    }
}

$action = $_GET['action'] ?? $_POST['action'] ?? 'list';

// ── ACTIONS PUBLIQUES ──

// Lister TOUS les sons (admin)
if ($action === 'list_all') {
    authCheck();
    $data = loadData();
    echo json_encode(['sounds' => $data['sounds']]);
    exit;
}

// Lister les sons actifs (pour OBS soundboard)
if ($action === 'list') {
    $data = loadData();
    $active = array_values(array_filter($data['sounds'], fn($s) => $s['active']));
    echo json_encode(['sounds' => $active]);
    exit;
}

// Déclencher un son via nom de rédemption
if ($action === 'trigger') {
    $rewardName = strtolower($_GET['reward'] ?? '');
    $user       = $_GET['user'] ?? 'Viewer';
    $data       = loadData();

    $matched = null;
    foreach ($data['sounds'] as $s) {
        if ($s['active'] && strtolower($s['reward_name']) === $rewardName) {
            $matched = $s;
            break;
        }
    }

    if (!$matched) {
        echo json_encode(['found' => false]);
        exit;
    }

    // Enregistre dans l'historique
    $history = loadHistory();
    array_unshift($history, [
        'sound'   => $matched['name'],
        'user'    => $user,
        'time'    => date('Y-m-d H:i:s'),
        'ts'      => time()
    ]);
    if (count($history) > MAX_HISTORY) $history = array_slice($history, 0, MAX_HISTORY);
    saveHistory($history);

    echo json_encode(['found' => true, 'sound' => $matched]);
    exit;
}

// ── ACTIONS ADMIN (protégées) ──

// Upload un son
if ($action === 'upload') {
    authCheck();
    if (!isset($_FILES['sound'])) {
        echo json_encode(['error' => 'Aucun fichier']); exit;
    }
    $file     = $_FILES['sound'];
    $ext      = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $allowed  = ['mp3','wav','ogg','m4a'];
    if (!in_array($ext, $allowed)) {
        echo json_encode(['error' => 'Format non supporté (mp3, wav, ogg, m4a)']); exit;
    }
    $filename = uniqid() . '_' . preg_replace('/[^a-z0-9._-]/i', '_', $file['name']);
    $dest     = SOUNDS_DIR . $filename;
    if (!move_uploaded_file($file['tmp_name'], $dest)) {
        echo json_encode(['error' => 'Erreur upload']); exit;
    }

    $data = loadData();
    $id   = uniqid('s_');
    $data['sounds'][] = [
        'id'          => $id,
        'name'        => pathinfo($file['name'], PATHINFO_FILENAME),
        'file'        => $filename,
        'url'         => 'https://tools.sooow.fr/soundboard/sounds/' . $filename,
        'reward_name' => '',
        'active'      => false,
        'added'       => date('Y-m-d H:i:s')
    ];
    saveData($data);
    echo json_encode(['success' => true, 'id' => $id]);
    exit;
}

// Toggle activer/désactiver
if ($action === 'toggle') {
    authCheck();
    $id   = $_POST['id'] ?? '';
    $data = loadData();
    foreach ($data['sounds'] as &$s) {
        if ($s['id'] === $id) {
            $s['active'] = !$s['active'];
            saveData($data);
            echo json_encode(['success' => true, 'active' => $s['active']]);
            exit;
        }
    }
    echo json_encode(['error' => 'Son introuvable']);
    exit;
}

// Modifier le nom de rédemption
if ($action === 'set_reward') {
    authCheck();
    $id     = $_POST['id'] ?? '';
    $reward = $_POST['reward'] ?? '';
    $name   = $_POST['name'] ?? '';
    $data   = loadData();
    foreach ($data['sounds'] as &$s) {
        if ($s['id'] === $id) {
            if ($reward !== '') $s['reward_name'] = $reward;
            if ($name   !== '') $s['name']        = $name;
            saveData($data);
            echo json_encode(['success' => true]);
            exit;
        }
    }
    echo json_encode(['error' => 'Son introuvable']);
    exit;
}

// Supprimer un son
if ($action === 'delete') {
    authCheck();
    $id   = $_POST['id'] ?? '';
    $data = loadData();
    foreach ($data['sounds'] as $k => $s) {
        if ($s['id'] === $id) {
            @unlink(SOUNDS_DIR . $s['file']);
            array_splice($data['sounds'], $k, 1);
            saveData($data);
            echo json_encode(['success' => true]);
            exit;
        }
    }
    echo json_encode(['error' => 'Son introuvable']);
    exit;
}

// Historique
if ($action === 'history') {
    authCheck();
    echo json_encode(['history' => loadHistory()]);
    exit;
}

echo json_encode(['error' => 'Action inconnue']);
?>