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

if (empty($_POST['pin']) || empty($_POST['confirm_pin'])) {
    echo json_encode(['success' => false, 'message' => 'PIN and confirmation required']);
    exit;
}

$pin = $_POST['pin'];
$confirm_pin = $_POST['confirm_pin'];

// Validate PIN
if (!preg_match('/^\d{6}$/', $pin)) {
    echo json_encode(['success' => false, 'message' => 'PIN must be exactly 6 digits']);
    exit;
}

if ($pin !== $confirm_pin) {
    echo json_encode(['success' => false, 'message' => 'PINs do not match']);
    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 wallet balance information
$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;

// 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 current security settings
$securityQuery = mysqli_query($conn, "SELECT * FROM user_security WHERE user_id = '$user_id'");
$has_existing_pin = mysqli_num_rows($securityQuery) > 0;
$action_type = $has_existing_pin ? 'Updated' : 'Set';

// Hash PIN
$hashed_pin = password_hash($pin, PASSWORD_DEFAULT);

// Check if security record exists
$check_sql = "SELECT id FROM user_security WHERE user_id = '$user_id'";
$check_result = mysqli_query($conn, $check_sql);

if (mysqli_num_rows($check_result) > 0) {
    // Update existing record
    $update_sql = "UPDATE user_security SET 
                   withdrawal_pin = '$hashed_pin',
                   updated_at = NOW()
                   WHERE user_id = '$user_id'";
} else {
    // Insert new record
    $update_sql = "INSERT INTO user_security 
                   (user_id, withdrawal_pin, created_at, updated_at)
                   VALUES ('$user_id', '$hashed_pin', NOW(), NOW())";
}

if (mysqli_query($conn, $update_sql)) {
    $security_id = mysqli_insert_id($conn);
    
    // NOTIFICATION: Withdrawal PIN Set/Updated (USER)
    $mail_subject = "Withdrawal PIN " . $action_type . " Successfully";
    $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 PIN has been " . strtolower($action_type) . " successfully!</strong><br>
                            Your withdrawal security is now enhanced with an additional protection layer.
                        </p>

                        <!-- Security Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Security Action:</strong> Withdrawal PIN " . $action_type . "<br>
                                <strong>Date & Time:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Current Wallet Balance:</strong> $" . number_format($wallet_balance, 2) . "<br>
                                <strong>PIN Status:</strong> <span style='color: #28a745; font-weight: bold;'>ACTIVE</span><br>
                                <strong>PIN Type:</strong> 6-digit numeric<br>
                                <strong>Action Type:</strong> " . ($has_existing_pin ? 'PIN Update' : 'Initial PIN Setup') . "<br>
                                <strong>Setup Location:</strong> " . $user_ip . "<br>
                                <strong>Device:</strong> " . $device . " (" . $browser . ")
                            </div>
                        </div>

                        <!-- What PIN Protects -->
                        <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #0056b3;'>💰 What Your Withdrawal PIN Protects</h4>
                            <p style='color: #0056b3;'>
                                Your 6-digit PIN is required for:<br>
                                • All withdrawal requests<br>
                                • Changing withdrawal limits<br>
                                • Modifying withdrawal methods<br>
                                • Security-sensitive wallet operations
                            </p>
                        </div>

                        <!-- Security Level Enhancement -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>🔒 Security Level Enhanced</h3>
                            <p style='color: #6c757d;'>With this PIN, your account now has:</p>
                            <ul style='color: #6c757d;'>
                                <li><strong>Two-factor security</strong> for withdrawals</li>
                                <li>Protection against unauthorized fund transfers</li>
                                <li>Additional verification for sensitive operations</li>
                                <li>Peace of mind for your trading funds</li>
                            </ul>
                        </div>

                        <!-- IMPORTANT Security Notes -->
                        <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>NEVER share your withdrawal PIN with anyone</strong></li>
                                <li><strong>" . $sitename . " staff will NEVER ask for your PIN</strong></li>
                                <li>Do not use easy-to-guess PINs (123456, 000000, birth dates)</li>
                                <li>Change your PIN every 3 months for maximum security</li>
                                <li>If you forget your PIN, use the secure reset process</li>
                                <li>Your PIN is different from your login password</li>
                            </ul>
                        </div>

                        <!-- What If You Didn't Do This -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>🚨 If You Didn't " . $action_type . " This PIN</h4>
                            <p style='color: #856404;'>
                                If you did not " . strtolower($action_type) . " this withdrawal PIN:<br>
                                1. <strong>IMMEDIATELY</strong> change your account password<br>
                                2. Enable two-factor authentication<br>
                                3. Contact our security team at <strong>security@" . parse_url($myUrl, PHP_URL_HOST) . "</strong><br>
                                4. Monitor your account for unauthorized activity
                            </p>
                        </div>

                        <!-- Action Buttons -->
                        <div style='text-align: center; margin: 30px 0;'>
                            <a href='" . $myUrl . "/wallet.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;'>
                                Go to Wallet
                            </a>
                            <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 Settings
                            </a>
                        </div>

                        <!-- Support Section -->
                        <div class='support-section'>
                            <p class='support-text'>Need help with withdrawal security?</p>
                            <a href='" . $myUrl . "/support.php?category=withdrawals' class='support-link'>Contact Withdrawal Support</a>
                        </div>
                    </div>";

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

    // NOTIFICATION: Withdrawal PIN Set/Updated (ADMIN - Security Alert)
    $admin_mail_subject = "Security Alert: Withdrawal PIN " . $action_type . " - User ID: " . $user_id;
    $admin_mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Security Alert: Withdrawal PIN " . $action_type . "</h2>
                            
                            <p class='message'>
                                A user has " . strtolower($action_type) . " their withdrawal security PIN.
                            </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 " . $action_type . "<br>
                                    <strong>Previous PIN Status:</strong> " . ($has_existing_pin ? 'Already Set' : 'Not Set') . "<br>
                                    <strong>Date & Time:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>User IP Address:</strong> " . $user_ip . "<br>
                                    <strong>Location:</strong> " . get_location_from_ip($user_ip) . "<br>
                                    <strong>Device:</strong> " . $device . "<br>
                                    <strong>Browser:</strong> " . $browser . "<br>
                                    <strong>Wallet Balance:</strong> $" . number_format($wallet_balance, 2) . "<br>
                                    <strong>Security ID:</strong> " . $security_id . "
                                </div>
                            </div>

                            <!-- Security Risk Assessment -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>Security Assessment</h3>
                                <p style='color: #6c757d;'>
                                    <strong>Risk Level:</strong> <span style='color: #28a745;'>LOW</span><br>
                                    <strong>Action Type:</strong> " . ($has_existing_pin ? 'PIN Update' : 'Initial Security Setup') . "<br>
                                    <strong>User Behavior:</strong> " . ($has_existing_pin ? 'Regular security maintenance' : 'Setting up security features') . "<br>
                                    <strong>Withdrawal History:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as count FROM withdrawals WHERE user_id='$user_id'"))['count'] ?? 0) . " withdrawals<br>
                                    <strong>Recent Withdrawals:</strong> $" . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT SUM(amount) as total FROM withdrawals 
                                             WHERE user_id='$user_id' AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"))['total'] ?? 0) . " (7 days)
                                </p>
                            </div>

                            <!-- Security Pattern Analysis -->
                            <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0056b3;'>📊 Security Pattern Analysis</h4>
                                <p style='color: #0056b3;'>
                                    <strong>Account Age:</strong> " . (isset($userData['created_at']) ? 
                                        round((time() - strtotime($userData['created_at'])) / (60 * 60 * 24)) . ' days' : 'N/A') . "<br>
                                    <strong>2FA Status:</strong> " . (isset($userData['two_factor_enabled']) && $userData['two_factor_enabled'] == 1 ? 'Enabled' : 'Disabled') . "<br>
                                    <strong>Email Verified:</strong> " . (isset($userData['email_verified']) && $userData['email_verified'] == 1 ? 'Yes' : 'No') . "<br>
                                    <strong>Security Actions (30 days):</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as actions FROM security_logs 
                                             WHERE user_id='$user_id' AND action_type LIKE '%PIN%' 
                                             AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)"))['actions'] ?? 0) . "
                                </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/withdrawals.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 Withdrawals
                                </a>
                                <a href='" . $myUrl . "/admin/security-logs.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;'>
                                    Security Logs
                                </a>
                            </div>

                            <!-- Notes -->
                            <div class='support-section'>
                                <p class='support-text'>This is an automated security notification.</p>
                                <p class='support-text'>Monitor for unusual withdrawal patterns after PIN changes.</p>
                            </div>
                        </div>";

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

    echo json_encode(['success' => true, 'message' => 'Withdrawal PIN set successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . mysqli_error($conn)]);
}

// Helper functions for device/browser detection
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';
}
?>