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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die(json_encode(['success' => false, 'message' => 'Invalid request method']));
}

if($userStatus !== 'verified') {
    die(json_encode(['success' => false, 'message' => 'Account must be verified to withdraw']));
    exit;
}

// Validate required fields
$required = ['amount', 'destination_address'];
foreach ($required as $field) {
    if (empty($_POST[$field])) {
        die(json_encode(['success' => false, 'message' => "Missing required field: $field"]));
    }
}

// Get withdrawal settings
$settings_sql = "SELECT * FROM system_settings WHERE setting_key IN ('withdrawal_fee', 'min_withdrawal', 'max_withdrawal', 'usdt_network')";
$settings_result = mysqli_query($conn, $settings_sql);
$settings = [];
while ($row = mysqli_fetch_assoc($settings_result)) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

$withdrawal_fee = isset($settings['withdrawal_fee']) ? floatval($settings['withdrawal_fee']) : 1.0;
$min_withdrawal = isset($settings['min_withdrawal']) ? floatval($settings['min_withdrawal']) : 10.0;
$max_withdrawal = isset($settings['max_withdrawal']) ? floatval($settings['max_withdrawal']) : 10000.0;
$usdt_network = isset($settings['usdt_network']) ? $settings['usdt_network'] : 'TRC20';

// Get user details for notification
$userQuery = mysqli_query($conn, "SELECT first_name, last_name, email, available_balance FROM users WHERE id='$user_id'");
$userData = mysqli_fetch_assoc($userQuery);
$first_name = $userData['first_name'];
$email = $userData['email'];
$availableBalance = floatval($userData['available_balance']);

// Get IP address for security notification
$user_ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];

// Validate amount
$amount = floatval($_POST['amount']);
if ($amount < $min_withdrawal) {
    die(json_encode(['success' => false, 'message' => "Minimum withdrawal amount is $" . number_format($min_withdrawal, 2)]));
}

if ($amount > $max_withdrawal) {
    die(json_encode(['success' => false, 'message' => "Maximum withdrawal amount is $" . number_format($max_withdrawal, 2)]));
}

// Check available balance
if ($amount > $availableBalance) {
    die(json_encode(['success' => false, 'message' => 'Insufficient balance. Available: $' . number_format($availableBalance, 2)]));
}

// Validate destination address
$destination_address = trim($_POST['destination_address']);
if (strlen($destination_address) < 10) {
    die(json_encode(['success' => false, 'message' => 'Invalid destination address']));
}

// Check network confirmation
if (!isset($_POST['confirm_network']) || $_POST['confirm_network'] !== 'on') {
    die(json_encode(['success' => false, 'message' => 'You must confirm the network type']));
}

// Calculate fees
$fee = $amount * ($withdrawal_fee / 100);
$total_amount = $amount - $fee;

// Check if user has a pending withdrawal
$pending_sql = "SELECT id FROM withdrawals WHERE user_id = '$user_id' AND status IN ('pending', 'processing')";
$pending_result = mysqli_query($conn, $pending_sql);
if (mysqli_num_rows($pending_result) > 0) {
    die(json_encode(['success' => false, 'message' => 'You already have a pending withdrawal. Please wait for it to complete.']));
}

// Start transaction
mysqli_begin_transaction($conn);

