<?php
require __DIR__ . '/lib/bootstrap.php';

global $config;
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';
$secret = $config['stripe']['webhook_secret'];

if (!verify_stripe_signature($payload, $signature, $secret)) {
    json_response(['ok' => false, 'error' => 'Invalid Stripe signature'], 400);
}

$event = json_decode($payload, true);
if (!is_array($event)) {
    json_response(['ok' => false, 'error' => 'Invalid JSON'], 400);
}

if (($event['type'] ?? '') === 'checkout.session.completed') {
    $session = $event['data']['object'] ?? [];
    $mac = $session['client_reference_id'] ?? ($session['metadata']['mac'] ?? '');

    if ($mac !== '') {
        $device = get_or_create_device($mac);
        $paidDays = (int) $config['app']['paid_days'];
        db()->prepare(
            'UPDATE devices
             SET status = ?, active_until = DATE_ADD(IF(active_until IS NULL OR active_until < NOW(), NOW(), active_until), INTERVAL ? DAY)
             WHERE id = ?'
        )->execute(['active', $paidDays, (int) $device['id']]);

        db()->prepare(
            'INSERT IGNORE INTO payments (device_id, stripe_session_id, amount_total, currency, status, payload)
             VALUES (?, ?, ?, ?, ?, ?)'
        )->execute([
            (int) $device['id'],
            $session['id'] ?? '',
            $session['amount_total'] ?? null,
            $session['currency'] ?? null,
            $session['payment_status'] ?? 'completed',
            $payload,
        ]);
    }
}

json_response(['ok' => true]);

function verify_stripe_signature(string $payload, string $header, string $secret): bool
{
    if ($secret === '' || strpos($secret, 'CHANGE_ME') !== false) {
        return false;
    }

    $timestamp = '';
    $signatures = [];
    foreach (explode(',', $header) as $part) {
        [$key, $value] = array_pad(explode('=', $part, 2), 2, '');
        if ($key === 't') {
            $timestamp = $value;
        } elseif ($key === 'v1') {
            $signatures[] = $value;
        }
    }

    if ($timestamp === '' || !$signatures) {
        return false;
    }

    $signedPayload = $timestamp . '.' . $payload;
    $expected = hash_hmac('sha256', $signedPayload, $secret);

    foreach ($signatures as $signature) {
        if (hash_equals($expected, $signature)) {
            return true;
        }
    }

    return false;
}
