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

// Check if PIN is set
$sql = "SELECT withdrawal_pin FROM user_security WHERE user_id = '$user_id'";
$result = mysqli_query($conn, $sql);
$security = mysqli_fetch_assoc($result);

if (!$security || empty($security['withdrawal_pin'])) {
    echo json_encode(['success' => false, 'message' => 'No PIN set']);
    exit;
}

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

// Get IP address for security notification
$user_ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$browser = get_browser_name($user_agent);
$device = is_mobile_device() ? 'Mobile' : 'Desktop';

// Get wallet balance for context
$walletQuery = mysqli_query($conn, "SELECT balance FROM wallets WHERE user_id='$user_id'");
$walletData = mysqli_fetch_assoc($walletQuery);
$wallet_balance = isset($walletData['balance']) ? floatval($walletData['balance']) : 0;

// Generate reset token
$token = bin2hex(random_bytes(32));
$expires = date('Y-m-d H:i:s', strtotime('+1 hour'));

// Save token
$update_sql = "UPDATE user_security SET 
               pin_reset_token = '$token',
               pin_reset_expires = '$expires',
               updated_at = NOW()
               WHERE user_id = '$user_id'";

if (!mysqli_query($conn, $update_sql)) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . mysqli_error($conn)]);
    exit;
}

// NOTIFICATION: Withdrawal PIN Reset Requested (USER)
$mail_subject = "Withdrawal PIN Reset Requested";
$mail_message = "<!-- Content Section -->
                <div class='email-content'>
                    <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                    
                    <p class='message'>
                        ⚠️ <strong>A withdrawal PIN reset has been requested for your account.</strong><br>
                        If this was you, please use the link below to reset your PIN.
                    </p>

                    <!-- Security Alert -->
                    <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                        <h4 style='color: #856404;'>🔒 Security Alert</h4>
                        <p style='color: #856404;'>
                            <strong>Important:</strong> This PIN reset request was initiated with the following details:
                        </p>
                        <div style='color: #856404;'>
                            <strong>Request Time:</strong> " . date('F j, Y g:i A') . "<br>
                            <strong>IP Address:</strong> " . $user_ip . "<br>
                            <strong>Device:</strong> " . $device . " (" . $browser . ")<br>
                            <strong>Wallet Balance:</strong> $" . number_format($wallet_balance, 2) . "<br>
                            <strong>Current Status:</strong> <span style='color: #dc3545; font-weight: bold;'>PIN Reset Pending</span>
                        </div>
                    </div>

                    <!-- Reset Instructions -->
                    <div class='next-steps'>
                        <h3 style='color: #2c3e50;'>Reset Your Withdrawal PIN</h3>
                        <p style='color: #6c757d;'>To reset your withdrawal PIN, click the button below:</p>
                    </div>

                    <!-- Reset Button -->
                    <div style='text-align: center; margin: 30px 0;'>
                        <a href='" . $myUrl . "/reset-pin.php?token=" . $token . "' class='verification-button' style='display: inline-block; padding: 16px 45px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 8px; font-weight: 600; font-size: 16px;'>
                            Reset Withdrawal PIN
                        </a>
                    </div>

                    <!-- Alternative Link -->
                    <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 15px; margin: 20px 0; text-align: center;'>
                        <p style='color: #6c757d; font-size: 14px; margin-bottom: 10px;'>Or copy and paste this link:</p>
                        <p style='background: white; padding: 10px; border-radius: 4px; font-family: monospace; word-break: break-all;'>
                            " . $myUrl . "/reset-pin.php?token=" . $token . "
                        </p>
                    </div>

                    <!-- Important Security Information -->
                    <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                        <h4 style='color: #721c24;'>⚠️ CRITICAL SECURITY INFORMATION</h4>
                        <ul style='color: #721c24;'>
                            <li><strong>This link expires in 1 hour</strong> (" . date('g:i A', strtotime('+1 hour')) . ")</li>
                            <li><strong>DO NOT share this link with anyone</strong></li>
                            <li>" . $sitename . " staff will NEVER ask for this link</li>
                            <li>Your withdrawal PIN protects your funds</li>
                            <li>Choose a strong, memorable PIN</li>
                        </ul>
                    </div>

                    <!-- What Your PIN Protects -->
                    <div class='next-steps'>
                        <h3 style='color: #2c3e50;'>What Your Withdrawal PIN Protects</h3>
                        <p style='color: #6c757d;'>Your withdrawal PIN is required for:</p>
                        <ul style='color: #6c757d;'>
                            <li>Withdrawing funds to external wallets</li>
                            <li>Large transactions</li>
                            <li>Changing withdrawal addresses</li>
                            <li>Exporting transaction history</li>
                            <li>Sensitive account operations</li>
                        </ul>
                    </div>

                    <!-- If Not You -->
                    <div style='background: #d1ecf1; border: 1px solid #bee5eb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                        <h4 style='color: #0c5460;'>❌ If This Wasn't You</h4>
                        <p style='color: #0c5460;'>
                            If you did NOT request a PIN reset:<br>
                            1. <strong>DO NOT click the reset link</strong><br>
                            2. Change your account password immediately<br>
                            3. Enable two-factor authentication<br>
                            4. Contact our security team
                        </p>
                        <div style='text-align: center; margin-top: 15px;'>
                            <a href='" . $myUrl . "/security.php' class='support-link' style='display: inline-block; padding: 10px 20px; background: #dc3545; color: white; text-decoration: none; border-radius: 6px; font-weight: 600;'>
                                🔒 Go to Security Settings
                            </a>
                        </div>
                    </div>

                    <!-- Action Buttons -->
                    <div style='text-align: center; margin: 30px 0;'>
                        <a href='" . $myUrl . "/security.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;'>
                            Security Dashboard
                        </a>
                        <a href='" . $myUrl . "/support.php?category=security' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #17a2b8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                            Contact Security Team
                        </a>
                    </div>

                    <!-- Support Section -->
                    <div class='support-section'>
                        <p class='support-text'>Need help with PIN reset?</p>
                        <a href='" . $myUrl . "/help/withdrawal-pin' class='support-link'>View PIN Reset Guide</a>
                    </div>
                </div>";

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

