<?php
session_start();
include('../includes/config.php');

$id = isset($_POST['id']) ? intval($_POST['id']) : 0;

// Get admin info from session
$admin_id = $_SESSION['admin_id'] ?: 1;
$admin_name = $_SESSION['admin_name'] ?: 'System';
$admin_role = $_SESSION['admin_role'] ?: 'admin';
$ip_address = $_SERVER['REMOTE_ADDR'] ?: '';
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?: '';

// Get transaction details first
$sql = "SELECT t.*, u.first_name, u.last_name, u.email, u.fund_balance, u.available_balance 
        FROM transactions t
        LEFT JOIN users u ON t.user_id = u.id
        WHERE t.id = $id AND t.status = 'pending'";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    $row = mysqli_fetch_assoc($result);
    $user_id = $row['user_id'];
    $amount = $row['amount'];
    $type = $row['type'];
    $description = $row['description'];
    $currency = $row['currency'];
    $user_name = $row['first_name'] . ' ' . $row['last_name'];
    $user_email = $row['email'];
    $old_fund_balance = $row['fund_balance'];
    $old_available_balance = $row['available_balance'];
    
    // Update transaction status
    $update_sql = "UPDATE transactions SET status = 'completed', updated_at = NOW() WHERE id = $id";
    
    if (mysqli_query($conn, $update_sql)) {
        // Calculate new balances
        $new_fund_balance = $old_fund_balance;
        $new_available_balance = $old_available_balance;
        
        // If it's a deposit, update user balance
        if ($type == 'deposit') {
            $new_fund_balance = $old_fund_balance + $amount;
            $new_available_balance = $old_available_balance + $amount;
            
            $update_balance = "UPDATE users SET 
                fund_balance = fund_balance + $amount, 
                available_balance = available_balance + $amount 
                WHERE id = $user_id";
            mysqli_query($conn, $update_balance);
            
            // Log balance update
            $log_sql2 = "INSERT INTO admin_activities (admin_id, admin_name, admin_role, action, description, module, ip_address, user_agent, affected_id, affected_table) 
                        VALUES ('$admin_id', '$admin_name', '$admin_role', 'User Balance Updated', 
                        'Updated balance for user ID $user_id after deposit ($$amount)', 
                        'Users', '$ip_address', '$user_agent', $user_id, 'users')";
            mysqli_query($conn, $log_sql2);
        } elseif ($type == 'withdrawal') {
            // Withdrawal already deducted from balance when initiated
            // Just mark as completed
            $new_available_balance = $old_available_balance; // Already deducted
        }
        
        // Log admin activity
        $log_sql = "INSERT INTO admin_activities (admin_id, admin_name, admin_role, action, description, module, ip_address, user_agent, affected_id, affected_table) 
                    VALUES ('$admin_id', '$admin_name', '$admin_role', 'Transaction Processed', 
                    'Processed transaction ID $id ($$amount, $type) for user ID $user_id', 
                    'Transactions', '$ip_address', '$user_agent', $id, 'transactions')";
        mysqli_query($conn, $log_sql);
        
        // NOTIFICATION: Transaction Processed (USER)
        $mail_subject = "Transaction Processed - " . strtoupper($type);
        $mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Hello <span class='user-name'>" . $row['first_name'] . "</span>,</h2>
                            
                            <p class='message'>
                                ✅ <strong>Your " . $type . " transaction has been processed successfully!</strong><br>
                                The transaction details are now complete and confirmed.
                            </p>

                            <!-- Transaction Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>Transaction ID:</strong> TXN-" . $id . "<br>
                                    <strong>Type:</strong> <span style='color: " . ($type == 'deposit' ? '#28a745' : ($type == 'withdrawal' ? '#dc3545' : '#007bff')) . "; font-weight: bold;'>" . ucfirst($type) . "</span><br>
                                    <strong>Amount:</strong> " . $currency . " " . number_format($amount, 2) . "<br>
                                    <strong>Description:</strong> " . $description . "<br>
                                    <strong>Status:</strong> <span style='color: #28a745; font-weight: bold;'>COMPLETED</span><br>
                                    <strong>Processed By:</strong> " . $admin_name . " (Admin)<br>
                                    <strong>Completion Date:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>Transaction Date:</strong> " . date('F j, Y g:i A', strtotime($row['created_at'])) . "
                                </div>
                            </div>";

        // Add balance information for deposits
        if ($type == 'deposit') {
            $mail_message .= "
                            <!-- Balance Update -->
                            <div style='background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #155724;'>💰 Balance Updated</h4>
                                <p style='color: #155724;'>
                                    <strong>Your account balances have been updated:</strong><br><br>
                                    <strong>Fund Balance:</strong><br>
                                    • Before: " . $currency . " " . number_format($old_fund_balance, 2) . "<br>
                                    • Added: " . $currency . " +" . number_format($amount, 2) . "<br>
                                    • <strong>New Total: " . $currency . " " . number_format($new_fund_balance, 2) . "</strong><br><br>
                                    
                                    <strong>Available Balance:</strong><br>
                                    • Before: " . $currency . " " . number_format($old_available_balance, 2) . "<br>
                                    • Added: " . $currency . " +" . number_format($amount, 2) . "<br>
                                    • <strong>New Total: " . $currency . " " . number_format($new_available_balance, 2) . "</strong>
                                </p>
                            </div>";
        } elseif ($type == 'withdrawal') {
            $mail_message .= "
                            <!-- Withdrawal Information -->
                            <div style='background: #d1ecf1; border: 1px solid #bee5eb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0c5460;'>💳 Withdrawal Processing</h4>
                                <p style='color: #0c5460;'>
                                    <strong>Next Steps:</strong><br>
                                    • Funds will be transferred to your specified account<br>
                                    • Processing time: 1-3 business days (varies by method)<br>
                                    • You will receive another notification when funds are sent<br>
                                    • Contact support if you don't receive funds within 5 business days
                                </p>
                            </div>";
        }

        $mail_message .= "
                            <!-- What This Means -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>📋 What Happens Next?</h3>
                                <p style='color: #6c757d;'>";
        
        if ($type == 'deposit') {
            $mail_message .= "• Funds are now available for trading<br>
                              • You can subscribe to trading bots<br>
                              • Start your AI trading journey<br>
                              • Monitor your balances in dashboard";
        } elseif ($type == 'withdrawal') {
            $mail_message .= "• Your withdrawal request is approved<br>
                              • Funds will be processed shortly<br>
                              • Check your external account in 1-3 days<br>
                              • Contact support if any issues arise";
        } else {
            $mail_message .= "• Your transaction is complete<br>
                              • Check your account for updates<br>
                              • View transaction history for details";
        }
        
        $mail_message .= "
                                </p>
                            </div>

                            <!-- Action Buttons -->
                            <div style='text-align: center; margin: 30px 0;'>
                                <a href='" . $myUrl . "/transactions.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                    View All Transactions
                                </a>
                                <a href='" . $myUrl . "/dashboard.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #6c757d; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                    Go to Dashboard
                                </a>
                            </div>

                            <!-- Support Section -->
                            <div class='support-section'>
                                <p class='support-text'>Need help with this transaction?</p>
                                <a href='" . $myUrl . "/support.php?category=transactions' class='support-link'>Contact Transaction Support</a>
                            </div>
                        </div>";

        // Send user notification
        $user_email = $row['email'];
        $first_name = $row['first_name'];
        require_once("../proccess/mail_sender.php");

        // NOTIFICATION: Transaction Processed (ADMIN)
        $admin_mail_subject = "Transaction #" . $id . " Processed - " . strtoupper($type);
        $admin_mail_message = "<!-- Content Section -->
                            <div class='email-content'>
                                <h2 class='greeting'>Transaction Processed</h2>
                                
                                <p class='message'>
                                    A pending transaction has been processed and marked as completed.
                                </p>

                                <!-- Transaction Details -->
                                <div class='details-section'>
                                    <div class='detail-box'>
                                        <strong>Transaction ID:</strong> TXN-" . $id . "<br>
                                        <strong>User ID:</strong> " . $user_id . "<br>
                                        <strong>User Name:</strong> " . $user_name . "<br>
                                        <strong>User Email:</strong> " . $user_email . "<br>
                                        <strong>Type:</strong> " . ucfirst($type) . "<br>
                                        <strong>Amount:</strong> " . $currency . " " . number_format($amount, 2) . "<br>
                                        <strong>Description:</strong> " . $description . "<br>
                                        <strong>Processed By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                        <strong>Processing Time:</strong> " . date('F j, Y g:i A') . "<br>
                                        <strong>IP Address:</strong> " . $ip_address . "<br>
                                        <strong>Status Change:</strong> PENDING → <span style='color: #28a745;'>COMPLETED</span>
                                    </div>
                                </div>";

        if ($type == 'deposit') {
            $admin_mail_message .= "
                                <!-- Balance Impact -->
                                <div style='background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                    <h4 style='color: #155724;'>💰 Balance Impact</h4>
                                    <p style='color: #155724;'>
                                        <strong>User Balance Updated:</strong><br>
                                        • Fund Balance: " . $currency . " " . number_format($old_fund_balance, 2) . " → " . $currency . " " . number_format($new_fund_balance, 2) . "<br>
                                        • Available Balance: " . $currency . " " . number_format($old_available_balance, 2) . " → " . $currency . " " . number_format($new_available_balance, 2) . "<br>
                                        • Increase: " . $currency . " +" . number_format($amount, 2) . "
                                    </p>
                                </div>";
        }

        $admin_mail_message .= "
                                <!-- System Information -->
                                <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                    <h4 style='color: #495057;'>⚙️ System Log</h4>
                                    <p style='color: #495057;'>
                                        <strong>Activity Logged:</strong> Yes<br>
                                        <strong>User Agent:</strong> " . substr($user_agent, 0, 100) . "...<br>
                                        <strong>Session ID:</strong> " . session_id() . "<br>
                                        <strong>Processing Duration:</strong> " . round((time() - strtotime($row['created_at'])) / (60 * 60 * 24), 1) . " days pending
                                    </p>
                                </div>

                                <!-- Admin Actions -->
                                <div style='text-align: center; margin: 30px 0;'>
                                    <a href='" . $myUrl . "/admin/transactions.php?id=" . $id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                        View Transaction
                                    </a>
                                    <a href='" . $myUrl . "/admin/users.php?id=" . $user_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                        View User Profile
                                    </a>
                                </div>

                                <!-- Support Section -->
                                <div class='support-section'>
                                    <p class='support-text'>Transaction processing complete.</p>
                                    <p class='support-text'>No further action required.</p>
                                </div>
                            </div>";

        // Send admin notification
        require_once("../proccess/admin_mailer.php");
        
        echo json_encode(array('success' => true, 'message' => 'Transaction processed successfully'));
    } else {
        echo json_encode(array('success' => false, 'message' => 'Failed to process transaction'));
    }
} else {
    echo json_encode(array('success' => false, 'message' => 'Transaction not found or already processed'));
}
?>