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

// Admin PIN for confirmation
$admin_pin = "1234";

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $submitted_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';
    $action = isset($_POST['action']) ? $_POST['action'] : '';
    
    // Get admin details for notification
    $admin_id = $_SESSION['admin_id'] ?? $_SESSION['user_id'] ?? 1;
    $adminQuery = mysqli_query($conn, "SELECT first_name, email FROM users WHERE id='$admin_id'");
    $adminData = mysqli_fetch_assoc($adminQuery);
    $admin_name = $adminData['first_name'] ?? 'Administrator';
    $admin_email = $adminData['email'] ?? 'admin@system.com';
    
    // Verify PIN
    if ($submitted_pin !== $admin_pin) {
        $error = "Invalid PIN. Changes not saved.";
    } else {
        switch ($action) {
            case 'save_general_settings':
                // Get old settings for comparison
                $old_site_name = getSetting($conn, 'site_name', '');
                $old_maintenance_mode = getSetting($conn, 'maintenance_mode', 0);
                
                // General Settings
                $settings = array(
                    'site_name' => mysqli_real_escape_string($conn, $_POST['site_name']),
                    'site_url' => mysqli_real_escape_string($conn, $_POST['site_url']),
                    'admin_email' => mysqli_real_escape_string($conn, $_POST['admin_email']),
                    'support_email' => mysqli_real_escape_string($conn, $_POST['support_email']),
                    'timezone' => mysqli_real_escape_string($conn, $_POST['timezone']),
                    'maintenance_mode' => isset($_POST['maintenance_mode']) ? 1 : 0,
                    'registration_enabled' => isset($_POST['registration_enabled']) ? 1 : 0,
                    'email_verification' => isset($_POST['email_verification']) ? 1 : 0
                );
                
                foreach ($settings as $key => $value) {
                    saveSetting($conn, $key, $value);
                }
                
                logAdminActivity('General Settings Updated', 'Updated general system settings', 'System Settings');
                
                // NOTIFICATION: General Settings Updated
                $mail_subject = "System Settings Updated - General Settings";
                $mail_message = "<!-- Content Section -->
                                <div class='email-content'>
                                    <h2 class='greeting'>System Settings Updated</h2>
                                    <p class='message'>General system settings have been modified by an administrator.</p>
                                    
                                    <div class='details-section'>
                                        <div class='detail-box'>
                                            <strong>Updated By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                            <strong>Update Time:</strong> " . date('F j, Y g:i A') . "<br>
                                            <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "<br>
                                            <strong>Settings Modified:</strong><br>
                                            &nbsp;&nbsp;• Site Name: " . ($old_site_name != $settings['site_name'] ? "<span style='color: #ffc107;'>Changed to: " . $settings['site_name'] . "</span>" : "<span style='color: #6c757d;'>No change</span>") . "<br>
                                            &nbsp;&nbsp;• Maintenance Mode: " . ($old_maintenance_mode != $settings['maintenance_mode'] ? 
                                                ($settings['maintenance_mode'] == 1 ? "<span style='color: #dc3545;'>ENABLED</span>" : "<span style='color: #28a745;'>DISABLED</span>") : 
                                                "<span style='color: #6c757d;'>No change</span>") . "<br>
                                            &nbsp;&nbsp;• Registration: " . ($settings['registration_enabled'] == 1 ? 'Enabled' : 'Disabled') . "<br>
                                            &nbsp;&nbsp;• Email Verification: " . ($settings['email_verification'] == 1 ? 'Required' : 'Optional') . "
                                        </div>
                                    </div>
                                    
                                    <div style='text-align: center; margin: 30px 0;'>
                                        <a href='" . $myUrl . "/admin/system_settings.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600;'>
                                            View Settings
                                        </a>
                                    </div>
                                </div>";
                
                require_once("../proccess/admin_mailer.php");
                
                $success = "General settings updated successfully!";
                break;
                
            case 'save_trading_settings':
                // Get old settings for comparison
                $old_min_deposit = getSetting($conn, 'min_deposit', 0);
                $old_max_deposit = getSetting($conn, 'max_deposit', 0);
                $old_withdrawal_fee = getSetting($conn, 'withdrawal_fee', 0);
                $old_auto_approve = getSetting($conn, 'auto_approve_deposits', 0);
                
                // Trading Settings
                $settings = array(
                    'min_deposit' => floatval($_POST['min_deposit']),
                    'max_deposit' => floatval($_POST['max_deposit']),
                    'min_withdrawal' => floatval($_POST['min_withdrawal']),
                    'max_withdrawal' => floatval($_POST['max_withdrawal']),
                    'withdrawal_fee' => floatval($_POST['withdrawal_fee']),
                    'trading_fee' => floatval($_POST['trading_fee']),
                    'min_trading_amount' => floatval($_POST['min_trading_amount']),
                    'max_trading_amount' => floatval($_POST['max_trading_amount']),
                    'auto_approve_deposits' => isset($_POST['auto_approve_deposits']) ? 1 : 0,
                    'auto_approve_withdrawals' => isset($_POST['auto_approve_withdrawals']) ? 1 : 0,
                    'usdt_network' => mysqli_real_escape_string($conn, $_POST['usdt_network'])
                );
                
                foreach ($settings as $key => $value) {
                    saveSetting($conn, $key, $value);
                }
                
                logAdminActivity('Trading Settings Updated', 'Updated trading platform settings', 'System Settings');
                
                // NOTIFICATION: Trading Settings Updated
                $mail_subject = "System Settings Updated - Trading Settings";
                $mail_message = "<!-- Content Section -->
                                <div class='email-content'>
                                    <h2 class='greeting'>Trading Settings Updated</h2>
                                    <p class='message'>Trading platform settings have been modified by an administrator.</p>
                                    
                                    <div class='details-section'>
                                        <div class='detail-box'>
                                            <strong>Updated By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                            <strong>Update Time:</strong> " . date('F j, Y g:i A') . "<br>
                                            <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "<br>
                                            <strong>Deposit Limits:</strong> $" . number_format($settings['min_deposit'], 2) . " - $" . number_format($settings['max_deposit'], 2) . "<br>
                                            <strong>Withdrawal Limits:</strong> $" . number_format($settings['min_withdrawal'], 2) . " - $" . number_format($settings['max_withdrawal'], 2) . "<br>
                                            <strong>Withdrawal Fee:</strong> " . $settings['withdrawal_fee'] . "%<br>
                                            <strong>Trading Fee:</strong> " . $settings['trading_fee'] . "%<br>
                                            <strong>Auto Approve Deposits:</strong> " . ($settings['auto_approve_deposits'] == 1 ? 'Enabled' : 'Disabled') . "<br>
                                            <strong>Auto Approve Withdrawals:</strong> " . ($settings['auto_approve_withdrawals'] == 1 ? 'Enabled' : 'Disabled') . "<br>
                                            <strong>USDT Network:</strong> " . $settings['usdt_network'] . "
                                        </div>
                                    </div>
                                    
                                    <div style='background: " . ($settings['auto_approve_withdrawals'] == 1 ? '#fff3cd' : '#e7f3ff') . "; border: 1px solid " . ($settings['auto_approve_withdrawals'] == 1 ? '#ffeaa7' : '#b3d7ff') . "; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                        <h4 style='color: " . ($settings['auto_approve_withdrawals'] == 1 ? '#856404' : '#0056b3') . ";'>⚠️ Important Note</h4>
                                        <p style='color: " . ($settings['auto_approve_withdrawals'] == 1 ? '#856404' : '#0056b3') . ";'>
                                            " . ($settings['auto_approve_withdrawals'] == 1 ? 
                                                'Auto-approve withdrawals is ENABLED. Withdrawals will be processed automatically without admin review.' : 
                                                'Auto-approve withdrawals is DISABLED. All withdrawals require manual admin approval.') . "
                                        </p>
                                    </div>
                                    
                                    <div style='text-align: center; margin: 30px 0;'>
                                        <a href='" . $myUrl . "/admin/system_settings.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600;'>
                                            View Trading Settings
                                        </a>
                                    </div>
                                </div>";
                
                require_once("../proccess/admin_mailer.php");
                
                $success = "Trading settings updated successfully!";
                break;
                
            case 'save_email_settings':
                // Email Settings
                $settings = array(
                    'smtp_host' => mysqli_real_escape_string($conn, $_POST['smtp_host']),
                    'smtp_port' => intval($_POST['smtp_port']),
                    'smtp_username' => mysqli_real_escape_string($conn, $_POST['smtp_username']),
                    'smtp_password' => mysqli_real_escape_string($conn, $_POST['smtp_password']),
                    'smtp_encryption' => mysqli_real_escape_string($conn, $_POST['smtp_encryption']),
                    'from_email' => mysqli_real_escape_string($conn, $_POST['from_email']),
                    'from_name' => mysqli_real_escape_string($conn, $_POST['from_name'])
                );
                
                foreach ($settings as $key => $value) {
                    saveSetting($conn, $key, $value);
                }
                
                // Also update mail_settings table
                $update_mail = "UPDATE mail_settings SET 
                               host = '{$settings['smtp_host']}',
                               username = '{$settings['smtp_username']}',
                               password = '{$settings['smtp_password']}',
                               port = '{$settings['smtp_port']}'
                               WHERE id = 1";
                mysqli_query($conn, $update_mail);
                
                logAdminActivity('Email Settings Updated', 'Updated email server settings', 'System Settings');
                
                // NOTIFICATION: Email Settings Updated
                $mail_subject = "System Settings Updated - Email Settings";
                $mail_message = "<!-- Content Section -->
                                <div class='email-content'>
                                    <h2 class='greeting'>Email Settings Updated</h2>
                                    <p class='message'>Email server settings have been modified by an administrator.</p>
                                    
                                    <div class='details-section'>
                                        <div class='detail-box'>
                                            <strong>Updated By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                            <strong>Update Time:</strong> " . date('F j, Y g:i A') . "<br>
                                            <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "<br>
                                            <strong>SMTP Host:</strong> " . $settings['smtp_host'] . "<br>
                                            <strong>SMTP Port:</strong> " . $settings['smtp_port'] . "<br>
                                            <strong>SMTP Username:</strong> " . $settings['smtp_username'] . "<br>
                                            <strong>SMTP Encryption:</strong> " . $settings['smtp_encryption'] . "<br>
                                            <strong>From Email:</strong> " . $settings['from_email'] . "<br>
                                            <strong>From Name:</strong> " . $settings['from_name'] . "
                                        </div>
                                    </div>
                                    
                                    <div style='background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                        <h4 style='color: #155724;'>📧 Email System Impact</h4>
                                        <p style='color: #155724;'>
                                            All system emails will now be sent using these new SMTP settings.<br>
                                            This affects: registration emails, notifications, password resets, and all automated communications.
                                        </p>
                                    </div>
                                    
                                    <div style='text-align: center; margin: 30px 0;'>
                                        <a href='" . $myUrl . "/admin/test-email.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px; font-weight: 600;'>
                                            Test Email Settings
                                        </a>
                                    </div>
                                </div>";
                
                require_once("../proccess/admin_mailer.php");
                
                $success = "Email settings updated successfully!";
                break;
                
            case 'save_referral_settings':
                // Referral Settings
                $settings = array(
                    'referral_enabled' => isset($_POST['referral_enabled']) ? 1 : 0,
                    'signup_bonus_referrer' => floatval($_POST['signup_bonus_referrer']),
                    'signup_bonus_referred' => floatval($_POST['signup_bonus_referred']),
                    'bot_bonus' => floatval($_POST['bot_bonus']),
                    'max_referral_discount' => floatval($_POST['max_referral_discount']),
                    'discount_per_referral' => floatval($_POST['discount_per_referral']),
                    'min_referral_payout' => floatval($_POST['min_referral_payout'])
                );
                
                foreach ($settings as $key => $value) {
                    saveSetting($conn, $key, $value);
                }
                
                // Also update referral_settings table
                $update_ref = "UPDATE referral_settings SET 
                              signup_bonus_referrer = '{$settings['signup_bonus_referrer']}',
                              signup_bonus_referred = '{$settings['signup_bonus_referred']}',
                              bot_bonus = '{$settings['bot_bonus']}',
                              max_referral_discount = '{$settings['max_referral_discount']}',
                              discount_per_referral = '{$settings['discount_per_referral']}'
                              WHERE id = 1";
                mysqli_query($conn, $update_ref);
                
                logAdminActivity('Referral Settings Updated', 'Updated referral program settings', 'System Settings');
                
                // NOTIFICATION: Referral Settings Updated
                $mail_subject = "System Settings Updated - Referral Program";
                $mail_message = "<!-- Content Section -->
                                <div class='email-content'>
                                    <h2 class='greeting'>Referral Program Settings Updated</h2>
                                    <p class='message'>Referral program settings have been modified by an administrator.</p>
                                    
                                    <div class='details-section'>
                                        <div class='detail-box'>
                                            <strong>Updated By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                            <strong>Update Time:</strong> " . date('F j, Y g:i A') . "<br>
                                            <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "<br>
                                            <strong>Referral Program:</strong> " . ($settings['referral_enabled'] == 1 ? '<span style="color: #28a745;">ENABLED</span>' : '<span style="color: #dc3545;">DISABLED</span>') . "<br>
                                            <strong>Signup Bonus (Referrer):</strong> $" . number_format($settings['signup_bonus_referrer'], 2) . "<br>
                                            <strong>Signup Bonus (Referred):</strong> $" . number_format($settings['signup_bonus_referred'], 2) . "<br>
                                            <strong>Bot Subscription Bonus:</strong> $" . number_format($settings['bot_bonus'], 2) . "<br>
                                            <strong>Discount Per Referral:</strong> " . $settings['discount_per_referral'] . "%<br>
                                            <strong>Max Discount:</strong> " . $settings['max_referral_discount'] . "%<br>
                                            <strong>Minimum Payout:</strong> $" . number_format($settings['min_referral_payout'], 2) . "
                                        </div>
                                    </div>
                                    
                                    <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                        <h4 style='color: #495057;'>👥 User Impact</h4>
                                        <p style='color: #495057;'>
                                            These changes will affect all new and existing referral transactions.<br>
                                            Current users will see updated bonus amounts for future referrals.
                                        </p>
                                    </div>
                                    
                                    <div style='text-align: center; margin: 30px 0;'>
                                        <a href='" . $myUrl . "/admin/referrals.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600;'>
                                            View Referral Reports
                                        </a>
                                    </div>
                                </div>";
                
                require_once("../proccess/admin_mailer.php");
                
                $success = "Referral settings updated successfully!";
                break;
                
            case 'save_security_settings':
                // Security Settings
                $settings = array(
                    'login_attempts' => intval($_POST['login_attempts']),
                    'login_lockout_minutes' => intval($_POST['login_lockout_minutes']),
                    'session_timeout' => intval($_POST['session_timeout']),
                    '2fa_enabled' => isset($_POST['2fa_enabled']) ? 1 : 0,
                    'ip_whitelist' => mysqli_real_escape_string($conn, $_POST['ip_whitelist']),
                    'password_expiry_days' => intval($_POST['password_expiry_days']),
                    'force_ssl' => isset($_POST['force_ssl']) ? 1 : 0,
                    'captcha_enabled' => isset($_POST['captcha_enabled']) ? 1 : 0
                );
                
                foreach ($settings as $key => $value) {
                    saveSetting($conn, $key, $value);
                }
                
                logAdminActivity('Security Settings Updated', 'Updated security settings', 'System Settings');
                
                // NOTIFICATION: Security Settings Updated
                $mail_subject = "⚠️ SECURITY ALERT - System Security Settings Updated";
                $mail_message = "<!-- Content Section -->
                                <div class='email-content'>
                                    <h2 class='greeting' style='color: #dc3545;'>Security Settings Updated</h2>
                                    <p class='message' style='color: #721c24;'>
                                        <strong>CRITICAL:</strong> System security settings have been modified by an administrator.
                                    </p>
                                    
                                    <div class='details-section'>
                                        <div class='detail-box'>
                                            <strong>Updated By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                            <strong>Update Time:</strong> " . date('F j, Y g:i A') . "<br>
                                            <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "<br>
                                            <strong>Login Attempts:</strong> " . $settings['login_attempts'] . " before lockout<br>
                                            <strong>Lockout Duration:</strong> " . $settings['login_lockout_minutes'] . " minutes<br>
                                            <strong>Session Timeout:</strong> " . $settings['session_timeout'] . " minutes<br>
                                            <strong>2FA Authentication:</strong> " . ($settings['2fa_enabled'] == 1 ? '<span style="color: #28a745;">ENABLED</span>' : '<span style="color: #dc3545;">DISABLED</span>') . "<br>
                                            <strong>Password Expiry:</strong> " . $settings['password_expiry_days'] . " days<br>
                                            <strong>Force SSL:</strong> " . ($settings['force_ssl'] == 1 ? 'Enabled' : 'Disabled') . "<br>
                                            <strong>CAPTCHA:</strong> " . ($settings['captcha_enabled'] == 1 ? 'Enabled' : 'Disabled') . "
                                        </div>
                                    </div>
                                    
                                    <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                        <h4 style='color: #721c24;'>🔒 Security Impact</h4>
                                        <p style='color: #721c24;'>
                                            <strong>These changes affect how users access the platform.</strong><br>
                                            • All users will be subject to new security policies<br>
                                            • Active sessions may be affected by timeout changes<br>
                                            • Password policies will apply to all users<br>
                                            • This action has been logged for security audit
                                        </p>
                                    </div>
                                    
                                    <div style='text-align: center; margin: 30px 0;'>
                                        <a href='" . $myUrl . "/admin/security-logs.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #dc3545; color: white; text-decoration: none; border-radius: 6px; font-weight: 600;'>
                                            View Security Logs
                                        </a>
                                    </div>
                                </div>";
                
                require_once("../proccess/admin_mailer.php");
                
                $success = "Security settings updated successfully!";
                break;
        }
    }
}

