<?php
// PayHere server-to-server notification (IPN).
// Configure this exact URL as the "Notify URL" in the checkout request (already sent
// automatically by upgrade.php) — PayHere calls this directly, no browser/session involved.
require_once 'includes/config.php';
require_once 'includes/functions.php';

header('Content-Type: text/plain');

$merchantId      = $_POST['merchant_id']      ?? '';
$orderId         = $_POST['order_id']         ?? '';
$payhereAmount   = $_POST['payhere_amount']   ?? '';
$payhereCurrency = $_POST['payhere_currency'] ?? '';
$statusCode      = $_POST['status_code']      ?? '';
$md5sig          = $_POST['md5sig']           ?? '';
$paymentId       = $_POST['payment_id']       ?? '';
$method          = $_POST['method']           ?? '';

if (!$orderId || !$md5sig) {
    http_response_code(400);
    echo 'missing_fields';
    exit;
}

$valid = payhereVerifyNotifyHash($merchantId, $orderId, $payhereAmount, $payhereCurrency, $statusCode, $md5sig);

$stmt = $pdo->prepare("SELECT * FROM payhere_payments WHERE order_id = ?");
$stmt->execute([$orderId]);
$payment = $stmt->fetch();

if (!$payment) {
    http_response_code(404);
    echo 'order_not_found';
    exit;
}

if (!$valid) {
    // Log the mismatch but don't touch the user's Pro status.
    $pdo->prepare("UPDATE payhere_payments SET status='failed', raw_payload=? WHERE order_id=?")
        ->execute([json_encode($_POST), $orderId]);
    http_response_code(400);
    echo 'invalid_signature';
    exit;
}

// PayHere status codes: 2 = success, 0 = pending, -1 = canceled, -2 = failed, -3 = chargedback
$statusMap = ['2' => 'completed', '0' => 'pending', '-1' => 'canceled', '-2' => 'failed', '-3' => 'chargedback'];
$newStatus = $statusMap[$statusCode] ?? 'failed';

$pdo->prepare("UPDATE payhere_payments SET status=?, payhere_payment_id=?, method=?, raw_payload=? WHERE order_id=?")
    ->execute([$newStatus, $paymentId, $method, json_encode($_POST), $orderId]);

if ($newStatus === 'completed' && $payment['status'] !== 'completed') {
    activatePro((int)$payment['user_id'], $payment['plan']);
}

echo 'ok';
