<?php
declare(strict_types=1);

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

require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../../src/mysql.php';

use function App\get_mysql_db;
use function App\get_mysql_env;

$payload = (string)@file_get_contents('php://input');
$sigHeader = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';
$env = get_mysql_env();
$webhookSecret = (string)$env['STRIPE_WEBHOOK_SECRET'];

try {
    if ($webhookSecret !== '') {
        $event = \Stripe\Webhook::constructEvent($payload, $sigHeader, $webhookSecret);
    } else {
        $event = json_decode($payload);
    }
} catch (\UnexpectedValueException $e) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Payload invalido']);
    exit;
} catch (\Stripe\Exception\SignatureVerificationException $e) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Firma invalida']);
    exit;
}

if (!is_object($event) || ($event->type ?? '') !== 'checkout.session.completed') {
    http_response_code(200);
    echo json_encode(['ok' => true, 'message' => 'evento ignorado']);
    exit;
}

$session = $event->data->object ?? null;
$sessionId = $session->id ?? null;
if (!$sessionId) {
    http_response_code(422);
    echo json_encode(['ok' => false, 'error' => 'session_id ausente']);
    exit;
}

$pdo = get_mysql_db();

try {
    $pdo->beginTransaction();

    $find = $pdo->prepare('SELECT id, event_id FROM payments WHERE provider = ? AND provider_ref = ? FOR UPDATE');
    $find->execute(['stripe', $sessionId]);
    $payment = $find->fetch();

    if ($payment) {
        $updPay = $pdo->prepare('UPDATE payments SET status = ?, payload = ?, updated_at = NOW() WHERE id = ?');
        $updPay->execute(['paid', json_encode($session, JSON_UNESCAPED_UNICODE), $payment['id']]);

        $updEvent = $pdo->prepare("UPDATE events SET status = 'active', updated_at = NOW() WHERE id = ? AND status IN ('pending','draft')");
        $updEvent->execute([$payment['event_id']]);

        $log = $pdo->prepare('INSERT INTO event_logs(event_id, log_type, meta, ip, user_agent) VALUES (?, ?, JSON_OBJECT("provider_ref", ?), ?, ?)');
        $log->execute([
            $payment['event_id'],
            'payment_webhook',
            $sessionId,
            $_SERVER['REMOTE_ADDR'] ?? null,
            substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255),
        ]);
    }

    $pdo->commit();
    http_response_code(200);
    echo json_encode(['ok' => true]);
} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Error interno webhook']);
}