try {
    // Insert withdrawal record
    $insert_sql = "INSERT INTO withdrawals (user_id, amount, fee, total_amount, destination_address, status, created_at) 
                   VALUES ('$user_id', '$amount', '$fee', '$total_amount', '$destination_address', 'pending', NOW())";
    
    if (!mysqli_query($conn, $insert_sql)) {
        throw new Exception('Failed to create withdrawal record: ' . mysqli_error($conn));
    }
    
    $withdrawal_id = mysqli_insert_id($conn);
    
    // Deduct amount from user's available balance
    $new_balance = $availableBalance - $amount;
    $update_sql = "UPDATE users SET available_balance = '$new_balance' WHERE id = '$user_id'";
    if (!mysqli_query($conn, $update_sql)) {
        throw new Exception('Failed to update user balance: ' . mysqli_error($conn));
    }
    
    // Create transaction record
    $transaction_sql = "INSERT INTO transactions (user_id, type, amount, description, status, currency, created_at) 
                       VALUES ('$user_id', 'withdrawal', '$amount', 'USDT Withdrawal (Pending)', 'pending', 'USDT', NOW())";
    if (!mysqli_query($conn, $transaction_sql)) {
        throw new Exception('Failed to create transaction record: ' . mysqli_error($conn));
    }
    
    // Commit transaction
    mysqli_commit($conn);
    
    // NOTIFICATION: Withdrawal Request Submitted (USER)
    $mail_subject = "Withdrawal Request Submitted - #WD" . $withdrawal_id;
    $mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                        
                        <p class='message'>
                            ✅ <strong>Your withdrawal request has been submitted successfully!</strong><br>
                            We have received your request and will process it within 24 hours.
                        </p>

                        <!-- Withdrawal Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Withdrawal ID:</strong> <span style='color: #2F2CD8; font-weight: bold;'>WD-" . $withdrawal_id . "</span><br>
                                <strong>Requested Amount:</strong> $" . number_format($amount, 2) . "<br>
                                <strong>Withdrawal Fee (" . $withdrawal_fee . "%):</strong> $" . number_format($fee, 2) . "<br>
                                <strong>Amount to Receive:</strong> $" . number_format($total_amount, 2) . "<br>
                                <strong>Network:</strong> " . $usdt_network . "<br>
                                <strong>Destination Address:</strong> <span style='font-family: monospace;'>" . htmlspecialchars(substr($destination_address, 0, 20)) . "...</span><br>
                                <strong>Submission Date:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Current Status:</strong> <span style='color: #ffc107; font-weight: bold;'>PENDING REVIEW</span><br>
                                <strong>Previous Balance:</strong> $" . number_format($availableBalance, 2) . "<br>
                                <strong>New Available Balance:</strong> $" . number_format($new_balance, 2) . "
                            </div>
                        </div>

                        <!-- Processing Timeline -->
                        <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #0056b3;'>⏰ Processing Timeline</h4>
                            <p style='color: #0056b3;'>
                                <strong>Step 1: Review (0-12 hours)</strong> - Manual verification by security team<br>
                                <strong>Step 2: Approval (12-24 hours)</strong> - Approval by finance department<br>
                                <strong>Step 3: Processing (0-2 hours)</strong> - Crypto transfer initiated<br>
                                <strong>Step 4: Completed</strong> - Funds sent to your wallet
                            </p>
                        </div>

                        <!-- Important Notes -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>📋 Important Information</h4>
                            <ul style='color: #856404;'>
                                <li>Withdrawals are processed within <strong>24 hours</strong> (business days)</li>
                                <li>Weekend requests may take longer</li>
                                <li>You will receive email updates at each stage</li>
                                <li>Network confirmation times vary (10-60 minutes)</li>
                                <li>Double-check your destination address</li>
                            </ul>
                        </div>

                        <!-- Security Check -->
                        <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #721c24;'>🔒 Security Verification</h4>
                            <p style='color: #721c24;'>
                                <strong>Request initiated from:</strong><br>
                                • IP Address: " . $user_ip . "<br>
                                • Time: " . date('g:i A') . "<br><br>
                                <strong>If you did NOT make this request:</strong><br>
                                1. Contact support immediately<br>
                                2. Change your password<br>
                                3. Enable 2FA if not already enabled
                            </p>
                        </div>

                        <!-- Action Buttons -->
                        <div style='text-align: center; margin: 30px 0;'>
                            <a href='" . $myUrl . "/withdrawals.php?id=" . $withdrawal_id . "' 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 Withdrawal Details
                            </a>
                            <a href='" . $myUrl . "/transactions.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;'>
                                View All Transactions
                            </a>
                        </div>

                        <!-- Support Section -->
                        <div class='support-section'>
                            <p class='support-text'>Questions about your withdrawal?</p>
                            <a href='" . $myUrl . "/support.php?category=withdrawal&ref=WD-" . $withdrawal_id . "' class='support-link'>Contact Withdrawal Support</a>
                        </div>
                    </div>";

    // Send user notification
    require_once("../proccess/mail_sender.php");

    // NOTIFICATION: New Withdrawal Request (ADMIN)
    $admin_mail_subject = "🚨 NEW WITHDRAWAL REQUEST - WD-" . $withdrawal_id . " - $" . number_format($amount, 2);
    $admin_mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>🚨 New Withdrawal Request</h2>
                            
                            <p class='message'>
                                A user has submitted a new withdrawal request requiring manual review.
                            </p>

                            <!-- Withdrawal Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>Withdrawal ID:</strong> <span style='color: #dc3545; font-weight: bold;'>WD-" . $withdrawal_id . "</span><br>
                                    <strong>User ID:</strong> " . $user_id . "<br>
                                    <strong>User Name:</strong> " . $first_name . " " . $userData['last_name'] . "<br>
                                    <strong>User Email:</strong> " . $email . "<br>
                                    <strong>Amount:</strong> <span style='color: #198754; font-weight: bold;'>$" . number_format($amount, 2) . "</span><br>
                                    <strong>Fee (" . $withdrawal_fee . "%):</strong> $" . number_format($fee, 2) . "<br>
                                    <strong>Net Amount:</strong> $" . number_format($total_amount, 2) . "<br>
                                    <strong>Network:</strong> " . $usdt_network . "<br>
                                    <strong>Destination Address:</strong><br>
                                    <span style='font-family: monospace; background: #f8f9fa; padding: 5px; border-radius: 4px; display: inline-block; margin-top: 5px;'>" . htmlspecialchars($destination_address) . "</span><br>
                                    <strong>Submission Time:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>User IP:</strong> " . $user_ip . "<br>
                                    <strong>Previous Balance:</strong> $" . number_format($availableBalance, 2) . "<br>
                                    <strong>New Balance:</strong> $" . number_format($new_balance, 2) . "<br>
                                    <strong>Status:</strong> <span style='color: #ffc107; font-weight: bold;'>PENDING REVIEW</span>
                                </div>
                            </div>

                            <!-- User Withdrawal History -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>User Withdrawal History</h3>
                                <p style='color: #6c757d;'>
                                    <strong>Total Withdrawals:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as total FROM withdrawals WHERE user_id='$user_id'"))['total'] ?? 0) . "<br>
                                    <strong>Total Withdrawn:</strong> $" . 
                                        (number_format(mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COALESCE(SUM(amount), 0) as total FROM withdrawals 
                                             WHERE user_id='$user_id' AND status='completed'"))['total'] ?? 0, 2)) . "<br>
                                    <strong>Pending Withdrawals:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as pending FROM withdrawals 
                                             WHERE user_id='$user_id' AND status IN ('pending', 'processing')"))['pending'] ?? 0) . "<br>
                                    <strong>Last Withdrawal:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT created_at FROM withdrawals 
                                             WHERE user_id='$user_id' AND status='completed' 
                                             ORDER BY created_at DESC LIMIT 1"))['created_at'] ?? 'Never') . "
                                </p>
                            </div>

                            <!-- Risk Assessment -->
                            <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #856404;'>⚠️ Risk Assessment</h4>
                                <p style='color: #856404;'>
                                    <strong>Check for:</strong><br>
                                    • First-time withdrawal? " . ((mysqli_fetch_assoc(mysqli_query($conn, 
                                        "SELECT COUNT(*) as count FROM withdrawals WHERE user_id='$user_id'"))['count'] ?? 0) == 0 ? 'YES' : 'NO') . "<br>
                                    • Large amount relative to balance? " . ($amount > ($availableBalance * 0.5) ? 'YES' : 'NO') . "<br>
                                    • New destination address? (Check user history)<br>
                                    • Unusual withdrawal time?<br>
                                    • Account verification status: " . $userStatus . "
                                </p>
                            </div>

                            <!-- Admin Actions -->
                            <div style='text-align: center; margin: 30px 0;'>
                                <a href='" . $myUrl . "/admin/withdrawals.php?id=" . $withdrawal_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;'>
                                    Review Withdrawal
                                </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>
                                <a href='" . $myUrl . "/admin/transactions.php?user_id=" . $user_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #6f42c1; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                    Transaction History
                                </a>
                            </div>

                            <!-- Processing Notes -->
                            <div style='background: #d1ecf1; border: 1px solid #bee5eb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0c5460;'>📝 Processing Notes</h4>
                                <p style='color: #0c5460;'>
                                    <strong>SLA:</strong> Process within 24 hours<br>
                                    <strong>Priority:</strong> " . ($amount > 5000 ? 'HIGH' : ($amount > 1000 ? 'MEDIUM' : 'STANDARD')) . "<br>
                                    <strong>Required Checks:</strong> KYC, AML, Address Verification<br>
                                    <strong>Network Fee Budget:</strong> $5-20 (depending on network congestion)
                                </p>
                            </div>

                            <!-- Support Section -->
                            <div class='support-section'>
                                <p class='support-text'>Withdrawal requires manual review and approval.</p>
                                <p class='support-text'>Process within 24 hours to maintain SLA.</p>
                            </div>
                        </div>";

    // Send admin notification
    require_once("../proccess/admin_mailer.php");
    
    echo json_encode([
        'success' => true, 
        'message' => 'Withdrawal request submitted successfully. It will be processed within 24 hours.',
        'withdrawal_id' => $withdrawal_id
    ]);
    
} catch (Exception $e) {
    // Rollback transaction on error
    mysqli_rollback($conn);
    
    echo json_encode([
        'success' => false, 
        'message' => 'Withdrawal failed: ' . $e->getMessage()
    ]);
}
?>