// NOTIFICATION: Withdrawal PIN Reset Request (ADMIN - Security Alert)
$admin_mail_subject = "SECURITY: Withdrawal PIN Reset Request - User ID: " . $user_id;
$admin_mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>⚠️ Security Alert: Withdrawal PIN Reset Request</h2>
                        
                        <p class='message'>
                            A user has requested to reset their withdrawal PIN. This is a high-security action that requires monitoring.
                        </p>

                        <!-- User & Security Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>User ID:</strong> " . $user_id . "<br>
                                <strong>User Name:</strong> " . $first_name . " " . $userData['last_name'] . "<br>
                                <strong>User Email:</strong> " . $email . "<br>
                                <strong>Action:</strong> Withdrawal PIN Reset Request<br>
                                <strong>Request Time:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Expires At:</strong> " . date('F j, Y g:i A', strtotime('+1 hour')) . "<br>
                                <strong>User IP Address:</strong> " . $user_ip . "<br>
                                <strong>Location:</strong> " . get_location_from_ip($user_ip) . "<br>
                                <strong>Device:</strong> " . $device . " (" . $browser . ")<br>
                                <strong>Wallet Balance:</strong> $" . number_format($wallet_balance, 2) . "<br>
                                <strong>Reset Token:</strong> " . $token . "<br>
                                <strong>Risk Level:</strong> <span style='color: #ffc107; font-weight: bold;'>MEDIUM</span>
                            </div>
                        </div>

                        <!-- Recent Security Activities -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>📋 Recent Security Activities</h4>
                            <p style='color: #856404;'>
                                <strong>Last PIN Reset:</strong> " . 
                                    (mysqli_fetch_assoc(mysqli_query($conn, 
                                        "SELECT updated_at FROM user_security 
                                         WHERE user_id='$user_id' AND pin_reset_token IS NOT NULL 
                                         ORDER BY updated_at DESC LIMIT 1,1"))['updated_at'] ?? 'Never') . "<br>
                                <strong>Last Login:</strong> " . (isset($userData['last_login']) ? date('F j, Y g:i A', strtotime($userData['last_login'])) : 'N/A') . "<br>
                                <strong>Failed Login Attempts (24h):</strong> " . 
                                    (mysqli_fetch_assoc(mysqli_query($conn, 
                                        "SELECT COUNT(*) as attempts FROM login_attempts 
                                         WHERE user_id='$user_id' AND success=0 
                                         AND attempted_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)"))['attempts'] ?? 0) . "<br>
                                <strong>2FA Status:</strong> " . (isset($userData['two_factor_enabled']) && $userData['two_factor_enabled'] == 1 ? 'Enabled' : 'Disabled') . "
                            </p>
                        </div>

                        <!-- Suspicious Activity Check -->
                        <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #721c24;'>🔍 Suspicious Activity Indicators</h4>
                            <p style='color: #721c24;'>
                                <strong>Check for:</strong><br>
                                • Multiple PIN reset requests in short period<br>
                                • IP address from unusual location<br>
                                • Recent password change<br>
                                • Unusual withdrawal patterns<br>
                                • Account access from new device
                            </p>
                        </div>

                        <!-- Admin Actions -->
                        <div style='text-align: center; margin: 30px 0;'>
                            <a href='" . $myUrl . "/admin/users.php?id=" . $user_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 User Profile
                            </a>
                            <a href='" . $myUrl . "/admin/security-logs.php?user_id=" . $user_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #dc3545; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                Security Audit
                            </a>
                            <a href='" . $myUrl . "/admin/transactions.php?user_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 Transactions
                            </a>
                        </div>

                        <!-- Security Notes -->
                        <div class='support-section'>
                            <p class='support-text'><strong>Security Protocol:</strong></p>
                            <p class='support-text'>
                                • Monitor this user's activity for 24 hours<br>
                                • Flag if multiple reset attempts occur<br>
                                • Check for unusual withdrawal patterns<br>
                                • Verify 2FA status
                            </p>
                        </div>
                    </div>";

// Send admin notification
require_once("../proccess/admin_mailer.php");

echo json_encode(['success' => true, 'message' => 'Reset link sent to your email']);

// Helper functions
function get_browser_name($user_agent) {
    if (strpos($user_agent, 'Chrome') !== false) return 'Chrome';
    if (strpos($user_agent, 'Firefox') !== false) return 'Firefox';
    if (strpos($user_agent, 'Safari') !== false) return 'Safari';
    if (strpos($user_agent, 'Edge') !== false) return 'Edge';
    if (strpos($user_agent, 'Opera') !== false) return 'Opera';
    return 'Unknown Browser';
}

function is_mobile_device() {
    $mobile_agents = array(
        'Android', 'webOS', 'iPhone', 'iPad', 'iPod', 'BlackBerry', 
        'Windows Phone', 'Mobile', 'Tablet'
    );
    
    foreach ($mobile_agents as $agent) {
        if (stripos($_SERVER['HTTP_USER_AGENT'], $agent) !== false) {
            return true;
        }
    }
    return false;
}

function get_location_from_ip($ip) {
    if ($ip == '127.0.0.1' || $ip == '::1') {
        return 'Localhost';
    }
    return 'Location data not available';
}
?>