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

// Get notification settings
$settings = [
    'email_notifications' => isset($_POST['email_notifications']) ? 1 : 0,
    'notify_login' => isset($_POST['notify_login']) ? 1 : 0,
    'notify_withdrawal' => isset($_POST['notify_withdrawal']) ? 1 : 0,
    'notify_deposit' => isset($_POST['notify_deposit']) ? 1 : 0,
    'notify_trade' => isset($_POST['notify_trade']) ? 1 : 0,
    'require_2fa_withdrawal' => isset($_POST['require_2fa_withdrawal']) ? 1 : 0
];

// 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 
                   email_notifications = '{$settings['email_notifications']}',
                   notify_login = '{$settings['notify_login']}',
                   notify_withdrawal = '{$settings['notify_withdrawal']}',
                   notify_deposit = '{$settings['notify_deposit']}',
                   notify_trade = '{$settings['notify_trade']}',
                   require_2fa_withdrawal = '{$settings['require_2fa_withdrawal']}',
                   updated_at = NOW()
                   WHERE user_id = '$user_id'";
} else {
    // Insert new record
    $update_sql = "INSERT INTO user_security 
                   (user_id, email_notifications, notify_login, notify_withdrawal, 
                    notify_deposit, notify_trade, require_2fa_withdrawal, created_at, updated_at)
                   VALUES ('$user_id', '{$settings['email_notifications']}', '{$settings['notify_login']}', 
                           '{$settings['notify_withdrawal']}', '{$settings['notify_deposit']}', 
                           '{$settings['notify_trade']}', '{$settings['require_2fa_withdrawal']}', 
                           NOW(), NOW())";
}

if (mysqli_query($conn, $update_sql)) {
    echo json_encode(['success' => true, 'message' => 'Notification preferences updated']);
} else {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . mysqli_error($conn)]);
}
?>