// Function to save settings
function saveSetting($conn, $key, $value) {
    // Check if setting exists
    $check = "SELECT id FROM system_settings WHERE setting_key = '$key'";
    $result = mysqli_query($conn, $check);
    
    if (mysqli_num_rows($result) > 0) {
        // Update
        $sql = "UPDATE system_settings SET setting_value = '$value', updated_at = NOW() WHERE setting_key = '$key'";
    } else {
        // Insert
        $sql = "INSERT INTO system_settings (setting_key, setting_value, created_at, updated_at) 
                VALUES ('$key', '$value', NOW(), NOW())";
    }
    
    return mysqli_query($conn, $sql);
}

// Function to get setting
function getSetting($conn, $key, $default = '') {
    $sql = "SELECT setting_value FROM system_settings WHERE setting_key = '$key'";
    $result = mysqli_query($conn, $sql);
    
    if ($row = mysqli_fetch_assoc($result)) {
        return $row['setting_value'];
    }
    
    return $default;
}

// Get current mail settings
$mail_sql = "SELECT * FROM mail_settings WHERE id = 1";
$mail_result = mysqli_query($conn, $mail_sql);
$mail_settings = mysqli_fetch_assoc($mail_result);

// Get referral settings
$ref_sql = "SELECT * FROM referral_settings WHERE id = 1";
$ref_result = mysqli_query($conn, $ref_sql);
$ref_settings = mysqli_fetch_assoc($ref_result);
?>

