<?php
declare(strict_types=1);
session_start();
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_login();

$uid = (int)($_SESSION['uid'] ?? 0);
if ($uid <= 0) {
    http_response_code(403);
    exit('Not logged in');
}

$txId   = (int)($_POST['transaction_id'] ?? 0);
$code   = trim($_POST['validation_code'] ?? '');
$action = trim($_POST['action'] ?? '');

if ($txId <= 0 || $code === '') {
    http_response_code(400);
    exit('Invalid request.');
}

try {
    $pdo->beginTransaction();

    // Lock this transaction row
    $stmt = $pdo->prepare("SELECT * FROM transactions WHERE id = ? FOR UPDATE");
    $stmt->execute([$txId]);
    $tx = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$tx) {
        throw new RuntimeException('Transaction not found.');
    }

    // Verify that this transaction belongs to the receiver
    if ((int)$tx['user_id'] !== $uid) {
        throw new RuntimeException('You can only validate your own incoming payment.');
    }

    // Make sure it's pending
    if ($tx['validation_status'] !== 'pending') {
        throw new RuntimeException('This payment has already been processed.');
    }

    // Fetch sender for potential refund later
    $senderId = (int)$tx['sender_id'];

    if ($action === 'validate' && $tx['validation_code'] === $code) {
        // ✅ Validation successful — credit receiver
        $stmt = $pdo->prepare("SELECT id, balance_cents FROM users WHERE id = ? FOR UPDATE");
        $stmt->execute([$uid]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        $newBal = $user['balance_cents'] + $tx['amount_cents'];

        // Update balance and mark transaction validated
        $pdo->prepare("UPDATE users SET balance_cents = ? WHERE id = ?")
            ->execute([$newBal, $uid]);
        $pdo->prepare("UPDATE transactions SET validation_status = 'validated' WHERE id = ?")
            ->execute([$txId]);

        $_SESSION['flash_success'] = 'Payment validated successfully! Funds added to your wallet.';

    } elseif ($action === 'reject') {
        // ❌ Receiver rejected payment
        $pdo->prepare("UPDATE transactions SET validation_status = 'rejected' WHERE id = ?")
            ->execute([$txId]);

        // Refund sender’s balance
        $stmt = $pdo->prepare("SELECT id, balance_cents FROM users WHERE id = ? FOR UPDATE");
        $stmt->execute([$senderId]);
        $sender = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($sender) {
            $refundBal = $sender['balance_cents'] + $tx['amount_cents'];
            $pdo->prepare("UPDATE users SET balance_cents = ? WHERE id = ?")
                ->execute([$refundBal, $senderId]);
        }

        $_SESSION['flash_error'] = 'Payment rejected and funds returned to sender.';
    } else {
        throw new RuntimeException('Invalid validation code.');
    }

    $pdo->commit();
    header('Location: transactions.php');
    exit;

} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    http_response_code(500);
    echo 'Error: ' . htmlspecialchars($e->getMessage());
    exit;
}
