<?php

// Include database connection and email function
require './conn.php';


use GuzzleHttp\Client;

require 'vendor/autoload.php';
$client = new Client();
// Get the raw POST data
$rawPayload = file_get_contents("php://input");
$payload = json_decode($rawPayload, true);

// Respond with HTTP 200 immediately to acknowledge receipt
//http_response_code(200);

// Ensure it's a valid JSON payload
if (!$payload || !isset($payload['event'])) {
    error_log("Invalid webhook payload received");
    exit;
}

// Switch-case to handle different events
switch ($payload['event']) {

 case 'deposit.failed_aml':

  // Validate payload
  if (!isset($payload['data']['status']) || $payload['data']['status'] !== 'failed_aml') {
   error_log("Invalid webhook.");
      http_response_code(400);
      exit;
  }

$qemail = $payload['data']['user']['email'] ?? null;
if (!$qemail) {
    error_log("Email missing in payload");
    http_response_code(400);
    exit;
}
  

  $amount = (float) $payload['data']['amount'];
  $currency = strtoupper($payload['data']['currency']);
  $txid = strtoupper($payload['data']['txid']);
 // $currency = $trade['currency'];
 $u = getUserInfo($qemail);
 $name = $u['first_name'];
 $email = $u['email'];


     // Send email notification
     $subject = "Transaction Rejected!";
     $message = "<p>Hello " . htmlspecialchars($name) . ",</p>";
     $message .= "A deposit of <b>" . number_format($amount, 6) . " </b> $currency to your wallet was rejected.</p>";
     $message .= "<p>Please contact support for any assistance.</p>";
     $message .= "<p>Best regards,<br><b>Swapeki Team</b></p>";

     //NOTIFY ADMIN
     $s = getSettings();
            $adminEmail = $s[0]['admin_email'];
     $subject2 = "User Deposit Rejected!";
     $message2 = "<p>Hello Admin,</p>";
     $message2 .= "A user deposit of <b>" . number_format($amount, 2) . " </b> $currency to $name ($email) wallet was rejected.</p>";
     $message2 .= "<p>Best regards,<br><b>Swapeki Team</b></p>";

     sendMail($email, $subject, $message);
     sendMail($adminEmail, $subject2, $message2);
      addNotification($u['id'], "A deposit of " . number_format($amount, 6) . "  $currency to your wallet was rejected.", 'Deposit Rejected');
     $transactionData = []; 
     $transactionData['payload'] = json_encode($payload['data']);
     $transactionData['title'] = $currency . " DEPOSIT";
     $transactionData['desc'] = "CRYPTO TRANSFER";
     $transactionData['time'] = time();
     $transactionData['amount'] = $amount;
     $transactionData['ref'] = $txid;
     $transactionData['status'] = "Failed";
     $transactionData['our_ref'] = $txid;
     $transactionData['email'] = $email;
     $transactionData['type'] = "crypto";
   
     insertTransaction($transactionData);
     http_response_code(200);
 
  break;



 case 'deposit.on_hold':

  // Validate payload
  if (!isset($payload['data']['status']) || $payload['data']['status'] !== 'on_hold') {
   error_log("Transaction not done.");
      http_response_code(400);
      exit;
  }

$qemail = $payload['data']['user']['email'] ?? null;
if (!$qemail) {
    error_log("Email missing in payload");
    http_response_code(400);
    exit;
}
  $amount = (float) $payload['data']['amount'];
  $currency = strtoupper($payload['data']['currency']);
 // $currency = $trade['currency'];
 $u = getUserInfo($qemail);
 $name = $u['first_name'];
 $email = $u['email'];


     // Send email notification
     $subject = "Deposit on hold!";
     $message = "<p>Hello " . htmlspecialchars($name) . ",</p>";
     $message .= "You have just received a deposit of <b>" . number_format($amount, 6) . " </b> $currency in your wallet but this deposit is currently on hold. We will notify you about the final status.</p>";
     $message .= "<p>Best regards,<br><b>Swapeki Team</b></p>";
  addNotification($u['id'], "You have just received a deposit of " . number_format($amount, 6) . "  $currency in your wallet but this deposit is currently on hold. We will notify you about the final status.", 'Deposit on Hold');
   if(sendMail($email, $subject, $message)){
    http_response_code(200);
   }
   else {
    error_log("Failed to notify $email about a held deposit");
    http_response_code(500);
}

  break;



 case 'deposit.successful':

  // Validate payload
  if (!isset($payload['data']['status']) || $payload['data']['status'] !== 'accepted') {
   error_log("Transaction not done.");
      http_response_code(400);
      exit;
  }

$qemail = $payload['data']['user']['email'] ?? null;
if (!$qemail) {
    error_log("Email missing in payload");
    http_response_code(400);
    exit;
}
  $amount = (float) $payload['data']['amount'];
  $currency = strtoupper($payload['data']['currency']);
  $txid = $payload['data']['txid'];
 // $currency = $trade['currency'];
 $u = getUserInfo($qemail);
 $name = $u['first_name'];
 $email = $u['email'];


     // Send email notification
     $subject = "Deposit successful!";
     $message = "<p>Hello " . htmlspecialchars($name) . ",</p>";
     $message .= "You have just received a deposit of <b>" . number_format($amount, 6) . " </b> $currency in your wallet</p>";
     $message .= "<p>Feel free to try a new trade.</p>";
     $message .= "<p>Best regards,<br><b>Swapeki Team</b></p>";
 addNotification($u['id'], "You have just received a deposit of " . number_format($amount, 6) . "  $currency in your wallet", 'Deposit Successful');
   if(sendMail($email, $subject, $message)){
    $transactionData = []; 
    $transactionData['payload'] = json_encode($payload['data']);
    $transactionData['title'] = $currency . " DEPOSIT";
    $transactionData['desc'] = "CRYPTO TRANSFER";
    $transactionData['time'] = time();
    $transactionData['amount'] = $amount;
    $transactionData['ref'] = $txid;
    $transactionData['status'] = "Complete";
    $transactionData['our_ref'] = $txid;
    $transactionData['email'] = $email;
    $transactionData['type'] = "crypto";
  
    insertTransaction($transactionData);
    http_response_code(200);
   }
   else {
    error_log("Failed to notify $email about a successful deposit");
    http_response_code(500);
}

  break;


 case 'withdraw.rejected':

  // Validate payload
  if (!isset($payload['data']['status']) || $payload['data']['status'] !== 'Rejected') {
   error_log("Invalid webhook.");
      http_response_code(400);
      exit;
  }

$qemail = $payload['data']['user']['email'] ?? null;
if (!$qemail) {
    error_log("Email missing in payload");
    http_response_code(400);
    exit;
}
  $amount = (float) $payload['data']['amount'];
  $ref = null;
if (!empty($payload['data']['reference']) && str_contains($payload['data']['reference'], '=')) {
    $parts = explode('=', $payload['data']['reference']);
    $ref = $parts[1] ?? null;
}

if (!$ref) {
    http_response_code(400);
    exit;
}

  $note = $payload['data']['transaction_note'];
  $currency = strtoupper($payload['data']['currency']);
  $w_type = filter_var($ref, FILTER_VALIDATE_EMAIL) === false ? 'internal' : 'user';

if($w_type === 'internal'){
 //GET THE TRADE
 $stmt = $mysqli->prepare("SELECT * FROM trades WHERE trade_id = ?");
 $stmt->bind_param("s", $ref);
 $stmt->execute();
 $result = $stmt->get_result();
 $trade = $result->fetch_assoc();
 $stmt->close();

 if (!$trade) {
  error_log("Trade not found.");
     http_response_code(404);
     exit;
 }
 $emailR = $trade['email'];
 $u = getUserInfo($emailR);
 if (empty($u)) {
  error_log("User not found for email: $emailR.");
  http_response_code(404);
  exit;
}
 $name = $u['first_name'];

 if($note === 'buy'){
     // Send email notification
     $subject = "Crypto purchase Failed partially!";
     $message = "<p>Hello " . $name . ",</p>";
     $message .= "Your crypto purchase was successful and your Naira balance was probably debited but a deposit of the equivalent of <b>" . number_format($amount, 6) . " </b> $currency to your wallet was rejected.</p>";
     $message .= "<p>Please contact support for any assistance and settlement. The trade ID is: $ref</p>";
     $message .= "<p>Best regards,<br><b>Swapeki Team</b></p>";

     $subject2 = "User crypto purchase Failed partially!";
     $message2 = "<p>Hello Admin,</p>";
     $message2 .= "$name's crypto purchase was successful but a deposit of the equivalent of <b>" . number_format($amount, 6) . " </b> $currency to $name ($emailR) wallet was rejected whereas their Naira balance was debited and funds deposited to the main account.</p>";
     $message2 .= "<p>Best regards,<br><b>Swapeki Team</b></p>";
 addNotification($u['id'], "Your crypto purchase was successful and your Naira balance was probably debited but a deposit of the equivalent of " . number_format($amount, 6) . "  $currency to your wallet was rejected.", "Crypto purchase Failed partially!");
     sendMail($emailR, $subject, $message);
     notifyAdmins($subject2, $message2);
     http_response_code(200);
 }

 else if($note === 'sell'){
  $subject = "Crypto Sale Failed Partially!";
     $message = "<p>Hello " . $name . ",</p>";
     $message .= "Your crypto sale was successful but a deposit of the equivalent Naira to your bank account was rejected.</p>";
     $message .= "<p>Please contact support for any assistance and settlement. The trade ID is: $ref</p>";
     $message .= "<p>Best regards,<br><b>Swapeki Team</b></p>";

$subject2 = "User crypto sale Failed partially!";
$message2 = "<p>Hello Admin,</p>";
$message2 .= "$name's crypto sale was successful but a deposit of the equivalent Naira to $name ($emailR) bank account was rejected whereas their Naira funds was deposited to their NGN sub-account. Move it and pay them. Everything will be moved when they execute another sell trade.</p>";
$message2 .= "<p>Best regards,<br><b>Swapeki Team</b></p>";
addNotification($u['id'], "Your crypto sale was successful but a deposit of the equivalent Naira to your bank account was rejected", "Crypto sale Failed partially!");
sendMail($emailR, $subject, $message);
     notifyAdmins($subject2, $message2);

http_response_code(200);
 }

}

else if($w_type === 'user'){
 $u = getUserInfo($qemail);
 if (empty($u)) {
  error_log("User not found for email: $email.");
  http_response_code(404);
  exit;
}
 $name = $u['first_name'];
 $email = $u['email'];

 $subject = "Withdrawal Rejected!";
 $message = "<p>Hello " .$name . ",</p>";
 $message .= "A withdrawal of <b>" . number_format($amount, 6) . " </b> $currency to your wallet was rejected.</p>";
 $message .= "<p>Please contact support for any assistance.</p>";
 $message .= "<p>Best regards,<br><b>Swapeki Team</b></p>";
addNotification($u['id'], "A withdrawal of " . number_format($amount, 6) . "  $currency to your wallet was rejected.", "Withdrawal Rejected!");
 sendMail($email, $subject, $message);
 $txid = $payload['data']['txid'] ?? '';
 $transactionData = []; 
 $transactionData['payload'] = json_encode($payload['data']);
 $transactionData['title'] = $currency . " WITHDRAWAL";
 $transactionData['desc'] = "CRYPTO TRANSFER";
 $transactionData['time'] = time();
 $transactionData['amount'] = $amount;
 $transactionData['ref'] = $txid;
 $transactionData['status'] = "Failed";
 $transactionData['our_ref'] = $payload['data']['txid'];
 $transactionData['email'] = $email;
 $transactionData['type'] = "crypto";

 insertTransaction($transactionData);
 http_response_code(200);


}
 
  break;



 case 'withdraw.successful':

  // Validate payload
  if (!isset($payload['data']['status']) || $payload['data']['status'] != 'Done') {
   error_log("Transaction not done.");
      http_response_code(400);
      exit;
  }

$qemail = $payload['data']['user']['email'] ?? null;
if (!$qemail) {
    error_log("Email missing in payload");
    http_response_code(400);
    exit;
}
  $amount = (float) $payload['data']['amount'];
$ref = null;
if (!empty($payload['data']['reference']) && str_contains($payload['data']['reference'], '=')) {
    $parts = explode('=', $payload['data']['reference']);
    $ref = $parts[1] ?? null;
}

if (!$ref) {
    http_response_code(400);
    exit;
}
  $txid = $payload['data']['txid'];
  $note = $payload['data']['transaction_note'];
  $currency = strtoupper($payload['data']['currency']);
  $w_type = filter_var($ref, FILTER_VALIDATE_EMAIL) === false ? 'internal' : 'user';

if($note === 'buy'){
//ITS A BUY. TRADE ID IN REF
$stmt = $mysqli->prepare("SELECT * FROM trades WHERE trade_id = ? LIMIT 1");
$stmt->bind_param("s", $ref);
$stmt->execute();
$result = $stmt->get_result();
$trade = $result->fetch_assoc();
$stmt->close();

if (!$trade) {
 error_log("Trade not found.");
    http_response_code(404);
    exit;
}

if ($trade['status'] === 'done') {
 error_log("Trade completed.");
    http_response_code(200);
    exit;
}

$emailR = $trade['email'];
//$wallet = $trade['wallet'];
$amountR = $trade['receive'];
$currencyR = $trade['currency'];
//$u = getUserInfo($emailR);
//$name = $u['first_name'];

 $u = getUserInfo($emailR);
 if (empty($u)) {
  error_log("User not found for email: $emailR.");
  http_response_code(404);
  exit;
}
 $name = $u['first_name'];
     // Send email notification
     $subject = "Transaction successful!";
     $message = "<p>Hello " . $name . ",</p>";
     $message .= "You have just received a deposit of <b>" . number_format($amountR, 6) . " </b> $currencyR in your wallet</p>";
     $message .= "<p>Feel free to try a new trade.</p>";
     $message .= "<p>Best regards,<br><b>Swapeki Team</b></p>";

$updstmt = $mysqli->prepare("UPDATE trades SET status = 'done' WHERE trade_id = ?");
$updstmt->bind_param("s", $ref);

   if($updstmt->execute()){
    addNotification($u['id'], "You have just received a deposit of " . number_format($amountR, 6) . "  $currencyR in your wallet", "Transaction successful!");
    sendMail($emailR, $subject, $message);

    http_response_code(200);
   }
   else {
    error_log("Failed to update trade status.");
    http_response_code(500);
   }
   $updstmt->close();
}

else if($note === 'sell'){
 $stmt = $mysqli->prepare("SELECT * FROM trades WHERE trade_id = ?");
 $stmt->bind_param("s", $ref);
 $stmt->execute();
 $result = $stmt->get_result();
 $trade = $result->fetch_assoc();
 $stmt->close();
 //error_log("PayLoad: " . json_encode($payload));

 if (!$trade) {
  error_log("Trade not found.");
     http_response_code(404);
     exit;
 }
 if ($trade['status'] === 'done') {
  error_log("Trade completed.");
     http_response_code(200);
     exit;
 }

 $emailR = $trade['email'];
 //$wallet = $trade['wallet'];
 $amountR = $trade['receive'];
 $currencyR = $trade['currency'];
$u = getUserInfo($emailR);
$name = $u['first_name'];

//API TO SEND TO USER BANK

try {
    $q = $client->request('POST', $quidaxBase . 'users/me/withdraws', [
        'body' => json_encode([
            'amount' => $amountR,
            'fund_uid' => $u['withdrawal_bank_account'],
            'fund_uid2' => $u['withdrawal_bank_code'],
            'currency' => 'ngn',
            'transaction_note' => 'pay',
                'reference' => time() .'='. $ref,
                'narration' => 'pay'
        ]),
        'headers' => [
            'Authorization' => 'Bearer ' . $qsk,
            'Accept' => 'application/json',
            'Content-Type' => 'application/json',
        ],
    ]);

    $res = json_decode($q->getBody(), true);

    if ($res && isset($res['status']) && $res['status'] === 'success') {
        $subject = "You got an incoming payment!";
$message = "<p>Hello " . $name . ",</p>";
$message .= "You have just received an incoming deposit of <b>" . number_format($amountR, 2) . " </b> Naira to your bank account.</p>";
$message .= "<p>We will let you know the status soon.</p>";
$message .= "<p>Best regards,<br><b>Swapeki Team</b></p>";
addNotification($u['id'], "You have just received an incoming deposit of " . number_format($amountR, 2) . "  Naira to your bank account.", "You got an incoming payment!");
sendMail($emailR, $subject, $message);
        error_log("Bank payment processing for $emailR.");
       
        http_response_code(200);
    } else {
        error_log("Payment failed: " . json_encode($res));
        http_response_code(500); // Internal Server Error
    }

} catch (Exception $e) {
    error_log("Payment failed: " . $e->getMessage());
    http_response_code(500);
}

}

else if($note === 'pay'){
    $stmt = $mysqli->prepare("SELECT * FROM trades WHERE trade_id = ?");
    $stmt->bind_param("s", $ref);
    $stmt->execute();
    $result = $stmt->get_result();
    $trade = $result->fetch_assoc();
    $stmt->close();
   // error_log("PAID: " . json_encode($payload));

    if (!$trade) {
     error_log("Trade not found.");
        http_response_code(404);
        exit;
    }
    if ($trade['status'] === 'done') {
     error_log("Trade completed.");
        http_response_code(200);
        exit;
    }
   
    $emailR = $trade['email'];
    //$wallet = $trade['wallet'];
    $amountR = $trade['receive'];
    $currencyR = $trade['currency'];
   $u = getUserInfo($emailR);
   $name = $u['first_name'];
   
   $subject = "You got paid!";
   $message = "<p>Hello " . $name . ",</p>";
   $message .= "You have just received a deposit of <b>" . number_format($amountR, 2) . " </b> Naira to your bank account.</p>";
   $message .= "<p>Best regards,<br><b>Swapeki Team</b></p>";
   
   $stmt = $mysqli->prepare("UPDATE trades SET status = 'done' WHERE trade_id = ?");
$stmt->bind_param("s", $ref);
$stmt->execute();
$stmt->close();
      if($stmt->execute()){
        addNotification($u['id'],  "You have just received a deposit of " . number_format($amountR, 2) . "  Naira to your bank account.", "You got paid!");
       sendMail($emailR, $subject, $message);
       http_response_code(200);
      }
      else {
       error_log("Failed to update trade status.");
       http_response_code(500);
      }
      
           error_log("Bank payment processing for $emailR.");
           http_response_code(200);
   
   }
   
   

else if($note === 'send'){
 $u = getUserInfo($ref);
        
    if (empty($u)) {
     error_log("User: $ref not found.");
http_response_code(500);
        exit;
    }

$name = $u['first_name'];

//API TO SEND TO USER BANK
$subject = "Crypto Withdrawal Successful!";
$message = "<p>Hello " . $name . ",</p>";
$message .= "Your crypto withdrawal of $amount $currency was successful. Transaction ID: $txid</p>";
$message .= "<p>Feel free to try a new trade.</p>";
$message .= "<p>Best regards,<br><b>Swapeki Team</b></p>";
addNotification($u['id'],  "Your crypto withdrawal of $amount $currency was successful.", "Crypto Withdrawal Successful!");
if(sendMail($ref, $subject, $message)){
    $transactionData = []; 
    $transactionData['payload'] = json_encode($payload['data']);
    $transactionData['title'] = $currency . " WITHDRAWAL";
    $transactionData['desc'] = "CRYPTO TRANSFER";
    $transactionData['time'] = time();
    $transactionData['amount'] = $amount;
    $transactionData['ref'] = $txid;
    $transactionData['status'] = "Complete";
    $transactionData['our_ref'] = $txid;
    $transactionData['email'] = $ref;
    $transactionData['type'] = "crypto";
  
    insertTransaction($transactionData);
http_response_code(200);
}
else {
error_log("Failed to notify $ref about a successful payment");
http_response_code(500);
}

}


else {
 error_log("Invalid transaction type. Narration: ".json_encode($payload));
 http_response_code(400);
}

  break;


 case 'swap_transaction.failed':

  // Validate payload
  if (!isset($payload['data']['swap_quotation']['id'])) {
   error_log("Order ID not found.");
      http_response_code(400);
      exit;
  }

  $trade_id = sanitizeInput($payload['data']['swap_quotation']['id']);

  $stmt = $mysqli->prepare("SELECT * FROM trades WHERE trade_id = ?");
  $stmt->bind_param("s", $trade_id);
  $stmt->execute();
  $result = $stmt->get_result();
  $trade = $result->fetch_assoc();
  $stmt->close();

  if (!$trade) {
   error_log("Trade not found.");
      http_response_code(404);
      exit;
  }
  if ($trade['status'] === 'done') {
   error_log("Trade completed.");
      http_response_code(200);
      exit;
  }
  $email = $trade['email'];
  //$wallet = $trade['wallet'];
  $amount = $trade['paid_amount'];
 // $currency = $trade['currency'];
 $u = getUserInfo($email);
 $name = $u['first_name'];


   $updateStmt = $mysqli->prepare("UPDATE users SET ngn_balance = ngn_balance + ? WHERE email = ?");
   $updateStmt->bind_param("ds", $amount, $email);

   if($updateStmt->execute()){
    error_log("$name got refunded for trade ID: $trade_id");
    $mysqli->query("UPDATE trades SET status = 'done' WHERE trade_id = '$trade_id'");       
    // Send email notification
    $subject = "You got refunded!";
    $message = "<p>Hello " . htmlspecialchars($name) . ",</p>";
    $message .= "<p>Unfortunately, we could not complete your trade with ID: <b>" . htmlspecialchars($trade_id) . "</b>. ";
    $message .= "Your balance has been credited with <b>" . number_format($amount, 2) . " NGN</b>.</p>";
    $message .= "<p>Feel free to try a new trade.</p>";
    $message .= "<p>Best regards,<br><b>Swapeki Team</b></p>";
    
addNotification($u['id'],  "Unfortunately, we could not complete your trade.", "You got refunded!");
    sendMail($email, $subject, $message);
    $transactionData = []; 
    $transactionData['payload'] = json_encode($payload['data']);
    $transactionData['title'] = "CRYPTO PURCHASE";
    $transactionData['desc'] = "CRYPTO PURCHASE";
    $transactionData['time'] = time();
    $transactionData['amount'] = $amount;
    $transactionData['ref'] = $trade_id;
    $transactionData['status'] = "Failed";
    $transactionData['our_ref'] = $trade_id;
    $transactionData['email'] = $email;
    $transactionData['type'] = "crypto";
  
    insertTransaction($transactionData);
    http_response_code(200);
   }
   else {
    error_log("Failed to update balance for $email. MySQL error: " . $mysqli->error);
    http_response_code(500);
}

  break;

  case 'swap_transaction.reversed':

  // Validate payload
  if (!isset($payload['data']['swap_quotation']['id'])) {
   error_log("Order ID not found.");
      http_response_code(400);
      exit;
  }

  $trade_id = sanitizeInput($payload['data']['swap_quotation']['id']);

  $stmt = $mysqli->prepare("SELECT * FROM trades WHERE trade_id = ?");
  $stmt->bind_param("s", $trade_id);
  $stmt->execute();
  $result = $stmt->get_result();
  $trade = $result->fetch_assoc();
  $stmt->close();

  if (!$trade) {
   error_log("Trade not found.");
      http_response_code(404);
      exit;
  }
  if ($trade['status'] === 'done') {
   error_log("Trade completed.");
      http_response_code(200);
      exit;
  }
  $email = $trade['email'];
  //$wallet = $trade['wallet'];
  $amount = $trade['paid_amount'];
 // $currency = $trade['currency'];
 $u = getUserInfo($email);
 $name = $u['first_name'];


   $updateStmt = $mysqli->prepare("UPDATE users SET ngn_balance = ngn_balance + ? WHERE email = ?");
   $updateStmt->bind_param("ds", $amount, $email);

   if($updateStmt->execute()){
    error_log("$name got refunded for trade ID: $trade_id");
    $mysqli->query("UPDATE trades SET status = 'done' WHERE trade_id = '$trade_id'");       
    // Send email notification
    $subject = "You got refunded!";
    $message = "<p>Hello " . htmlspecialchars($name) . ",</p>";
    $message .= "<p>Unfortunately, we could not complete your trade with ID: <b>" . htmlspecialchars($trade_id) . "</b>. ";
    $message .= "Your balance has been credited with <b>" . number_format($amount, 2) . " NGN</b>.</p>";
    $message .= "<p>Feel free to try a new trade.</p>";
    $message .= "<p>Best regards,<br><b>Swapeki Team</b></p>";
    
addNotification($u['id'],  "Unfortunately, we could not complete your trade.", "You got refunded!");
    sendMail($email, $subject, $message);
    $transactionData = []; 
      $transactionData['payload'] = json_encode($payload['data']);
      $transactionData['title'] = "CRYPTO PURCHASE";
      $transactionData['desc'] = "CRYPTO PURCHASE";
      $transactionData['time'] = time();
      $transactionData['amount'] = $amount;
      $transactionData['ref'] = $trade_id;
      $transactionData['status'] = "Reversed";
      $transactionData['our_ref'] = $trade_id;
      $transactionData['email'] = $email;
      $transactionData['type'] = "crypto";
    
      insertTransaction($transactionData);
    http_response_code(200);
   }
   else {
    error_log("Failed to update balance for $email. MySQL error: " . $mysqli->error);
    http_response_code(500);
}

   break;
 
 

 case 'swap_transaction.completed':

  // Validate payload
  if (!isset($payload['data']['swap_quotation']['id'])) {
   error_log("Order ID not found.");
      http_response_code(400);
      exit;
  }

  $trade_id = sanitizeInput($payload['data']['swap_quotation']['id']);

  $stmt = $mysqli->prepare("SELECT * FROM trades WHERE trade_id = ?");
  $stmt->bind_param("s", $trade_id);
  $stmt->execute();
  $result = $stmt->get_result();
  $trade = $result->fetch_assoc();
  $stmt->close();

  if (!$trade) {
   error_log("Trade not found.");
      http_response_code(404);
      exit;
  }
  if ($trade['status'] === 'done') {
   error_log("Trade completed.");
      http_response_code(200);
      exit;
  }

  $email = $trade['email'];
  $wallet = $trade['wallet'];
  $amount = $trade['receive'];
  $type = $trade['type'];

  $currency = strtolower($trade['currency']);

  $transactionData = []; 
  $flow = NULL;
  if($type == 'buy'){
    $flow = 'out';
  }
  else if ($type == 'sell'){
    $flow = 'in';
  }
$act = $type === 'buy' ? "PURCHASE" : "SALE";
  $transactionData['payload'] = json_encode($payload['data']);
  $transactionData['title'] = $trade['currency'] . " CRYPTO ".$act;
  $transactionData['desc'] = "CRYPTO ".$act;
  $transactionData['time'] = time();
  $transactionData['amount'] = $amount;
  $transactionData['ref'] = $trade_id;
  $transactionData['status'] = "Complete";
  $transactionData['our_ref'] = $trade_id;
  $transactionData['email'] = $email;
  $transactionData['type'] = "crypto";
  $transactionData['flow'] = $flow;

  insertTransaction($transactionData);

  try {
   if($type === 'buy'){
    //Initiate a withdraw to customer wallet
   $q = $client->request('POST', $quidaxBase . 'users/me/withdraws', [
       'body' => json_encode([
           'currency' => $currency,
           'amount' => $amount,
           'fund_uid' => $wallet,
           'reference' => time() .'='. $trade_id,
           'transaction_note' => 'buy',
           'narration' => $email
       ]),
       'headers' => [
           'Authorization' => 'Bearer ' . $qsk,
           'Accept' => 'application/json',
           'Content-Type' => 'application/json',
       ],
   ]);

   $res = json_decode($q->getBody(), true);

   if ($res && isset($res['status']) && $res['status'] === 'success') {
       error_log("Transfer processing FOR BUY.");
       http_response_code(200);
   } else {
       error_log("Withdrawal failed: " . json_encode($res));
       http_response_code(500); // Internal Server Error
   }
  }
  else {
    $u = getUserInfo($email);
        
            if (empty($u) || $u['quidax_id'] === null) {
                error_log('User not found.');
                http_response_code(400);
                exit;
            }
            $q_id = $u['quidax_id'];

            //CHECK USER BALANCE
            $q = $client->request('GET', $quidaxBase . 'users/'.$q_id.'/wallets/ngn', [
             'headers' => [
                 'Authorization' => 'Bearer ' . $qsk,
                 'Accept' => 'application/json',
                 'Content-Type' => 'application/json',
             ],
         ]);
         
         $res = json_decode($q->getBody(), true);
         if (isset($res['status']) && $res['status'] === 'success' && !empty($res['data'])) {
          $bal = $res['data']['balance'];
          if($bal > 0){
           //WITHDRAW TO MAIN ACCOUNT
           $q2 = $client->request('POST', $quidaxBase . 'users/'.$q_id.'/withdraws', [
            'body' => json_encode([
                'currency' => 'ngn',
                'amount' => $bal,
                'fund_uid' => '87f1e72e-ef15-4208-b6bf-ff3e6a37dc6d',
                'transaction_note' => 'sell',
                'reference' => time() .'='. $trade_id,
                'narration' => 'sell'
            ]),
            'headers' => [
                'Authorization' => 'Bearer ' . $qsk,
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
            ],
        ]);
     
        $res2 = json_decode($q2->getBody(), true);
     
        if ($res2 && isset($res2['status']) && $res2['status'] === 'success') {
            error_log("Transfer processing for SELL.");
            http_response_code(200);
        } else {
            error_log("Withdrawal failed: " . json_encode($res2));
            http_response_code(500); // Internal Server Error
        }
          }
          else {
           error_log("Withdrawal failed: User NGN balance is zero.");
            http_response_code(400);
          }
         }
         else {
          error_log("Withdrawal failed: " . json_encode($res));
          http_response_code(500);
         }

          

  }
} catch (Exception $e) {
   error_log("API Request Failed: " . $e->getMessage());
   http_response_code(500);
}
  break;


    case "wallet.address.generated":
        $data = $payload['data'];

        $quserEmail = $data['user']['email'];
        $u = getUserInfo($quserEmail);
       // $name = $u['first_name'];
        $userEmail = $u['email'];
        $walletAddress = $data['address'];
        $currency = strtolower($data['currency']);
        $network = strtoupper($data['network']);
            error_log("Wallet address updated successfully for $userEmail");
            
            // Send email notification
            $subject = "Your New ".strtoupper($currency)." Wallet Address";
            $message = "Hello " . $data['user']['first_name'] . ",\n\n";
            $message .= "Your ".strtoupper($currency)." ($network) wallet address has been generated:\n\n";
            $message .= "<b>$walletAddress</b><p>";
            $message .= "You can now use this address for deposits on the $network chain.<p>";
            $message .= "Best regards,<br>Swapeki Team";
addNotification($u['id'],  "Your ".strtoupper($currency)." ($network) wallet address has been generated.", "Your New ".strtoupper($currency)." Wallet Address");
            sendMail($userEmail, $subject, $message);
            http_response_code(200);
        break;

    default:
        error_log("Unhandled event type: " . $payload['event']);
        break;
}


