

<?php
require_once __DIR__ . '/config/config.php';

// Allow only POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
    exit;
}

// Sanitize input
$id = intval($_POST['id']);
$status = trim($_POST['status']);
$type = trim($_POST['type']);

// Validate
$allowedStatus = ['approved', 'pending', 'rejected', 'declined'];
if (!in_array($status, $allowedStatus) || !in_array($type, ['deposit', 'withdrawal'])) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid parameters']);
    exit;
}

// Choose the table
$table = $type === 'deposit' ? 'deposits' : 'withdrawals';

// Begin transaction
$conn->begin_transaction();

try {
    // Update the transaction status
    $stmt = $conn->prepare("UPDATE `$table` SET `status` = ? WHERE `id` = ?");
    $stmt->bind_param("si", $status, $id);
    $stmt->execute();

    if ($stmt->affected_rows === 0) {
        throw new Exception("Transaction not found or no change made.");
    }
    $stmt->close();

    // If deposit is approved, credit user's account
    if ($type === 'deposit' && $status === 'approved') {
        $stmt = $conn->prepare("SELECT user_id, usd_amount FROM deposits WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->bind_result($user_id, $usd_amount);
        if ($stmt->fetch()) {
            $stmt->close();

            $updateBalance = $conn->prepare("UPDATE users SET account_balance = account_balance + ? WHERE id = ?");
            $updateBalance->bind_param("di", $usd_amount, $user_id);
            $updateBalance->execute();
            $updateBalance->close();

            $formattedAmount = number_format($usd_amount, 2);
            $description = "Your deposit of \$$formattedAmount has been approved and credited to your account. ✅";
            $actor = 'admin';
            $action_type = 'deposit_approved';
            $created_at = date('Y-m-d H:i:s');

            $logStmt = $conn->prepare("INSERT INTO activity_logs (user_id, actor, action_type, description, created_at) VALUES (?, ?, ?, ?, ?)");
            $logStmt->bind_param("issss", $user_id, $actor, $action_type, $description, $created_at);
            $logStmt->execute();
            $logStmt->close();
        } else {
            throw new Exception("Deposit not found.");
        }
    }

    // If withdrawal is approved, debit user's account
    if ($type === 'withdrawal' && $status === 'approved') {
        $stmt = $conn->prepare("SELECT user_id, usd_amount FROM withdrawals WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->bind_result($user_id, $usd_amount);
        if ($stmt->fetch()) {
            $stmt->close();

            $updateBalance = $conn->prepare("UPDATE users SET account_balance = account_balance - ? WHERE id = ?");
            $updateBalance->bind_param("di", $usd_amount, $user_id);
            $updateBalance->execute();
            $updateBalance->close();

            $formattedAmount = number_format($usd_amount, 2);
            $description = "Your withdrawal of \$$formattedAmount has been approved and is being processed. 🚀";
            $actor = "admin";
            $action_type = 'withdrawal_approved';
            $created_at = date('Y-m-d H:i:s');

            $logStmt = $conn->prepare("INSERT INTO activity_logs (user_id, actor, action_type, description, created_at) VALUES (?, ?, ?, ?, ?)");
            $logStmt->bind_param("issss", $user_id, $actor, $action_type, $description, $created_at);
            $logStmt->execute();
            $logStmt->close();
        } else {
            throw new Exception("Withdrawal not found.");
        }
    }

    $conn->commit();
    echo json_encode(['status' => 'success', 'message' => ucfirst($type) . " updated"]);
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}

$conn->close();
?>
