<?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');
$xVerify = $_SERVER['HTTP_X_VERIFY'] ?? '';

$pdo = getDbConnection();
$gwStmt = $pdo->query("SELECT salt_key, salt_index FROM payment_gateways WHERE gateway_name = 'PHONEPE'");
$gw = $gwStmt->fetch();

if (!$gw || empty($gw['salt_key'])) {
    http_response_code(200);
    exit;
}

// PhonePe signature: SHA256(base64Response + saltKey) + "###" + saltIndex
$expected = hash('sha256', $rawBody . $gw['salt_key']) . '###' . $gw['salt_index'];
if (!hash_equals($expected, $xVerify)) {
    send_error('Invalid webhook signature.', 400);
}

$decoded = json_decode(base64_decode($rawBody), true);
$merchantTransactionId = $decoded['data']['merchantTransactionId'] ?? '';
$state = $decoded['data']['state'] ?? '';

if ($merchantTransactionId && $state === 'COMPLETED') {
    $txnStmt = $pdo->prepare(
        "SELECT * FROM payment_transactions WHERE order_id = :order_id AND status = 'PENDING' LIMIT 1"
    );
    $txnStmt->execute([':order_id' => $merchantTransactionId]);
    $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]);
