<?php
/**
 * Simple Email Settings Test Form
 * Direct form without complications
 */

require_once 'config/config.php';
require_once 'classes/Database.php';

$db = Database::getInstance();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_settings'])) {
    echo "<div style='background: #d4edda; padding: 15px; border-radius: 5px; margin: 10px 0; color: #155724;'>";
    echo "<strong>✅ Processing form submission...</strong><br>";
    
    // Get form values
    $email_mode = $_POST['email_mode'] ?? 'smtp';
    $mail_host = $_POST['mail_host'] ?? '';
    $mail_port = $_POST['mail_port'] ?? '';
    $mail_encryption = $_POST['mail_encryption'] ?? '';
    $mail_username = $_POST['mail_username'] ?? '';
    $mail_password = $_POST['mail_password'] ?? '';
    $mail_from_email = $_POST['mail_from_email'] ?? '';
    $mail_from_name = $_POST['mail_from_name'] ?? '';
    
    echo "Received values:<br>";
    echo "- email_mode: $email_mode<br>";
    echo "- mail_host: $mail_host<br>";
    echo "- mail_port: $mail_port<br>";
    echo "- mail_encryption: $mail_encryption<br>";
    echo "- mail_username: $mail_username<br>";
    echo "- mail_from_email: $mail_from_email<br>";
    echo "- mail_from_name: $mail_from_name<br>";
    
    // Update database
    try {
        $settings = [
            'email_mode' => $email_mode,
            'mail_host' => $mail_host,
            'mail_port' => $mail_port,
            'mail_encryption' => $mail_encryption,
            'mail_username' => $mail_username,
            'mail_from_email' => $mail_from_email,
            'mail_from_name' => $mail_from_name
        ];
        
        foreach ($settings as $key => $value) {
            if (empty($value) && $key !== 'email_mode' && $key !== 'mail_from_name') {
                continue;
            }
            
            $result = $db->update(
                'admin_settings',
                ['setting_value' => $value],
                'setting_key = ?',
                [$key]
            );
        }
        
        // Handle password separately
        if (!empty($mail_password)) {
            $encrypted = base64_encode($mail_password);
            $db->update(
                'admin_settings',
                ['setting_value' => $encrypted],
                'setting_key = ?',
                ['mail_password_encrypted']
            );
        }
        
        echo "<br><strong style='color: green;'>✅ Settings saved successfully!</strong><br>";
        echo "Redirecting in 2 seconds...";
        echo "<script>setTimeout(function() { location.reload(); }, 2000);</script>";
        
    } catch (Exception $e) {
        echo "<br><strong style='color: red;'>❌ Error: " . $e->getMessage() . "</strong>";
    }
    
    echo "</div>";
}

// Fetch current settings
$settings = [];
$keys = ['email_mode', 'mail_host', 'mail_port', 'mail_encryption', 'mail_username', 'mail_from_email', 'mail_from_name'];

foreach ($keys as $key) {
    $row = $db->fetch('SELECT setting_value FROM admin_settings WHERE setting_key = ?', [$key]);
    $settings[$key] = $row['setting_value'] ?? '';
}

$pass = $db->fetch('SELECT setting_value FROM admin_settings WHERE setting_key = ?', ['mail_password_encrypted']);
$hasPassword = !empty($pass['setting_value']);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Email Settings</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { padding: 20px; background: #f5f5f5; }
        .container { max-width: 600px; background: white; padding: 30px; border-radius: 10px; }
        h1 { color: #333; margin-bottom: 30px; }
        .form-group { margin-bottom: 20px; }
        label { font-weight: bold; }
    </style>
</head>
<body>
    <div class="container">
        <h1>📧 Email Settings</h1>
        
        <form method="POST" id="emailForm">
            <div class="form-group">
                <label>Email Mode</label>
                <select name="email_mode" class="form-control">
                    <option value="smtp" <?= $settings['email_mode'] === 'smtp' ? 'selected' : '' ?>>SMTP</option>
                    <option value="php_mail" <?= $settings['email_mode'] === 'php_mail' ? 'selected' : '' ?>>PHP Mail</option>
                </select>
            </div>

            <div class="form-group">
                <label>SMTP Host</label>
                <input type="text" name="mail_host" class="form-control" value="<?= htmlspecialchars($settings['mail_host']) ?>" placeholder="smtp.gmail.com">
            </div>

            <div class="form-group">
                <label>SMTP Port</label>
                <input type="number" name="mail_port" class="form-control" value="<?= htmlspecialchars($settings['mail_port']) ?>" placeholder="465">
            </div>

            <div class="form-group">
                <label>Encryption</label>
                <select name="mail_encryption" class="form-control">
                    <option value="tls" <?= $settings['mail_encryption'] === 'tls' ? 'selected' : '' ?>>TLS</option>
                    <option value="ssl" <?= $settings['mail_encryption'] === 'ssl' ? 'selected' : '' ?>>SSL</option>
                    <option value="none" <?= $settings['mail_encryption'] === 'none' ? 'selected' : '' ?>>None</option>
                </select>
            </div>

            <div class="form-group">
                <label>Email Username</label>
                <input type="email" name="mail_username" class="form-control" value="<?= htmlspecialchars($settings['mail_username']) ?>" placeholder="your-email@gmail.com">
            </div>

            <div class="form-group">
                <label>Email Password</label>
                <input type="password" name="mail_password" class="form-control" placeholder="<?= $hasPassword ? 'Leave empty to keep current' : 'Enter password' ?>">
                <?php if ($hasPassword): ?>
                    <small class="text-success">✓ Password already set</small>
                <?php endif; ?>
            </div>

            <div class="form-group">
                <label>From Email</label>
                <input type="email" name="mail_from_email" class="form-control" value="<?= htmlspecialchars($settings['mail_from_email']) ?>" placeholder="noreply@yourdomain.com">
            </div>

            <div class="form-group">
                <label>From Name</label>
                <input type="text" name="mail_from_name" class="form-control" value="<?= htmlspecialchars($settings['mail_from_name']) ?>" placeholder="Company Name">
            </div>

            <button type="submit" name="save_settings" class="btn btn-primary btn-lg" onclick="return confirm('Save these email settings?')">
                💾 Save Settings
            </button>
        </form>

        <hr>

        <h4>📋 Current Settings in Database:</h4>
        <pre style="background: #f8f9fa; padding: 10px; border-radius: 5px;">
<?php
foreach ($keys as $key) {
    echo "$key = " . htmlspecialchars($settings[$key]) . "\n";
}
?>
        </pre>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