<!DOCTYPE html>
<html lang="en">
  	
	
	<body class="hold-transition dark-skin sidebar-mini theme-primary fixed">
		
		<div class="wrapper">
		  	<div id="loader"></div>
		  	
		  <?php include('includes/header.php') ?>

		  <?php include('includes/sidebar.php') ?>

		  	<!-- Content Wrapper. Contains page content -->
			<div class="content-wrapper">
				<div class="container-full">
					<!-- Main content -->
					<section class="content">
						<div class="row">
							<div class="col-12">
								<div class="box">
									<div class="box-header">
										<h4 class="box-title"><i class="fas fa-cogs me-2"></i>System Settings</h4>
										<div class="box-controls pull-right">
											<button class="btn btn-primary" onclick="testEmailSettings()">
												<i class="fas fa-envelope me-1"></i> Test Email
											</button>
										</div>
									</div>
									<div class="box-body">
										
										<?php if (isset($success)): ?>
											<div class="alert alert-success alert-dismissible fade show">
												<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
												<i class="fas fa-check-circle me-2"></i> <?php echo $success; ?>
											</div>
										<?php endif; ?>
										
										<?php if (isset($error)): ?>
											<div class="alert alert-danger alert-dismissible fade show">
												<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
												<i class="fas fa-exclamation-circle me-2"></i> <?php echo $error; ?>
											</div>
										<?php endif; ?>
										
										<!-- Settings Tabs -->
										<ul class="nav nav-tabs" role="tablist">
											<li class="nav-item">
												<a class="nav-link active" data-bs-toggle="tab" href="#general">
													<i class="fas fa-globe me-2"></i> General
												</a>
											</li>
											<li class="nav-item">
												<a class="nav-link" data-bs-toggle="tab" href="#trading">
													<i class="fas fa-chart-line me-2"></i> Trading
												</a>
											</li>
											<li class="nav-item">
												<a class="nav-link" data-bs-toggle="tab" href="#email">
													<i class="fas fa-envelope me-2"></i> Email
												</a>
											</li>
											<li class="nav-item">
												<a class="nav-link" data-bs-toggle="tab" href="#referral">
													<i class="fas fa-users me-2"></i> Referral
												</a>
											</li>
											<li class="nav-item">
												<a class="nav-link" data-bs-toggle="tab" href="#security">
													<i class="fas fa-shield-alt me-2"></i> Security
												</a>
											</li>
											<li class="nav-item">
												<a class="nav-link" data-bs-toggle="tab" href="#backup">
													<i class="fas fa-database me-2"></i> Backup
												</a>
											</li>
										</ul>
										
										<div class="tab-content mt-3">
											<!-- General Settings Tab -->
											<div class="tab-pane fade show active" id="general">
												<form method="POST">
													<input type="hidden" name="action" value="save_general_settings">
													
													<div class="row">
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">Site Name <span class="text-danger">*</span></label>
																<input type="text" class="form-control" name="site_name" value="<?php echo getSetting($conn, 'site_name', 'AI Trading Platform'); ?>" required>
															</div>
														</div>
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">Site URL <span class="text-danger">*</span></label>
																<input type="url" class="form-control" name="site_url" value="<?php echo getSetting($conn, 'site_url', 'https://yourplatform.com'); ?>" required>
															</div>
														</div>
													</div>
													
													<div class="row">
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">Admin Email <span class="text-danger">*</span></label>
																<input type="email" class="form-control" name="admin_email" value="<?php echo getSetting($conn, 'admin_email', 'admin@yourplatform.com'); ?>" required>
															</div>
														</div>
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">Support Email <span class="text-danger">*</span></label>
																<input type="email" class="form-control" name="support_email" value="<?php echo getSetting($conn, 'support_email', 'support@yourplatform.com'); ?>" required>
															</div>
														</div>
													</div>
													
													<div class="row">
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">Timezone <span class="text-danger">*</span></label>
																<select class="form-control" name="timezone" required>
																	<option value="UTC" <?php echo getSetting($conn, 'timezone') == 'UTC' ? 'selected' : ''; ?>>UTC</option>
																	<option value="America/New_York" <?php echo getSetting($conn, 'timezone') == 'America/New_York' ? 'selected' : ''; ?>>Eastern Time (ET)</option>
																	<option value="Europe/London" <?php echo getSetting($conn, 'timezone') == 'Europe/London' ? 'selected' : ''; ?>>London</option>
																	<option value="Asia/Singapore" <?php echo getSetting($conn, 'timezone') == 'Asia/Singapore' ? 'selected' : ''; ?>>Singapore</option>
																	<option value="Africa/Johannesburg" <?php echo getSetting($conn, 'timezone') == 'Africa/Johannesburg' ? 'selected' : ''; ?>>South Africa</option>
																</select>
															</div>
														</div>
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">Logo URL</label>
																<input type="url" class="form-control" name="logo_url" value="<?php echo getSetting($conn, 'logo_url'); ?>">
															</div>
														</div>
													</div>
													
													<div class="row">
														<div class="col-md-4">
															<div class="form-check form-switch mb-3">
																<input class="form-check-input" type="checkbox" name="maintenance_mode" id="maintenance_mode" value="1" <?php echo getSetting($conn, 'maintenance_mode') ? 'checked' : ''; ?>>
																<label class="form-check-label" for="maintenance_mode">Maintenance Mode</label>
															</div>
														</div>
														<div class="col-md-4">
															<div class="form-check form-switch mb-3">
																<input class="form-check-input" type="checkbox" name="registration_enabled" id="registration_enabled" value="1" <?php echo getSetting($conn, 'registration_enabled', '1') ? 'checked' : ''; ?>>
																<label class="form-check-label" for="registration_enabled">Registration Enabled</label>
															</div>
														</div>
														<div class="col-md-4">
															<div class="form-check form-switch mb-3">
																<input class="form-check-input" type="checkbox" name="email_verification" id="email_verification" value="1" <?php echo getSetting($conn, 'email_verification') ? 'checked' : ''; ?>>
																<label class="form-check-label" for="email_verification">Email Verification</label>
															</div>
														</div>
													</div>
													
													<div class="mb-3">
														<label class="form-label">Maintenance Message</label>
														<textarea class="form-control" name="maintenance_message" rows="3"><?php echo getSetting($conn, 'maintenance_message', 'The platform is currently under maintenance. Please check back later.'); ?></textarea>
													</div>
													
													<hr>
													<div class="mb-3">
														<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
														<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
														<small class="text-mute">Required for security confirmation</small>
													</div>
													
													<button type="submit" class="btn btn-primary">
														<i class="fas fa-save me-1"></i> Save General Settings
													</button>
												</form>
											</div>
											
											<!-- Trading Settings Tab -->
											<div class="tab-pane fade" id="trading">
												<form method="POST">
													<input type="hidden" name="action" value="save_trading_settings">
													
													<h5 class="mb-3"><i class="fas fa-money-bill-wave me-2"></i> Deposit & Withdrawal Limits</h5>
													<div class="row">
														<div class="col-md-3">
															<div class="mb-3">
																<label class="form-label">Min Deposit ($)</label>
																<input type="number" class="form-control" name="min_deposit" step="0.01" min="0" value="<?php echo getSetting($conn, 'min_deposit', '10.00'); ?>">
															</div>
														</div>
														<div class="col-md-3">
															<div class="mb-3">
																<label class="form-label">Max Deposit ($)</label>
																<input type="number" class="form-control" name="max_deposit" step="0.01" min="0" value="<?php echo getSetting($conn, 'max_deposit', '100000.00'); ?>">
															</div>
														</div>
														<div class="col-md-3">
															<div class="mb-3">
																<label class="form-label">Min Withdrawal ($)</label>
																<input type="number" class="form-control" name="min_withdrawal" step="0.01" min="0" value="<?php echo getSetting($conn, 'min_withdrawal', '10.00'); ?>">
															</div>
														</div>
														<div class="col-md-3">
															<div class="mb-3">
																<label class="form-label">Max Withdrawal ($)</label>
																<input type="number" class="form-control" name="max_withdrawal" step="0.01" min="0" value="<?php echo getSetting($conn, 'max_withdrawal', '10000.00'); ?>">
															</div>
														</div>
													</div>
													
													<h5 class="mb-3"><i class="fas fa-percentage me-2"></i> Fees</h5>
													<div class="row">
														<div class="col-md-4">
															<div class="mb-3">
																<label class="form-label">Withdrawal Fee (%)</label>
																<input type="number" class="form-control" name="withdrawal_fee" step="0.01" min="0" max="100" value="<?php echo getSetting($conn, 'withdrawal_fee', '1.00'); ?>">
															</div>
														</div>
														<div class="col-md-4">
															<div class="mb-3">
																<label class="form-label">Trading Fee (%)</label>
																<input type="number" class="form-control" name="trading_fee" step="0.01" min="0" max="100" value="<?php echo getSetting($conn, 'trading_fee', '0.10'); ?>">
															</div>
														</div>
														<div class="col-md-4">
															<div class="mb-3">
																<label class="form-label">USDT Network</label>
																<select class="form-control" name="usdt_network">
																	<option value="TRC20" <?php echo getSetting($conn, 'usdt_network', 'TRC20') == 'TRC20' ? 'selected' : ''; ?>>TRC20</option>
																	<option value="ERC20" <?php echo getSetting($conn, 'usdt_network') == 'ERC20' ? 'selected' : ''; ?>>ERC20</option>
																	<option value="BEP20" <?php echo getSetting($conn, 'usdt_network') == 'BEP20' ? 'selected' : ''; ?>>BEP20</option>
																</select>
															</div>
														</div>
													</div>
													
													<h5 class="mb-3"><i class="fas fa-robot me-2"></i> Trading Limits</h5>
													<div class="row">
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">Min Trading Amount ($)</label>
																<input type="number" class="form-control" name="min_trading_amount" step="0.01" min="0" value="<?php echo getSetting($conn, 'min_trading_amount', '100.00'); ?>">
															</div>
														</div>
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">Max Trading Amount ($)</label>
																<input type="number" class="form-control" name="max_trading_amount" step="0.01" min="0" value="<?php echo getSetting($conn, 'max_trading_amount', '1000000.00'); ?>">
															</div>
														</div>
													</div>
													
													<h5 class="mb-3"><i class="fas fa-bolt me-2"></i> Automation</h5>
													<div class="row">
														<div class="col-md-6">
															<div class="form-check form-switch mb-3">
																<input class="form-check-input" type="checkbox" name="auto_approve_deposits" id="auto_approve_deposits" value="1" <?php echo getSetting($conn, 'auto_approve_deposits') ? 'checked' : ''; ?>>
																<label class="form-check-label" for="auto_approve_deposits">Auto Approve Deposits</label>
															</div>
														</div>
														<div class="col-md-6">
															<div class="form-check form-switch mb-3">
																<input class="form-check-input" type="checkbox" name="auto_approve_withdrawals" id="auto_approve_withdrawals" value="1" <?php echo getSetting($conn, 'auto_approve_withdrawals') ? 'checked' : ''; ?>>
																<label class="form-check-label" for="auto_approve_withdrawals">Auto Approve Withdrawals</label>
															</div>
														</div>
													</div>
													
													<hr>
													<div class="mb-3">
														<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
														<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
														<small class="text-mute">Required for security confirmation</small>
													</div>
													
													<button type="submit" class="btn btn-primary">
														<i class="fas fa-save me-1"></i> Save Trading Settings
													</button>
												</form>
											</div>
											
											<!-- Email Settings Tab -->
											<div class="tab-pane fade" id="email">
												<form method="POST">
													<input type="hidden" name="action" value="save_email_settings">
													
													<h5 class="mb-3"><i class="fas fa-server me-2"></i> SMTP Server Settings</h5>
													<div class="row">
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">SMTP Host <span class="text-danger">*</span></label>
																<input type="text" class="form-control" name="smtp_host" value="<?php echo $mail_settings['host'] ?: 'smtp.gmail.com'; ?>" required>
															</div>
														</div>
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">SMTP Port <span class="text-danger">*</span></label>
																<input type="number" class="form-control" name="smtp_port" value="<?php echo $mail_settings['port'] ?: '587'; ?>" required>
															</div>
														</div>
													</div>
													
													<div class="row">
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">SMTP Username <span class="text-danger">*</span></label>
																<input type="text" class="form-control" name="smtp_username" value="<?php echo $mail_settings['username'] ?: ''; ?>" required>
															</div>
														</div>
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">SMTP Password <span class="text-danger">*</span></label>
																<input type="password" class="form-control" name="smtp_password" value="<?php echo $mail_settings['password'] ?: ''; ?>" required>
															</div>
														</div>
													</div>
													
													<div class="row">
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">SMTP Encryption</label>
																<select class="form-control" name="smtp_encryption">
																	<option value="tls" <?php echo getSetting($conn, 'smtp_encryption', 'tls') == 'tls' ? 'selected' : ''; ?>>TLS</option>
																	<option value="ssl" <?php echo getSetting($conn, 'smtp_encryption') == 'ssl' ? 'selected' : ''; ?>>SSL</option>
																	<option value="" <?php echo getSetting($conn, 'smtp_encryption') == '' ? 'selected' : ''; ?>>None</option>
																</select>
															</div>
														</div>
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">Connection Timeout (seconds)</label>
																<input type="number" class="form-control" name="smtp_timeout" value="<?php echo getSetting($conn, 'smtp_timeout', '30'); ?>">
															</div>
														</div>
													</div>
													
													<h5 class="mb-3"><i class="fas fa-envelope-open me-2"></i> Email Content</h5>
													<div class="row">
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">From Email <span class="text-danger">*</span></label>
																<input type="email" class="form-control" name="from_email" value="<?php echo getSetting($conn, 'from_email', 'noreply@yourplatform.com'); ?>" required>
															</div>
														</div>
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">From Name <span class="text-danger">*</span></label>
																<input type="text" class="form-control" name="from_name" value="<?php echo getSetting($conn, 'from_name', 'AI Trading Platform'); ?>" required>
															</div>
														</div>
													</div>
													
													<h5 class="mb-3"><i class="fas fa-bell me-2"></i> Email Notifications</h5>
													<div class="row">
														<div class="col-md-4">
															<div class="form-check form-switch mb-3">
																<input class="form-check-input" type="checkbox" name="email_deposit_notify" id="email_deposit_notify" value="1" <?php echo getSetting($conn, 'email_deposit_notify', '1') ? 'checked' : ''; ?>>
																<label class="form-check-label" for="email_deposit_notify">Deposit Notifications</label>
															</div>
														</div>
														<div class="col-md-4">
															<div class="form-check form-switch mb-3">
																<input class="form-check-input" type="checkbox" name="email_withdrawal_notify" id="email_withdrawal_notify" value="1" <?php echo getSetting($conn, 'email_withdrawal_notify', '1') ? 'checked' : ''; ?>>
																<label class="form-check-label" for="email_withdrawal_notify">Withdrawal Notifications</label>
															</div>
														</div>
														<div class="col-md-4">
															<div class="form-check form-switch mb-3">
																<input class="form-check-input" type="checkbox" name="email_trading_notify" id="email_trading_notify" value="1" <?php echo getSetting($conn, 'email_trading_notify', '1') ? 'checked' : ''; ?>>
																<label class="form-check-label" for="email_trading_notify">Trading Notifications</label>
															</div>
														</div>
													</div>
													
													<hr>
													<div class="mb-3">
														<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
														<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
														<small class="text-mute">Required for security confirmation</small>
													</div>
													
													<button type="submit" class="btn btn-primary">
														<i class="fas fa-save me-1"></i> Save Email Settings
													</button>
												</form>
											</div>
											
											<!-- Referral Settings Tab -->
											<div class="tab-pane fade" id="referral">
												<form method="POST">
													<input type="hidden" name="action" value="save_referral_settings">
													
													<div class="form-check form-switch mb-3">
														<input class="form-check-input" type="checkbox" name="referral_enabled" id="referral_enabled" value="1" <?php echo getSetting($conn, 'referral_enabled', '1') ? 'checked' : ''; ?>>
														<label class="form-check-label" for="referral_enabled">Enable Referral System</label>
													</div>
													
													<h5 class="mb-3"><i class="fas fa-gift me-2"></i> Signup Bonuses</h5>
													<div class="row">
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">Referrer Bonus ($)</label>
																<input type="number" class="form-control" name="signup_bonus_referrer" step="0.01" min="0" value="<?php echo $ref_settings['signup_bonus_referrer'] ?: '100.00'; ?>">
																<small class="text-mute">Bonus for the referrer when someone signs up</small>
															</div>
														</div>
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">Referred Bonus ($)</label>
																<input type="number" class="form-control" name="signup_bonus_referred" step="0.01" min="0" value="<?php echo $ref_settings['signup_bonus_referred'] ?: '50.00'; ?>">
																<small class="text-mute">Bonus for the new user when they sign up</small>
															</div>
														</div>
													</div>
													
													<div class="mb-3">
														<label class="form-label">Bot Subscription Bonus ($)</label>
														<input type="number" class="form-control" name="bot_bonus" step="0.01" min="0" value="<?php echo $ref_settings['bot_bonus'] ?: '200.00'; ?>">
														<small class="text-mute">Bonus when referred user subscribes to a bot</small>
													</div>
													
													<h5 class="mb-3"><i class="fas fa-percentage me-2"></i> Trading Discounts</h5>
													<div class="row">
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">Discount Per Referral (%)</label>
																<input type="number" class="form-control" name="discount_per_referral" step="0.01" min="0" max="100" value="<?php echo $ref_settings['discount_per_referral'] ?: '0.10'; ?>">
																<small class="text-mute">Trading fee discount per successful referral</small>
															</div>
														</div>
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">Max Referral Discount (%)</label>
																<input type="number" class="form-control" name="max_referral_discount" step="0.01" min="0" max="100" value="<?php echo $ref_settings['max_referral_discount'] ?: '1.00'; ?>">
																<small class="text-mute">Maximum total trading fee discount</small>
															</div>
														</div>
													</div>
													
													<div class="mb-3">
														<label class="form-label">Minimum Referral Payout ($)</label>
														<input type="number" class="form-control" name="min_referral_payout" step="0.01" min="0" value="<?php echo getSetting($conn, 'min_referral_payout', '10.00'); ?>">
														<small class="text-mute">Minimum amount required for referral payout</small>
													</div>
													
													<h5 class="mb-3"><i class="fas fa-calendar me-2"></i> Payout Schedule</h5>
													<div class="row">
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">Payout Frequency</label>
																<select class="form-control" name="payout_frequency">
																	<option value="daily" <?php echo getSetting($conn, 'payout_frequency') == 'daily' ? 'selected' : ''; ?>>Daily</option>
																	<option value="weekly" <?php echo getSetting($conn, 'payout_frequency', 'weekly') == 'weekly' ? 'selected' : ''; ?>>Weekly</option>
																	<option value="monthly" <?php echo getSetting($conn, 'payout_frequency') == 'monthly' ? 'selected' : ''; ?>>Monthly</option>
																</select>
															</div>
														</div>
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">Payout Day</label>
																<select class="form-control" name="payout_day">
																	<?php for ($i = 1; $i <= 31; $i++): ?>
																		<option value="<?php echo $i; ?>" <?php echo getSetting($conn, 'payout_day', '1') == $i ? 'selected' : ''; ?>><?php echo $i; ?></option>
																	<?php endfor; ?>
																</select>
															</div>
														</div>
													</div>
													
													<hr>
													<div class="mb-3">
														<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
														<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
														<small class="text-mute">Required for security confirmation</small>
													</div>
													
													<button type="submit" class="btn btn-primary">
														<i class="fas fa-save me-1"></i> Save Referral Settings
													</button>
												</form>
											</div>
											
											<!-- Security Settings Tab -->
											<div class="tab-pane fade" id="security">
												<form method="POST">
													<input type="hidden" name="action" value="save_security_settings">
													
													<h5 class="mb-3"><i class="fas fa-sign-in-alt me-2"></i> Login Security</h5>
													<div class="row">
														<div class="col-md-4">
															<div class="mb-3">
																<label class="form-label">Max Login Attempts</label>
																<input type="number" class="form-control" name="login_attempts" min="1" value="<?php echo getSetting($conn, 'login_attempts', '5'); ?>">
															</div>
														</div>
														<div class="col-md-4">
															<div class="mb-3">
																<label class="form-label">Lockout Minutes</label>
																<input type="number" class="form-control" name="login_lockout_minutes" min="1" value="<?php echo getSetting($conn, 'login_lockout_minutes', '15'); ?>">
															</div>
														</div>
														<div class="col-md-4">
															<div class="mb-3">
																<label class="form-label">Session Timeout (minutes)</label>
																<input type="number" class="form-control" name="session_timeout" min="1" value="<?php echo getSetting($conn, 'session_timeout', '30'); ?>">
															</div>
														</div>
													</div>
													
													<h5 class="mb-3"><i class="fas fa-lock me-2"></i> Password Policy</h5>
													<div class="row">
														<div class="col-md-4">
															<div class="mb-3">
																<label class="form-label">Min Password Length</label>
																<input type="number" class="form-control" name="min_password_length" min="6" value="<?php echo getSetting($conn, 'min_password_length', '8'); ?>">
															</div>
														</div>
														<div class="col-md-4">
															<div class="mb-3">
																<label class="form-label">Password Expiry (days)</label>
																<input type="number" class="form-control" name="password_expiry_days" min="0" value="<?php echo getSetting($conn, 'password_expiry_days', '90'); ?>">
																<small class="text-mute">0 = Never expires</small>
															</div>
														</div>
														<div class="col-md-4">
															<div class="form-check form-switch mb-3 mt-4">
																<input class="form-check-input" type="checkbox" name="require_strong_password" id="require_strong_password" value="1" <?php echo getSetting($conn, 'require_strong_password') ? 'checked' : ''; ?>>
																<label class="form-check-label" for="require_strong_password">Require Strong Password</label>
															</div>
														</div>
													</div>
													
													<h5 class="mb-3"><i class="fas fa-shield-alt me-2"></i> Advanced Security</h5>
													<div class="row">
														<div class="col-md-4">
															<div class="form-check form-switch mb-3">
																<input class="form-check-input" type="checkbox" name="2fa_enabled" id="2fa_enabled" value="1" <?php echo getSetting($conn, '2fa_enabled') ? 'checked' : ''; ?>>
																<label class="form-check-label" for="2fa_enabled">Enable 2FA</label>
															</div>
														</div>
														<div class="col-md-4">
															<div class="form-check form-switch mb-3">
																<input class="form-check-input" type="checkbox" name="force_ssl" id="force_ssl" value="1" <?php echo getSetting($conn, 'force_ssl') ? 'checked' : ''; ?>>
																<label class="form-check-label" for="force_ssl">Force SSL/HTTPS</label>
															</div>
														</div>
														<div class="col-md-4">
															<div class="form-check form-switch mb-3">
																<input class="form-check-input" type="checkbox" name="captcha_enabled" id="captcha_enabled" value="1" <?php echo getSetting($conn, 'captcha_enabled') ? 'checked' : ''; ?>>
																<label class="form-check-label" for="captcha_enabled">Enable CAPTCHA</label>
															</div>
														</div>
													</div>
													
													<div class="mb-3">
														<label class="form-label">IP Whitelist</label>
														<textarea class="form-control" name="ip_whitelist" rows="3" placeholder="Enter IP addresses (one per line)"><?php echo getSetting($conn, 'ip_whitelist'); ?></textarea>
														<small class="text-mute">Leave empty to allow all IPs. One IP per line.</small>
													</div>
													
													<div class="mb-3">
														<label class="form-label">Admin Session Timeout (minutes)</label>
														<input type="number" class="form-control" name="admin_session_timeout" min="1" value="<?php echo getSetting($conn, 'admin_session_timeout', '15'); ?>">
														<small class="text-mute">Admin panel session timeout</small>
													</div>
													
													<hr>
													<div class="mb-3">
														<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
														<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
														<small class="text-mute">Required for security confirmation</small>
													</div>
													
													<button type="submit" class="btn btn-primary">
														<i class="fas fa-save me-1"></i> Save Security Settings
													</button>
												</form>
											</div>
											
											<!-- Backup Tab -->
											<div class="tab-pane fade" id="backup">
												<div class="row">
													<div class="col-md-6">
														<div class="box bg-light">
															<div class="box-header">
																<h5 class="box-title"><i class="fas fa-database me-2"></i> Database Backup</h5>
															</div>
															<div class="box-body text-center">
																<div class="mb-20">
																	<i class="fas fa-database fa-3x text-primary"></i>
																</div>
																<p class="mb-3">Create a backup of your database</p>
																<button class="btn btn-primary" onclick="createBackup()">
																	<i class="fas fa-download me-1"></i> Backup Now
																</button>
																<div class="mt-3">
																	<small class="text-mute">Last backup: <?php echo getSetting($conn, 'last_backup', 'Never'); ?></small>
																</div>
															</div>
														</div>
													</div>
													
													<div class="col-md-6">
														<div class="box bg-light">
															<div class="box-header">
																<h5 class="box-title"><i class="fas fa-history me-2"></i> Backup Settings</h5>
															</div>
															<div class="box-body">
																<form method="POST" action="ajax/backup_settings.php">
																	<input type="hidden" name="action" value="save_backup_settings">
																	
																	<div class="form-check form-switch mb-3">
																		<input class="form-check-input" type="checkbox" name="auto_backup" id="auto_backup" value="1" <?php echo getSetting($conn, 'auto_backup') ? 'checked' : ''; ?>>
																		<label class="form-check-label" for="auto_backup">Enable Auto Backup</label>
																	</div>
																	
																	<div class="mb-3">
																		<label class="form-label">Backup Frequency</label>
																		<select class="form-control" name="backup_frequency">
																			<option value="daily" <?php echo getSetting($conn, 'backup_frequency', 'daily') == 'daily' ? 'selected' : ''; ?>>Daily</option>
																			<option value="weekly" <?php echo getSetting($conn, 'backup_frequency') == 'weekly' ? 'selected' : ''; ?>>Weekly</option>
																			<option value="monthly" <?php echo getSetting($conn, 'backup_frequency') == 'monthly' ? 'selected' : ''; ?>>Monthly</option>
																		</select>
																	</div>
																	
																	<div class="mb-3">
																		<label class="form-label">Keep Backups For (days)</label>
																		<input type="number" class="form-control" name="keep_backups_days" min="1" value="<?php echo getSetting($conn, 'keep_backups_days', '30'); ?>">
																	</div>
																	
																	<hr>
																	<div class="mb-3">
																		<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
																		<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
																	</div>
																	
																	<button type="submit" class="btn btn-primary">
																		<i class="fas fa-save me-1"></i> Save Backup Settings
																	</button>
																</form>
															</div>
														</div>
													</div>
												</div>
												
												<div class="box mt-3">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-file-archive me-2"></i> Available Backups</h5>
													</div>
													<div class="box-body">
														<div class="table-responsive">
															<table class="table table-hover">
																<thead>
																	<tr>
																		<th>File Name</th>
																		<th>Date</th>
																		<th>Size</th>
																		<th>Actions</th>
																	</tr>
																</thead>
																<tbody id="backupList">
																	<!-- Backups will be loaded via AJAX -->
																</tbody>
															</table>
														</div>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</section>
					<!-- /.content -->
				</div>
			</div>
		  	
		  <?php include('includes/footer.php') ?>

		  <?php include('includes/control_sidebar.php') ?>
			
		</div>
		<!-- ./wrapper -->
		
		  
    
		
		
		  <?php include('includes/scripts.php') ?>
		
		<!-- SweetAlert2 -->
		<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
		
		<script>
		$(document).ready(function() {
			// Load backup list
			loadBackupList();
			
			// Refresh backup list every 30 seconds
			setInterval(loadBackupList, 30000);
		});
		
		// Load backup list
		function loadBackupList() {
			$.ajax({
				url: 'ajax/get_backup_list.php',
				type: 'GET',
				success: function(data) {
					$('#backupList').html(data);
				}
			});
		}
		
		// Create database backup
		function createBackup() {
			Swal.fire({
				title: 'Create Database Backup?',
				html: `
					<p>This will create a backup of your entire database.</p>
					<div class="mt-3">
						<label class="form-label">Enter Admin PIN to confirm:</label>
						<input type="password" id="backupPin" class="form-control" placeholder="4-digit PIN" autocomplete="off">
					</div>
				`,
				icon: 'question',
				showCancelButton: true,
				confirmButtonColor: '#3085d6',
				cancelButtonColor: '#d33',
				confirmButtonText: 'Create Backup',
				cancelButtonText: 'Cancel',
				preConfirm: () => {
					const pin = document.getElementById('backupPin').value;
					if (!pin) {
						Swal.showValidationMessage('Please enter your PIN');
					} else if (pin.length !== 4) {
						Swal.showValidationMessage('PIN must be 4 digits');
					}
					return { pin: pin };
				}
			}).then((result) => {
				if (result.isConfirmed) {
					// Show loading
					Swal.fire({
						title: 'Creating Backup...',
						text: 'Please wait while we create the backup.',
						allowOutsideClick: false,
						didOpen: () => {
							Swal.showLoading();
						}
					});
					
					// Send request
					$.ajax({
						url: 'ajax/create_backup.php',
						type: 'POST',
						data: { admin_pin: result.value.pin },
						success: function(response) {
							var data = JSON.parse(response);
							if (data.success) {
								Swal.fire({
									icon: 'success',
									title: 'Backup Created!',
									html: `Backup created successfully.<br>File: ${data.filename}<br>Size: ${data.size}`,
									confirmButtonText: 'OK'
								});
								loadBackupList();
							} else {
								Swal.fire({
									icon: 'error',
									title: 'Backup Failed',
									text: data.message,
									confirmButtonText: 'OK'
								});
							}
						}
					});
				}
			});
		}
		
		// Download backup
		function downloadBackup(filename) {
			window.open('backups/' + filename, '_blank');
		}
		
		// Delete backup
		function deleteBackup(filename) {
			Swal.fire({
				title: 'Delete Backup?',
				html: `
					<p>Are you sure you want to delete ${filename}?</p>
					<div class="mt-3">
						<label class="form-label">Enter Admin PIN to confirm:</label>
						<input type="password" id="deleteBackupPin" class="form-control" placeholder="4-digit PIN" autocomplete="off">
					</div>
				`,
				icon: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#d33',
				cancelButtonColor: '#3085d6',
				confirmButtonText: 'Delete Backup',
				cancelButtonText: 'Cancel',
				preConfirm: () => {
					const pin = document.getElementById('deleteBackupPin').value;
					if (!pin) {
						Swal.showValidationMessage('Please enter your PIN');
					} else if (pin.length !== 4) {
						Swal.showValidationMessage('PIN must be 4 digits');
					}
					return { pin: pin };
				}
			}).then((result) => {
				if (result.isConfirmed) {
					$.ajax({
						url: 'ajax/delete_backup.php',
						type: 'POST',
						data: { filename: filename, admin_pin: result.value.pin },
						success: function(response) {
							var data = JSON.parse(response);
							if (data.success) {
								Swal.fire({
									icon: 'success',
									title: 'Backup Deleted!',
									text: 'Backup file has been deleted.',
									confirmButtonText: 'OK'
								});
								loadBackupList();
							} else {
								Swal.fire({
									icon: 'error',
									title: 'Delete Failed',
									text: data.message,
									confirmButtonText: 'OK'
								});
							}
						}
					});
				}
			});
		}
		
		// Test email settings
		function testEmailSettings() {
			Swal.fire({
				title: 'Test Email Settings',
				html: `
					<p>This will send a test email to verify your email settings.</p>
					<div class="mt-3">
						<label class="form-label">Enter Admin PIN to confirm:</label>
						<input type="password" id="testEmailPin" class="form-control" placeholder="4-digit PIN" autocomplete="off">
					</div>
					<div class="mt-3">
						<label class="form-label">Test Email Address:</label>
						<input type="email" id="testEmailAddress" class="form-control" placeholder="email@example.com">
					</div>
				`,
				icon: 'info',
				showCancelButton: true,
				confirmButtonColor: '#3085d6',
				cancelButtonColor: '#d33',
				confirmButtonText: 'Send Test Email',
				cancelButtonText: 'Cancel',
				preConfirm: () => {
					const pin = document.getElementById('testEmailPin').value;
					const email = document.getElementById('testEmailAddress').value;
					
					if (!pin) {
						Swal.showValidationMessage('Please enter your PIN');
					} else if (pin.length !== 4) {
						Swal.showValidationMessage('PIN must be 4 digits');
					} else if (!email) {
						Swal.showValidationMessage('Please enter an email address');
					} else if (!isValidEmail(email)) {
						Swal.showValidationMessage('Please enter a valid email address');
					}
					return { pin: pin, email: email };
				}
			}).then((result) => {
				if (result.isConfirmed) {
					// Show loading
					Swal.fire({
						title: 'Sending Test Email...',
						text: 'Please wait while we send the test email.',
						allowOutsideClick: false,
						didOpen: () => {
							Swal.showLoading();
						}
					});
					
					// Send request
					$.ajax({
						url: 'ajax/test_email.php',
						type: 'POST',
						data: { 
							admin_pin: result.value.pin,
							test_email: result.value.email 
						},
						success: function(response) {
							var data = JSON.parse(response);
							if (data.success) {
								Swal.fire({
									icon: 'success',
									title: 'Test Email Sent!',
									html: `Test email sent successfully to ${result.value.email}.<br><br>Please check your inbox.`,
									confirmButtonText: 'OK'
								});
							} else {
								Swal.fire({
									icon: 'error',
									title: 'Email Failed',
									html: `Failed to send test email.<br><br>Error: ${data.message}`,
									confirmButtonText: 'OK'
								});
							}
						}
					});
				}
			});
		}
		
		// Email validation
		function isValidEmail(email) {
			var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
			return re.test(email);
		}
		</script>
		
		<style>
		.nav-tabs .nav-link {
			border: 1px solid transparent;
			border-radius: 5px 5px 0 0;
			margin-right: 5px;
			padding: 10px 20px;
		}
		.nav-tabs .nav-link.active {
			background-color: #f8f9fa;
			border-color: #dee2e6 #dee2e6 #f8f9fa;
			font-weight: 600;
		}
		.form-check.form-switch {
			padding-left: 3.5em;
		}
		.form-check-input:checked {
			background-color: #0d6efd;
			border-color: #0d6efd;
		}
		.box.bg-light {
			background-color: #f8f9fa !important;
		}
		</style>
		
	</body>
</html>