<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';

apply_cors();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    send_error('Method not allowed.', 405);
}

$rawBody = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_RAZORPAY_SIGNATURE'] ?? '';

$pdo = getDbConnection();
$gwStmt = $pdo->query("SELECT webhook_secret FROM payment_gateways WHERE gateway_name = 'RAZORPAY'");
$webhookSecret = $gwStmt->fetchColumn();

if (empty($webhookSecret)) {
    http_response_code(200); // acknowledge so Razorpay stops retrying, but do nothing
    exit;
}

$expected = hash_hmac('sha256', $rawBody, $webhookSecret);
if (!hash_equals($expected, $signature)) {
    send_error('Invalid webhook signature.', 400);
}

$event = json_decode($rawBody, true);
$eventType = $event['event'] ?? '';

if ($eventType === 'payment.captured') {
    $payment = $event['payload']['payment']['entity'] ?? [];
    $razorpayOrderId = $payment['order_id'] ?? '';

    if ($razorpayOrderId) {
        $txnStmt = $pdo->prepare(
            "SELECT * FROM payment_transactions WHERE payment_id = :order_id AND status = 'PENDING' LIMIT 1"
        );
        $txnStmt->execute([':order_id' => $razorpayOrderId]);
        $txn = $txnStmt->fetch();

        if ($txn) {
            $pdo->beginTransaction();
            try {
                $upd = $pdo->prepare(
                    "UPDATE payment_transactions SET status = 'SUCCESS', verified_at = NOW() WHERE id = :id"
                );
                $upd->execute([':id' => $txn['id']]);

                $extend = $pdo->prepare(
                    'UPDATE users SET validity_days = validity_days + :days, activated_at = NOW() WHERE email = :email'
                );
                $extend->execute([':days' => (int) $txn['validity_days_added'], ':email' => $txn['user_email']]);

                $pdo->commit();
            } catch (Throwable $e) {
                $pdo->rollBack();
            }
        }
    }
}

http_response_code(200);
echo json_encode(['success' => true]);
