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

// Check admin session
$admin_id = $_SESSION['admin_id'] ?: 1;
$admin_name = $_SESSION['admin_name'] ?: 'System Admin';
$admin_role = $_SESSION['admin_role'] ?: 'admin';
$admin_email = $_SESSION['admin_email'] ?? '';

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

// Initialize messages
$success = $error = $test_result = '';

// Get current email settings
$sql = "SELECT * FROM mail_settings WHERE id = 1";
$result = mysqli_query($conn, $sql);
$mail_settings = mysqli_fetch_assoc($result);

if (!$mail_settings) {
    // Initialize default settings
    $mail_settings = array(
        'host' => 'smtp.gmail.com',
        'username' => 'your-email@gmail.com',
        'password' => '',
        'port' => 587,
        'encryption' => 'tls',
        'from_name' => 'AI Trading Platform',
        'from_email' => 'noreply@aitrading.com',
        'reply_to' => 'support@aitrading.com',
        'url' => 'http://localhost/ai_trading/'
    );
}

// Get admin email for notification
if (empty($admin_email)) {
    $adminQuery = mysqli_query($conn, "SELECT email FROM users WHERE id='$admin_id'");
    $adminData = mysqli_fetch_assoc($adminQuery);
    $admin_email = $adminData['email'] ?? 'admin@system.com';
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $submitted_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';
    $action = isset($_POST['action']) ? $_POST['action'] : '';
    
    if ($submitted_pin !== $admin_pin) {
        $error = "Invalid PIN. Action not authorized.";
    } else {
        switch ($action) {
            case 'save_smtp':
                $host = mysqli_real_escape_string($conn, $_POST['host']);
                $username = mysqli_real_escape_string($conn, $_POST['username']);
                $password = mysqli_real_escape_string($conn, $_POST['password']);
                $port = intval($_POST['port']);
                $encryption = mysqli_real_escape_string($conn, $_POST['encryption']);
                $from_name = mysqli_real_escape_string($conn, $_POST['from_name']);
                $from_email = mysqli_real_escape_string($conn, $_POST['from_email']);
                $reply_to = mysqli_real_escape_string($conn, $_POST['reply_to']);
                $url = mysqli_real_escape_string($conn, $_POST['url']);
                
                // Get old settings for comparison
                $old_settings = $mail_settings;
                
                // Check if settings exist
                $check_sql = "SELECT id FROM mail_settings WHERE id = 1";
                $check_result = mysqli_query($conn, $check_sql);
                
                if (mysqli_num_rows($check_result) > 0) {
                    // Update existing settings
                    $sql = "UPDATE mail_settings SET 
                            host = '$host',
                            username = '$username',
                            password = '$password',
                            port = '$port',
                            url = '$url',
                            from_name = '$from_name',
                            from_email = '$from_email',
                            reply_to = '$reply_to',
                            encryption = '$encryption',
                            updated_at = NOW()
                            WHERE id = 1";
                } else {
                    // Insert new settings
                    $sql = "INSERT INTO mail_settings (id, host, username, password, port, url, from_name, from_email, reply_to, encryption, created_at) 
                            VALUES (1, '$host', '$username', '$password', '$port', '$url', '$from_name', '$from_email', '$reply_to', '$encryption', NOW())";
                }
                
                if (mysqli_query($conn, $sql)) {
                    logAdminActivity(
                        'Email Settings Updated',
                        'Updated SMTP email settings',
                        'Settings',
                        1,
                        'mail_settings'
                    );
                    $success = "SMTP settings saved successfully!";
                    
                    // NOTIFICATION: Email Settings Updated (ADMIN)
                    $mail_subject = "Email Settings Updated";
                    $mail_message = "<!-- Content Section -->
                                    <div class='email-content'>
                                        <h2 class='greeting'>Email Settings Updated</h2>
                                        
                                        <p class='message'>
                                            The system email configuration has been modified by an administrator.
                                        </p>

                                        <!-- Settings Update Details -->
                                        <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>Action:</strong> SMTP Configuration Updated
                                            </div>
                                        </div>

                                        <!-- Settings Comparison -->
                                        <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                            <h4 style='color: #495057;'>⚙️ Configuration Changes</h4>
                                            <table style='width: 100%; border-collapse: collapse; margin: 15px 0;'>
                                                <tr>
                                                    <td style='padding: 8px; border-bottom: 1px solid #dee2e6;'><strong>SMTP Host:</strong></td>
                                                    <td style='padding: 8px; border-bottom: 1px solid #dee2e6;'>" . $old_settings['host'] . " → " . $host . "</td>
                                                </tr>
                                                <tr>
                                                    <td style='padding: 8px; border-bottom: 1px solid #dee2e6;'><strong>Port:</strong></td>
                                                    <td style='padding: 8px; border-bottom: 1px solid #dee2e6;'>" . $old_settings['port'] . " → " . $port . "</td>
                                                </tr>
                                                <tr>
                                                    <td style='padding: 8px; border-bottom: 1px solid #dee2e6;'><strong>Encryption:</strong></td>
                                                    <td style='padding: 8px; border-bottom: 1px solid #dee2e6;'>" . $old_settings['encryption'] . " → " . $encryption . "</td>
                                                </tr>
                                                <tr>
                                                    <td style='padding: 8px; border-bottom: 1px solid #dee2e6;'><strong>From Name:</strong></td>
                                                    <td style='padding: 8px; border-bottom: 1px solid #dee2e6;'>" . $old_settings['from_name'] . " → " . $from_name . "</td>
                                                </tr>
                                                <tr>
                                                    <td style='padding: 8px; border-bottom: 1px solid #dee2e6;'><strong>From Email:</strong></td>
                                                    <td style='padding: 8px; border-bottom: 1px solid #dee2e6;'>" . $old_settings['from_email'] . " → " . $from_email . "</td>
                                                </tr>
                                            </table>
                                        </div>

                                        <!-- Security Warning -->
                                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                            <h4 style='color: #856404;'>⚠️ Security Notice</h4>
                                            <p style='color: #856404;'>
                                                Email settings control all system communications.<br>
                                                Verify these settings are correct to ensure email delivery.
                                            </p>
                                        </div>

                                        <!-- Admin Actions -->
                                        <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: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                Test Email Configuration
                                            </a>
                                            <a href='" . $myUrl . "/admin/email-templates.php' 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;'>
                                                Manage Email Templates
                                            </a>
                                        </div>

                                        <div class='support-section'>
                                            <p class='support-text'>Configuration saved successfully.</p>
                                        </div>
                                    </div>";

                    // Send admin notification
                    require_once("../proccess/admin_mailer.php");
                    
                    // Refresh settings
                    $result = mysqli_query($conn, "SELECT * FROM mail_settings WHERE id = 1");
                    $mail_settings = mysqli_fetch_assoc($result);
                } else {
                    $error = "Failed to save SMTP settings: " . mysqli_error($conn);
                }
                break;
                
            case 'save_template':
                $template_id = intval($_POST['template_id']);
                $subject = mysqli_real_escape_string($conn, $_POST['subject']);
                $content = mysqli_real_escape_string($conn, $_POST['content']);
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                // Get template details before update
                $template_sql = "SELECT template_name, template_type FROM email_templates WHERE id = $template_id";
                $template_result = mysqli_query($conn, $template_sql);
                $template_data = mysqli_fetch_assoc($template_result);
                $template_name = $template_data['template_name'] ?? 'Unknown Template';
                $template_type = $template_data['template_type'] ?? 'notification';
                
                // Check if template exists
                $check_sql = "SELECT id FROM email_templates WHERE id = $template_id";
                $check_result = mysqli_query($conn, $check_sql);
                
                if (mysqli_num_rows($check_result) > 0) {
                    // Update template
                    $sql = "UPDATE email_templates SET 
                            subject = '$subject',
                            content = '$content',
                            is_active = $is_active,
                            updated_at = NOW()
                            WHERE id = $template_id";
                } else {
                    // Insert new template (this shouldn't happen but handle it)
                    $template_name = mysqli_real_escape_string($conn, $_POST['template_name']);
                    $sql = "INSERT INTO email_templates (template_name, subject, content, is_active, created_at) 
                            VALUES ('$template_name', '$subject', '$content', $is_active, NOW())";
                }
                
                if (mysqli_query($conn, $sql)) {
                    logAdminActivity(
                        'Email Template Updated',
                        "Updated email template ID $template_id - $template_name",
                        'Settings',
                        $template_id,
                        'email_templates'
                    );
                    $success = "Email template saved successfully!";
                    
                    // NOTIFICATION: Email Template Updated (ADMIN)
                    $mail_subject = "Email Template Updated";
                    $mail_message = "<!-- Content Section -->
                                    <div class='email-content'>
                                        <h2 class='greeting'>Email Template Updated</h2>
                                        
                                        <p class='message'>
                                            An email template has been modified in the system.
                                        </p>

                                        <!-- Template Details -->
                                        <div class='details-section'>
                                            <div class='detail-box'>
                                                <strong>Template ID:</strong> " . $template_id . "<br>
                                                <strong>Template Name:</strong> " . $template_name . "<br>
                                                <strong>Template Type:</strong> " . $template_type . "<br>
                                                <strong>Updated By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                <strong>Update Time:</strong> " . date('F j, Y g:i A') . "<br>
                                                <strong>Status:</strong> " . ($is_active ? '<span style="color: #28a745;">Active</span>' : '<span style="color: #dc3545;">Inactive</span>') . "<br>
                                                <strong>Subject:</strong> " . $subject . "
                                            </div>
                                        </div>

                                        <!-- Content Preview -->
                                        <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                            <h4 style='color: #495057;'>📧 Content Preview</h4>
                                            <div style='max-height: 200px; overflow-y: auto; padding: 10px; background: white; border: 1px solid #dee2e6;'>
                                                " . substr(strip_tags($content), 0, 500) . "...<br>
                                                <span style='color: #6c757d;'>(Content truncated - view in admin panel for full template)</span>
                                            </div>
                                        </div>

                                        <!-- Impact Notice -->
                                        <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                            <h4 style='color: #0056b3;'>📨 System Impact</h4>
                                            <p style='color: #0056b3;'>
                                                This template is used for " . $template_type . " emails.<br>
                                                Changes will affect all future emails sent using this template.
                                            </p>
                                        </div>

                                        <!-- Admin Actions -->
                                        <div style='text-align: center; margin: 30px 0;'>
                                            <a href='" . $myUrl . "/admin/email-templates.php?id=" . $template_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 Template
                                            </a>
                                            <a href='" . $myUrl . "/admin/email-settings.php' 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;'>
                                                Back to Settings
                                            </a>
                                        </div>

                                        <div class='support-section'>
                                            <p class='support-text'>Template updated successfully.</p>
                                        </div>
                                    </div>";

                    // Send admin notification
                    require_once("../proccess/admin_mailer.php");
                } else {
                    $error = "Failed to save email template: " . mysqli_error($conn);
                }
                break;
                
            case 'test_email':
                $test_email = mysqli_real_escape_string($conn, $_POST['test_email']);
                
                // Test email sending
                $test_result = testEmailSending($test_email, $mail_settings, $admin_name, $admin_id);
                
                if (strpos($test_result, 'success') !== false) {
                    // NOTIFICATION: Test Email Sent (ADMIN)
                    $mail_subject = "Test Email Sent";
                    $mail_message = "<!-- Content Section -->
                                    <div class='email-content'>
                                        <h2 class='greeting'>Test Email Sent</h2>
                                        
                                        <p class='message'>
                                            A test email was sent to verify the email configuration.
                                        </p>

                                        <!-- Test Details -->
                                        <div class='details-section'>
                                            <div class='detail-box'>
                                                <strong>Sent By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                <strong>Sent To:</strong> " . $test_email . "<br>
                                                <strong>Sent Time:</strong> " . date('F j, Y g:i A') . "<br>
                                                <strong>SMTP Host:</strong> " . $mail_settings['host'] . "<br>
                                                <strong>Port:</strong> " . $mail_settings['port'] . "<br>
                                                <strong>Encryption:</strong> " . $mail_settings['encryption'] . "<br>
                                                <strong>From Email:</strong> " . $mail_settings['from_email'] . "<br>
                                                <strong>Result:</strong> <span style='color: #28a745;'>SUCCESS</span>
                                            </div>
                                        </div>

                                        <div class='support-section'>
                                            <p class='support-text'>Email configuration is working properly.</p>
                                        </div>
                                    </div>";

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

// Get email templates
$templates_sql = "SELECT * FROM email_templates ORDER BY template_name";
$templates_result = mysqli_query($conn, $templates_sql);

// If templates table doesn't exist, create default templates
if (!$templates_result) {
    // Create email_templates table if it doesn't exist
    $create_table = "CREATE TABLE IF NOT EXISTS email_templates (
        id INT(11) NOT NULL AUTO_INCREMENT,
        template_name VARCHAR(100) NOT NULL,
        template_type ENUM('welcome', 'verification', 'password_reset', 'deposit', 'withdrawal', 'notification', 'newsletter') DEFAULT 'notification',
        subject VARCHAR(255) NOT NULL,
        content TEXT NOT NULL,
        variables TEXT,
        is_active TINYINT(1) DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
    
    mysqli_query($conn, $create_table);
    
    // Insert default templates
    $default_templates = array(
        array(
            'template_name' => 'Welcome Email',
            'template_type' => 'welcome',
            'subject' => 'Welcome to AI Trading Platform!',
            'content' => '<h2>Welcome {first_name}!</h2>
<p>Thank you for joining our AI Trading Platform. Your account has been successfully created.</p>
<p>Account Details:</p>
<ul>
<li>Username: {username}</li>
<li>Email: {email}</li>
<li>Account Status: {status}</li>
</ul>
<p>Please complete your KYC verification to unlock all features.</p>
<p>Start trading: {login_url}</p>
<p>Best regards,<br>AI Trading Team</p>',
            'variables' => '{first_name}, {last_name}, {username}, {email}, {status}, {login_url}'
        ),
        array(
            'template_name' => 'Account Verification',
            'template_type' => 'verification',
            'subject' => 'Account Verification Required',
            'content' => '<h2>Verify Your Account</h2>
<p>Dear {first_name},</p>
<p>Please verify your account by clicking the link below:</p>
<p><a href="{verification_url}" style="background-color: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;">Verify Account</a></p>
<p>Or copy this link: {verification_url}</p>
<p>This link will expire in 24 hours.</p>
<p>If you didn\'t create an account, please ignore this email.</p>
<p>Best regards,<br>AI Trading Team</p>',
            'variables' => '{first_name}, {last_name}, {username}, {email}, {verification_url}'
        ),
        array(
            'template_name' => 'Password Reset',
            'template_type' => 'password_reset',
            'subject' => 'Password Reset Request',
            'content' => '<h2>Reset Your Password</h2>
<p>You requested to reset your password. Click the link below to proceed:</p>
<p><a href="{reset_url}" style="background-color: #dc3545; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;">Reset Password</a></p>
<p>Or copy this link: {reset_url}</p>
<p>This link will expire in 1 hour.</p>
<p>If you didn\'t request a password reset, please ignore this email.</p>
<p>Best regards,<br>AI Trading Team</p>',
            'variables' => '{first_name}, {last_name}, {username}, {email}, {reset_url}'
        )
    );
    
    foreach ($default_templates as $template) {
        $insert_sql = "INSERT INTO email_templates (template_name, template_type, subject, content, variables) 
                      VALUES ('{$template['template_name']}', '{$template['template_type']}', '{$template['subject']}', '{$template['content']}', '{$template['variables']}')";
        mysqli_query($conn, $insert_sql);
    }
    
    // Re-fetch templates
    $templates_result = mysqli_query($conn, $templates_sql);
}

// Function to test email sending
function testEmailSending($to_email, $settings, $admin_name = 'Admin', $admin_id = 1) {
    $subject = "Test Email from AI Trading Platform";
    $message = "<h2>Test Email</h2>
    <p>This is a test email sent from your AI Trading Platform admin panel.</p>
    <p>If you're reading this, your email settings are configured correctly!</p>
    <p><strong>Sent by:</strong> " . $admin_name . " (ID: " . $admin_id . ")</p>
    <p><strong>Timestamp:</strong> " . date('Y-m-d H:i:s') . "</p>
    <p><strong>SMTP Host:</strong> " . $settings['host'] . "</p>
    <p><strong>Port:</strong> " . $settings['port'] . "</p>
    <p><strong>Encryption:</strong> " . $settings['encryption'] . "</p>
    <p><strong>From:</strong> " . $settings['from_name'] . " &lt;" . $settings['from_email'] . "&gt;</p>
    <p><strong>Reply-To:</strong> " . $settings['reply_to'] . "</p>
    <hr>
    <p style='color: #28a745;'><strong>✅ Test completed successfully!</strong></p>";
    
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: " . $settings['from_name'] . " <" . $settings['from_email'] . ">" . "\r\n";
    $headers .= "Reply-To: " . $settings['reply_to'] . "\r\n";
    
    // For testing, we'll use mail() function
    // In production, you would use PHPMailer or similar
    if (mail($to_email, $subject, $message, $headers)) {
        return '<div class="alert alert-success">✅ Test email sent successfully to ' . htmlspecialchars($to_email) . '</div>';
    } else {
        return '<div class="alert alert-danger">❌ Failed to send test email. Please check your SMTP settings.</div>';
    }
}
?>


<!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-envelope me-2"></i>Email Settings</h4>
									</div>
									<div class="box-body">
										<!-- Messages -->
										<?php if ($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 ($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; ?>
										
										<?php if ($test_result): ?>
											<?php echo $test_result; ?>
										<?php endif; ?>
										
										<!-- Tabs -->
										<ul class="nav nav-tabs" role="tablist">
											<li class="nav-item">
												<a class="nav-link active" data-bs-toggle="tab" href="#smtp">SMTP Settings</a>
											</li>
											<li class="nav-item">
												<a class="nav-link" data-bs-toggle="tab" href="#templates">Email Templates</a>
											</li>
											<li class="nav-item">
												<a class="nav-link" data-bs-toggle="tab" href="#test">Test Email</a>
											</li>
											<li class="nav-item">
												<a class="nav-link" data-bs-toggle="tab" href="#logs">Email Logs</a>
											</li>
										</ul>
										
										<div class="tab-content mt-4">
											<!-- SMTP Settings Tab -->
											<div class="tab-pane fade show active" id="smtp">
												<form method="POST">
													<input type="hidden" name="action" value="save_smtp">
													
													<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="host" value="<?php echo htmlspecialchars($mail_settings['host'] ?: 'smtp.gmail.com'); ?>" required>
																<small class="text-mute">e.g., smtp.gmail.com, smtp.sendgrid.net</small>
															</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="port" value="<?php echo htmlspecialchars($mail_settings['port'] ?: 587); ?>" required>
																<small class="text-mute">Common ports: 587 (TLS), 465 (SSL), 25 (Standard)</small>
															</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="username" value="<?php echo htmlspecialchars($mail_settings['username'] ?: ''); ?>" required>
																<small class="text-mute">Your email address or SMTP username</small>
															</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="password" value="<?php echo htmlspecialchars($mail_settings['password'] ?: ''); ?>" required>
																<small class="text-mute">App password for Gmail or SMTP password</small>
															</div>
														</div>
													</div>
													
													<div class="row">
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">Encryption <span class="text-danger">*</span></label>
																<select class="form-control" name="encryption" required>
																	<option value="tls" <?php echo ($mail_settings['encryption'] ?: 'tls') == 'tls' ? 'selected' : ''; ?>>TLS (Recommended)</option>
																	<option value="ssl" <?php echo ($mail_settings['encryption'] ?: '') == 'ssl' ? 'selected' : ''; ?>>SSL</option>
																	<option value="" <?php echo empty($mail_settings['encryption'] ?: '') ? 'selected' : ''; ?>>None</option>
																</select>
															</div>
														</div>
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">Base URL <span class="text-danger">*</span></label>
																<input type="url" class="form-control" name="url" value="<?php echo htmlspecialchars($mail_settings['url'] ?: 'http://localhost/ai_trading/'); ?>" required>
																<small class="text-mute">Website URL for links in emails</small>
															</div>
														</div>
													</div>
													
													<div class="row">
														<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 htmlspecialchars($mail_settings['from_name'] ?: 'AI Trading Platform'); ?>" required>
																<small class="text-mute">Display name for sender</small>
															</div>
														</div>
														<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 htmlspecialchars($mail_settings['from_email'] ?: 'noreply@aitrading.com'); ?>" required>
																<small class="text-mute">Email address for sender</small>
															</div>
														</div>
													</div>
													
													<div class="row">
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">Reply-To Email</label>
																<input type="email" class="form-control" name="reply_to" value="<?php echo htmlspecialchars($mail_settings['reply_to'] ?: 'support@aitrading.com'); ?>">
																<small class="text-mute">Where replies should be sent</small>
															</div>
														</div>
														<div class="col-md-6">
															<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>
														</div>
													</div>
													
													<div class="mt-4">
														<button type="submit" class="btn btn-primary">
															<i class="fas fa-save me-1"></i> Save SMTP Settings
														</button>
														<button type="button" class="btn btn-secondary" onclick="testCurrentSettings()">
															<i class="fas fa-paper-plane me-1"></i> Test Current Settings
														</button>
													</div>
												</form>
												
												<div class="mt-4">
													<h5><i class="fas fa-info-circle me-2"></i>SMTP Configuration Guide</h5>
													<div class="alert alert-info">
														<h6>For Gmail:</h6>
														<ul class="mb-0">
															<li>Host: smtp.gmail.com</li>
															<li>Port: 587 (TLS) or 465 (SSL)</li>
															<li>Username: Your full Gmail address</li>
															<li>Password: <a href="https://myaccount.google.com/apppasswords" target="_blank">App Password</a> (2FA required)</li>
															<li>Encryption: TLS (recommended)</li>
														</ul>
													</div>
												</div>
											</div>
											
											<!-- Email Templates Tab -->
											<div class="tab-pane fade" id="templates">
												<div class="row">
													<div class="col-md-4">
														<div class="list-group" id="templateList">
															<?php if ($templates_result && mysqli_num_rows($templates_result) > 0): ?>
																<?php while ($template = mysqli_fetch_assoc($templates_result)): ?>
																	<a href="javascript:void(0)" 
																	   class="list-group-item list-group-item-action template-item <?php echo $template['id'] == 1 ? 'active' : ''; ?>" 
																	   data-id="<?php echo $template['id']; ?>"
																	   data-name="<?php echo htmlspecialchars($template['template_name']); ?>"
																	   data-type="<?php echo $template['template_type']; ?>"
																	   data-subject="<?php echo htmlspecialchars($template['subject']); ?>"
																	   data-content="<?php echo htmlspecialchars($template['content']); ?>"
																	   data-variables="<?php echo htmlspecialchars($template['variables'] ?: ''); ?>"
																	   data-active="<?php echo $template['is_active']; ?>">
																		<div class="d-flex w-100 justify-content-between">
																			<h6 class="mb-1"><?php echo htmlspecialchars($template['template_name']); ?></h6>
																			<small>
																				<?php if ($template['is_active']): ?>
																					<span class="badge bg-success">Active</span>
																				<?php else: ?>
																					<span class="badge bg-secondary">Inactive</span>
																				<?php endif; ?>
																			</small>
																		</div>
																		<small class="text-mute">Type: <?php echo ucfirst($template['template_type']); ?></small>
																	</a>
																<?php endwhile; ?>
															<?php else: ?>
																<div class="alert alert-info">No email templates found.</div>
															<?php endif; ?>
														</div>
														
														<div class="mt-3">
															<button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#newTemplateModal">
																<i class="fas fa-plus me-1"></i> New Template
															</button>
														</div>
													</div>
													
													<div class="col-md-8">
														<form method="POST" id="templateForm">
															<input type="hidden" name="action" value="save_template">
															<input type="hidden" name="template_id" id="templateId" value="1">
															
															<div class="mb-3">
																<label class="form-label">Template Name <span class="text-danger">*</span></label>
																<input type="text" class="form-control" id="templateName" name="template_name" required readonly>
															</div>
															
															<div class="mb-3">
																<label class="form-label">Template Type</label>
																<input type="text" class="form-control" id="templateType" readonly>
															</div>
															
															<div class="mb-3">
																<label class="form-label">Subject <span class="text-danger">*</span></label>
																<input type="text" class="form-control" id="templateSubject" name="subject" required>
															</div>
															
															<div class="mb-3">
																<label class="form-label">Available Variables</label>
																<div class="alert alert-light" id="variablesList">
																	<small>Select a template to see available variables</small>
																</div>
															</div>
															
															<div class="mb-3">
																<label class="form-label">Email Content (HTML) <span class="text-danger">*</span></label>
																<textarea class="form-control" id="templateContent" name="content" rows="15" required></textarea>
																<small class="text-mute">Use HTML for formatting. Include variables like {first_name}, {email}, etc.</small>
															</div>
															
															<div class="mb-3">
																<div class="form-check">
																	<input class="form-check-input" type="checkbox" id="templateActive" name="is_active" value="1">
																	<label class="form-check-label" for="templateActive">
																		Active (Send emails using this template)
																	</label>
																</div>
															</div>
															
															<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>
															
															<div class="mt-4">
																<button type="submit" class="btn btn-primary">
																	<i class="fas fa-save me-1"></i> Save Template
																</button>
																<button type="button" class="btn btn-danger" id="deleteTemplateBtn">
																	<i class="fas fa-trash me-1"></i> Delete Template
																</button>
																<button type="button" class="btn btn-secondary" onclick="previewTemplate()">
																	<i class="fas fa-eye me-1"></i> Preview
																</button>
															</div>
														</form>
													</div>
												</div>
											</div>
											
											<!-- Test Email Tab -->
											<div class="tab-pane fade" id="test">
												<div class="row">
													<div class="col-md-6">
														<div class="box">
															<div class="box-header">
																<h5 class="box-title">Send Test Email</h5>
															</div>
															<div class="box-body">
																<form method="POST">
																	<input type="hidden" name="action" value="test_email">
																	
																	<div class="mb-3">
																		<label class="form-label">Test Email Address <span class="text-danger">*</span></label>
																		<input type="email" class="form-control" name="test_email" required placeholder="Enter email to send test">
																		<small class="text-mute">Send a test email to verify your SMTP settings</small>
																	</div>
																	
																	<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-paper-plane me-1"></i> Send Test Email
																	</button>
																</form>
															</div>
														</div>
													</div>
													
													<div class="col-md-6">
														<div class="box">
															<div class="box-header">
																<h5 class="box-title">Current SMTP Settings</h5>
															</div>
															<div class="box-body">
																<table class="table table-sm">
																	<tr>
																		<td><strong>Host:</strong></td>
																		<td><?php echo htmlspecialchars($mail_settings['host'] ?: 'Not set'); ?></td>
																	</tr>
																	<tr>
																		<td><strong>Port:</strong></td>
																		<td><?php echo htmlspecialchars($mail_settings['port'] ?: 'Not set'); ?></td>
																	</tr>
																	<tr>
																		<td><strong>Username:</strong></td>
																		<td><?php echo htmlspecialchars($mail_settings['username'] ?: 'Not set'); ?></td>
																	</tr>
																	<tr>
																		<td><strong>From Name:</strong></td>
																		<td><?php echo htmlspecialchars($mail_settings['from_name'] ?: 'Not set'); ?></td>
																	</tr>
																	<tr>
																		<td><strong>From Email:</strong></td>
																		<td><?php echo htmlspecialchars($mail_settings['from_email'] ?: 'Not set'); ?></td>
																	</tr>
																	<tr>
																		<td><strong>Encryption:</strong></td>
																		<td><?php echo htmlspecialchars($mail_settings['encryption'] ?: 'Not set'); ?></td>
																	</tr>
																</table>
															</div>
														</div>
													</div>
												</div>
											</div>
											
											<!-- Email Logs Tab -->
											<div class="tab-pane fade" id="logs">
												<div class="alert alert-info">
													<i class="fas fa-info-circle me-2"></i> 
													Email logging will be implemented in the next update. This will track all emails sent from the system.
												</div>
												
												<!-- Placeholder for future email logs table -->
												<div class="table-responsive">
													<table class="table table-hover">
														<thead>
															<tr>
																<th>ID</th>
																<th>Recipient</th>
																<th>Subject</th>
																<th>Template</th>
																<th>Status</th>
																<th>Sent At</th>
															</tr>
														</thead>
														<tbody>
															<tr>
																<td colspan="6" class="text-center py-20 text-mute">
																	<i class="fas fa-inbox fa-2x mb-3"></i><br>
																	Email logging feature coming soon
																</td>
															</tr>
														</tbody>
													</table>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</section>
					<!-- /.content -->
				</div>
			</div>
		  	
		  <?php include('includes/footer.php') ?>

		  <?php include('includes/control_sidebar.php') ?>
			
		</div>
		<!-- ./wrapper -->
		
		<!-- Modal for New Template -->
		<div class="modal fade" id="newTemplateModal" tabindex="-1" aria-labelledby="newTemplateModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST" action="add_email_template.php">
						<div class="modal-header">
							<h5 class="modal-title" id="newTemplateModalLabel">New Email Template</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<div class="mb-3">
								<label class="form-label">Template Name <span class="text-danger">*</span></label>
								<input type="text" class="form-control" name="template_name" required>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Template Type <span class="text-danger">*</span></label>
								<select class="form-control" name="template_type" required>
									<option value="welcome">Welcome Email</option>
									<option value="verification">Account Verification</option>
									<option value="password_reset">Password Reset</option>
									<option value="deposit">Deposit Notification</option>
									<option value="withdrawal">Withdrawal Notification</option>
									<option value="notification">General Notification</option>
									<option value="newsletter">Newsletter</option>
								</select>
							</div>
							
							<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>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
							<button type="submit" class="btn btn-primary">Create Template</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Preview -->
		<div class="modal fade" id="previewModal" tabindex="-1" aria-labelledby="previewModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title" id="previewModalLabel">Email Preview</h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body" id="previewContent">
						<!-- Preview will be loaded here -->
					</div>
				</div>
			</div>
		</div>
		
		  
    
		
		
		  <?php include('includes/scripts.php') ?>
		
		<!-- SweetAlert2 -->
		<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
		
		<script>
		$(document).ready(function() {
			// Load first template by default
			loadTemplate(1);
			
			// Template selection
			$('.template-item').click(function() {
				$('.template-item').removeClass('active');
				$(this).addClass('active');
				
				var templateId = $(this).data('id');
				loadTemplate(templateId);
			});
			
			// Delete template button
			$('#deleteTemplateBtn').click(function() {
				var templateId = $('#templateId').val();
				var templateName = $('#templateName').val();
				
				if (templateId) {
					Swal.fire({
						title: 'Delete Template?',
						html: `Are you sure you want to delete template "<strong>${templateName}</strong>"?<br><br>
							   <div class="mt-3">
								   <label class="form-label">Enter Admin PIN to confirm:</label>
								   <input type="password" id="swalPin" class="form-control" placeholder="4-digit PIN" autocomplete="off">
							   </div>`,
						icon: 'warning',
						showCancelButton: true,
						confirmButtonColor: '#d33',
						cancelButtonColor: '#3085d6',
						confirmButtonText: 'Delete Template',
						cancelButtonText: 'Cancel',
						preConfirm: () => {
							const pin = document.getElementById('swalPin').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) {
							// Submit delete request
							$.ajax({
								url: 'ajax/delete_email_template.php',
								type: 'POST',
								data: {
									template_id: templateId,
									admin_pin: result.value.pin
								},
								success: function(response) {
									var data = JSON.parse(response);
									if (data.success) {
										Swal.fire({
											title: 'Deleted!',
											text: 'Template deleted successfully.',
											icon: 'success'
										}).then(() => {
											location.reload();
										});
									} else {
										Swal.fire('Error!', data.message, 'error');
									}
								}
							});
						}
					});
				}
			});
		});
		
		function loadTemplate(templateId) {
			var templateItem = $('.template-item[data-id="' + templateId + '"]');
			if (templateItem.length) {
				$('#templateId').val(templateId);
				$('#templateName').val(templateItem.data('name'));
				$('#templateType').val(templateItem.data('type'));
				$('#templateSubject').val(templateItem.data('subject'));
				$('#templateContent').val(templateItem.data('content'));
				$('#templateActive').prop('checked', templateItem.data('active') == '1');
				
				// Show variables
				var variables = templateItem.data('variables');
				if (variables) {
					var varsArray = variables.split(',');
					var varsHtml = '<small>Available variables: ';
					varsArray.forEach(function(variable, index) {
						varsHtml += '<code class="me-1">' + variable.trim() + '</code>';
						if ((index + 1) % 3 === 0) varsHtml += '<br>';
					});
					varsHtml += '</small>';
					$('#variablesList').html(varsHtml);
				} else {
					$('#variablesList').html('<small>No variables defined</small>');
				}
			}
		}
		
		function previewTemplate() {
			var subject = $('#templateSubject').val();
			var content = $('#templateContent').val();
			
			// Replace variables with sample data
			var previewContent = content
				.replace(/{first_name}/g, 'John')
				.replace(/{last_name}/g, 'Doe')
				.replace(/{username}/g, 'johndoe')
				.replace(/{email}/g, 'john.doe@example.com')
				.replace(/{verification_url}/g, 'https://yourdomain.com/verify/abc123')
				.replace(/{reset_url}/g, 'https://yourdomain.com/reset/xyz789')
				.replace(/{login_url}/g, 'https://yourdomain.com/login')
				.replace(/{status}/g, 'Verified');
			
			$('#previewModalLabel').text('Preview: ' + subject);
			$('#previewContent').html(previewContent);
			$('#previewModal').modal('show');
		}
		
		function testCurrentSettings() {
			Swal.fire({
				title: 'Test Current Settings',
				html: `Enter an email address to test current SMTP settings:<br><br>
					   <input type="email" id="testEmail" class="form-control" placeholder="test@example.com" autocomplete="off">
					   <div class="mt-3">
						   <label class="form-label">Admin PIN:</label>
						   <input type="password" id="testPin" class="form-control" placeholder="4-digit PIN" autocomplete="off">
					   </div>`,
				showCancelButton: true,
				confirmButtonText: 'Send Test',
				cancelButtonText: 'Cancel',
				preConfirm: () => {
					const email = document.getElementById('testEmail').value;
					const pin = document.getElementById('testPin').value;
					
					if (!email || !pin) {
						Swal.showValidationMessage('Please fill all fields');
					} else if (!validateEmail(email)) {
						Swal.showValidationMessage('Please enter a valid email');
					} else if (pin.length !== 4) {
						Swal.showValidationMessage('PIN must be 4 digits');
					}
					
					return { email: email, pin: pin };
				}
			}).then((result) => {
				if (result.isConfirmed) {
					// Submit test request
					$.ajax({
						url: 'ajax/test_email.php',
						type: 'POST',
						data: {
							test_email: result.value.email,
							admin_pin: result.value.pin
						},
						success: function(response) {
							var data = JSON.parse(response);
							if (data.success) {
								Swal.fire('Success!', data.message, 'success');
							} else {
								Swal.fire('Error!', data.message, 'error');
							}
						}
					});
				}
			});
		}
		
		function validateEmail(email) {
			var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
			return re.test(email);
		}
		</script>
		
		<style>
		.nav-tabs .nav-link.active {
			background-color: #f8f9fa;
			border-color: #dee2e6 #dee2e6 #f8f9fa;
		}
		.template-item.active {
			background-color: #e3f2fd;
			border-color: #0d6efd;
		}
		#templateContent {
			font-family: 'Courier New', monospace;
			font-size: 14px;
		}
		.preview-modal .modal-body {
			min-height: 400px;
		}
		</style>
		
	</body>
</html>