//echo json_encode(["success" => true]);
exit;

function insertTransaction(array $transactionData)
{
    global $mysqli;
    // Retrieve User ID from Email
    $u = getUserInfo($transactionData['email']);
    if (!$u) {
    throw new Exception("User not found for transaction insert.");
}
    $userId = $u['id'];


    // Prepare the SQL statement
    $transactionQuery = $mysqli->prepare("
        INSERT INTO transactions 
        (payload, title, description, date, amount, ref, status, our_ref, email, user_id, type) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    if ($transactionQuery === false) {
        throw new Exception("Failed to prepare statement: " . $mysqli->error);
    }

    // Bind parameters
    $transactionQuery->bind_param(
        "sssssssssis",
        $transactionData['payload'],
        $transactionData['title'],
        $transactionData['desc'],
        $transactionData['time'],
        $transactionData['amount'],
        $transactionData['ref'],
        $transactionData['status'],
        $transactionData['our_ref'],
        $transactionData['email'],
        $userId,
        $transactionData['type']
    );

    // Execute the query
    if (!$transactionQuery->execute()) {
        throw new Exception("Transaction Insert Error: " . $transactionQuery->error);
    }
    // Close the statement
    $transactionQuery->close();

     // 🔁 Optional flow update (SAFE)
    if (!empty($transactionData['flow'])) {
        $flowStmt = $mysqli->prepare("
            UPDATE transactions 
            SET flow = ? 
            WHERE our_ref = ?
        ");
        $flowStmt->bind_param(
            "ss",
            $transactionData['flow'],
            $transactionData['our_ref']
        );
        $flowStmt->execute();
        $flowStmt->close();
    }
}

?>
