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

header('Content-Type: application/json');

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

if (!$data) {
    http_response_code(400);
    exit(json_encode(['error' => 'Invalid payload']));
}

// Get sign from header
$sign = $_SERVER['HTTP_SIGN'] ?? '';

$api = new HeleketAPI();

// Verify signature
if (!$api->verifyWebhook($data, $sign)) {
    http_response_code(401);
    exit(json_encode(['error' => 'Invalid signature']));
}

$pdo = getDBConnection();

// Get payment status
$status = $data['status'] ?? '';
$paymentStatus = $data['payment_status'] ?? '';
$orderId = $data['order_id'] ?? '';
$uuid = $data['uuid'] ?? '';
$amount = $data['amount'] ?? 0;
$payerAmount = $data['payer_amount'] ?? 0;
$currency = $data['currency'] ?? '';
$txid = $data['txid'] ?? '';

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

// 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 UUID
    $stmt = $pdo->prepare("SELECT * FROM fund_requests WHERE payment_uuid = ? AND status = 'pending'");
    $stmt->execute([$uuid]);
    $request = $stmt->fetch();
}

if (!$request) {
    exit(json_encode(['status' => 'ok', 'message' => 'No matching request']));
}

// Process based on status
if (in_array($status, ['paid', 'paid_over'])) {
    // Payment successful - credit user
    $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 Heleket (' . $currency . ')',
        $orderId
    ]);
    
    echo json_encode(['status' => 'ok', 'message' => 'Payment credited']);
    
} elseif (in_array($status, ['cancel', 'fail', 'system_fail', 'wrong_amount'])) {
    // Payment failed
    $stmt = $pdo->prepare("UPDATE fund_requests SET status = 'rejected', admin_note = ?, updated_at = NOW() WHERE id = ?");
    $stmt->execute(['Payment ' . $status, $request['id']]);
    
    echo json_encode(['status' => 'ok', 'message' => 'Payment failed']);
    
} else {
    // Still processing
    echo json_encode(['status' => 'ok', 'message' => 'Processing']);
}