<?php
require_once __DIR__ . '/api.php';

// Load environment variables
$env = env_load(dirname(__DIR__) . '/.env');
$secret = $env['EVENTSUB_SECRET'] ?? 'change_this_secret';

// Get raw POST body
$raw = file_get_contents('php://input');

// Get Twitch headers
$t = $_SERVER['HTTP_TWITCH_EVENTSUB_MESSAGE_TYPE'] ?? '';
$id = $_SERVER['HTTP_TWITCH_EVENTSUB_MESSAGE_ID'] ?? '';
$ts = $_SERVER['HTTP_TWITCH_EVENTSUB_MESSAGE_TIMESTAMP'] ?? '';
$sig = $_SERVER['HTTP_TWITCH_EVENTSUB_MESSAGE_SIGNATURE'] ?? '';

// Calculate signature
$calc = 'sha256=' . hash_hmac('sha256', $id . $ts . $raw, $secret);

// Verify signature
if (!hash_equals($calc, $sig)) {
	http_response_code(403);
	echo 'bad sig';
	exit;
}

// Decode JSON
$data = json_decode($raw, true);

// Handle webhook verification
if ($t === 'webhook_callback_verification') {
	header('Content-Type: text/plain');
	echo $data['challenge'] ?? '';
	exit;
}

// Handle notification
if ($t === 'notification') {
	$type = $data['subscription']['type'] ?? '';
	$ev = $data['event'] ?? [];

	try {
		$db = new PDO('sqlite:' . dirname(__DIR__) . '/data/app.db');
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		if ($type === 'channel.cheer') {
			$u = strtolower($ev['user_login'] ?? '');
			$n = $ev['user_name'] ?? $u;
			$bits = (int)($ev['bits'] ?? 0);
			$st = $db->prepare('INSERT INTO events(type,user_login,user_name,value,ts) VALUES(?,?,?,?,?)');
			$st->execute(['cheer', $u, $n, $bits, gmdate('c')]);
		}

		if (
			$type === 'channel.subscribe' ||
			$type === 'channel.subscription.message' ||
			$type === 'channel.subscription.gift'
		) {
			$u = strtolower($ev['user_login'] ?? $ev['gifter_login'] ?? '');
			$n = $ev['user_name'] ?? $ev['gifter_name'] ?? $u;
			$val = (int)($ev['tier'] ?? $ev['total'] ?? 1);
			$st = $db->prepare('INSERT INTO events(type,user_login,user_name,value,ts) VALUES(?,?,?,?,?)');
			$st->execute([
				($type === 'channel.subscription.gift' ? 'subgift' : 'sub'),
				$u,
				$n,
				$val,
				gmdate('c')
			]);
		}
	} catch (PDOException $e) {
		error_log('Database error: ' . $e->getMessage());
		http_response_code(500);
		echo 'db error';
		exit;
	}

	echo 'ok';
	exit;
}

echo 'ok';