<?php
/**
 * OxaPay Webhook Handler
 * URL: https://yoursite.com/api/oxapay-webhook.php
 */
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/classes/OxaPayAPI.php';

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

// Get raw input
$payload = file_get_contents('php://input');
$data = json_decode($payload, true);

if (!$data) {
    http_response_code(400);
    exit('Invalid payload');
}

// Get HMAC from header
$hmacHeader = $_SERVER['HTTP_HMAC'] ?? '';

$api = new OxaPayAPI();

// Verify HMAC signature
if (!$api->verifyWebhook($payload, $hmacHeader)) {
    http_response_code(401);
    exit('Invalid signature');
}

$pdo = getDBConnection();

// Get payment data
$status = $data['status'] ?? '';
$trackId = $data['track_id'] ?? '';
$orderId = $data['order_id'] ?? '';
$amount = $data['amount'] ?? 0;
$currency = $data['currency'] ?? '';
$txid = $data['txid'] ?? '';
$type = $data['type'] ?? '';

// Log webhook
$logStmt = $pdo->prepare("INSERT INTO payment_webhooks (provider, order_id, uuid, status, payload, created_at) VALUES ('oxapay', ?, ?, ?, ?, NOW())");
$logStmt->execute([$orderId, $trackId, $status, $payload]);

// Only process invoice type
if ($type !== 'invoice') {
    http_response_code(200);
    exit('ok');
}

// Find the fund request
$stmt = $pdo->prepare("SELECT * FROM fund_requests WHERE payment_reference = ? AND status = 'pending'");
$stmt->execute([$orderId]);
$request = $stmt->fetch();

if (!$request) {
    // Try by track_id
    $stmt = $pdo->prepare("SELECT * FROM fund_requests WHERE payment_uuid = ? AND status = 'pending'");
    $stmt->execute([$trackId]);
    $request = $stmt->fetch();
}

if (!$request) {
    http_response_code(200);
    exit('ok');
}

// Process based on status
// OxaPay statuses: waiting, confirming, paid, failed, expired
if ($status === 'paid') {
    // Payment successful - credit user
    require_once dirname(__DIR__) . '/classes/User.php';
    $userModel = new User();
    $userModel->updateBalance($request['user_id'], $request['amount'], 'add');
    
    // Update fund request
    $stmt = $pdo->prepare("UPDATE fund_requests SET status = 'approved', payment_txid = ?, updated_at = NOW() WHERE id = ?");
    $stmt->execute([$txid, $request['id']]);
    
    // Record transaction
    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description, reference, created_at) VALUES (?, 'deposit', ?, ?, ?, NOW())");
    $stmt->execute([
        $request['user_id'],
        $request['amount'],
        'Crypto deposit via OxaPay',
        $orderId
    ]);
    
    http_response_code(200);
    exit('ok');
    
} elseif (in_array($status, ['failed', 'expired'])) {
    // Payment failed
    $stmt = $pdo->prepare("UPDATE fund_requests SET status = 'rejected', admin_note = ?, updated_at = NOW() WHERE id = ?");
    $stmt->execute(['Payment ' . $status, $request['id']]);
    
    http_response_code(200);
    exit('ok');
    
} else {
    // Still processing (waiting, confirming)
    http_response_code(200);
    exit('ok');
}