<?php
/**
 * Email Settings for Admin Panel
 * Allows admin to configure email credentials
 */

if (!isset($db)) {
    echo '<div class="alert alert-danger">❌ Database connection missing.</div>';
    return;
}

// Debug: Log form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_email_settings'])) {
    error_log('EMAIL SETTINGS FORM SUBMITTED at ' . date('Y-m-d H:i:s'));
    error_log('POST DATA: ' . print_r($_POST, true));
}

// Check if form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_email_settings'])) {
    try {
        $email_mode = trim($_POST['email_mode'] ?? 'smtp');
        $mail_host = trim($_POST['mail_host'] ?? 'smtp.gmail.com');
        $mail_port = trim($_POST['mail_port'] ?? '587');
        $mail_encryption = trim($_POST['mail_encryption'] ?? 'tls');
        $mail_username = trim($_POST['mail_username'] ?? '');
        $mail_password = trim($_POST['mail_password'] ?? '');
        $mail_from_email = trim($_POST['mail_from_email'] ?? '');
        $mail_from_name = trim($_POST['mail_from_name'] ?? 'Advanced Mobile Info');
        
        // Update settings in database
        $settingKeys = [
            'email_mode',
            'mail_host',
            'mail_port',
            'mail_encryption',
            'mail_username',
            'mail_from_email',
            'mail_from_name'
        ];
        
        foreach ($settingKeys as $key) {
            $value = $$key;
            
            // Skip empty values for optional fields
            if (empty($value) && $key !== 'email_mode' && $key !== 'mail_from_name') {
                continue;
            }
            
            // Check if setting exists
            $exists = $db->fetch(
                'SELECT id FROM admin_settings WHERE setting_key = ?',
                [$key]
            );
            
            if ($exists) {
                $db->update(
                    'admin_settings',
                    ['setting_value' => $value],
                    'setting_key = ?',
                    [$key]
                );
            } else {
                $db->insert(
                    'admin_settings',
                    [
                        'setting_key' => $key,
                        'setting_value' => $value,
                        'created_at' => date('Y-m-d H:i:s')
                    ]
                );
            }
        }
        
        // Encrypt and save password separately (ONLY if a new password is provided)
        if (!empty($mail_password)) {
            $encrypted_password = base64_encode($mail_password);
            $exists = $db->fetch(
                'SELECT id FROM admin_settings WHERE setting_key = ?',
                ['mail_password_encrypted']
            );
            
            if ($exists) {
                $db->update(
                    'admin_settings',
                    ['setting_value' => $encrypted_password],
                    'setting_key = ?',
                    ['mail_password_encrypted']
                );
            } else {
                $db->insert(
                    'admin_settings',
                    [
                        'setting_key' => 'mail_password_encrypted',
                        'setting_value' => $encrypted_password,
                        'created_at' => date('Y-m-d H:i:s')
                    ]
                );
            }
        }
        
        echo '<div class="alert alert-success alert-dismissible fade show" role="alert">
                ✅ Email settings updated successfully!
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
              </div>';
        
        // Redirect to prevent form resubmission
        header('Location: ' . $_SERVER['REQUEST_URI'], true, 303);
        exit;
    } catch (Exception $e) {
        echo '<div class="alert alert-danger">❌ Error: ' . htmlspecialchars($e->getMessage()) . '</div>';
    }
}

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

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

// Get encrypted password for display
$passwordSetting = $db->fetch(
    'SELECT setting_value FROM admin_settings WHERE setting_key = ?',
    ['mail_password_encrypted']
);
$hasPassword = !empty($passwordSetting['setting_value']);

?>

<div class="card shadow-sm border-0 mb-4">
    <div class="card-header bg-gradient" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none;">
        <h5 class="mb-0" style="font-size: 1.1rem;">
            <i class="feather" data-feather="mail"></i> Email Configuration
        </h5>
    </div>
    
    <div class="card-body">
        <form method="POST" class="needs-validation">
            <input type="hidden" name="save_email_settings" value="1">
            
            <!-- Email Mode -->
            <div class="row mb-3">
                <label class="col-md-3 col-form-label fw-semibold">Email Mode</label>
                <div class="col-md-9">
                    <select name="email_mode" class="form-select">
                        <option value="smtp" <?= ($settings['email_mode'] === 'smtp' ? 'selected' : '') ?>>SMTP (Recommended)</option>
                        <option value="php_mail" <?= ($settings['email_mode'] === 'php_mail' ? 'selected' : '') ?>>PHP Mail</option>
                    </select>
                    <small class="text-muted d-block mt-1">SMTP is more reliable for production</small>
                </div>
            </div>
            
            <hr class="my-4">
            
            <!-- SMTP Settings -->
            <h6 class="mb-3 fw-semibold text-secondary">📋 SMTP Settings</h6>
            
            <div class="row mb-3">
                <label class="col-md-3 col-form-label">SMTP Host</label>
                <div class="col-md-9">
                    <input type="text" name="mail_host" class="form-control" 
                           value="<?= htmlspecialchars($settings['mail_host']) ?>" 
                           placeholder="smtp.gmail.com">
                    <small class="text-muted d-block mt-1">Example: smtp.gmail.com, smtp.office365.com</small>
                </div>
            </div>
            
            <div class="row mb-3">
                <label class="col-md-3 col-form-label">SMTP Port</label>
                <div class="col-md-9">
                    <input type="number" name="mail_port" class="form-control" 
                           value="<?= htmlspecialchars($settings['mail_port']) ?>" 
                           placeholder="587" min="1" max="65535">
                    <small class="text-muted d-block mt-1">Common: 587 (TLS), 465 (SSL), 25 (Unencrypted)</small>
                </div>
            </div>
            
            <div class="row mb-3">
                <label class="col-md-3 col-form-label">Encryption Type</label>
                <div class="col-md-9">
                    <select name="mail_encryption" class="form-select">
                        <option value="tls" <?= ($settings['mail_encryption'] === 'tls' ? 'selected' : '') ?>>TLS (587)</option>
                        <option value="ssl" <?= ($settings['mail_encryption'] === 'ssl' ? 'selected' : '') ?>>SSL (465)</option>
                        <option value="none" <?= ($settings['mail_encryption'] === 'none' ? 'selected' : '') ?>>None (25)</option>
                    </select>
                </div>
            </div>
            
            <hr class="my-4">
            
            <!-- Authentication -->
            <h6 class="mb-3 fw-semibold text-secondary">🔐 Authentication</h6>
            
            <div class="row mb-3">
                <label class="col-md-3 col-form-label">Email Username</label>
                <div class="col-md-9">
                    <input type="email" name="mail_username" class="form-control" 
                           value="<?= htmlspecialchars($settings['mail_username']) ?>" 
                           placeholder="your-email@gmail.com">
                    <small class="text-muted d-block mt-1">Your Gmail or email account</small>
                </div>
            </div>
            
            <div class="row mb-3">
                <label class="col-md-3 col-form-label">Email Password</label>
                <div class="col-md-9">
                    <input type="password" name="mail_password" class="form-control" 
                           placeholder="<?= $hasPassword ? '••••••••••••••••' : 'Your password or app-specific password' ?>">
                    <small class="text-muted d-block mt-1">
                        ⚠️ <strong>For Gmail:</strong> Use <a href="https://myaccount.google.com/apppasswords" target="_blank">App Password</a> (not your main password)
                    </small>
                    <?php if ($hasPassword): ?>
                        <small class="text-success d-block mt-1">✓ Password already set. Leave empty to keep existing password.</small>
                    <?php endif; ?>
                </div>
            </div>
            
            <hr class="my-4">
            
            <!-- Sender Info -->
            <h6 class="mb-3 fw-semibold text-secondary">📧 Sender Information</h6>
            
            <div class="row mb-3">
                <label class="col-md-3 col-form-label">From Email Address</label>
                <div class="col-md-9">
                    <input type="email" name="mail_from_email" class="form-control" 
                           value="<?= htmlspecialchars($settings['mail_from_email']) ?>" 
                           placeholder="noreply@yourdomain.com">
                    <small class="text-muted d-block mt-1">Email address shown to recipients</small>
                </div>
            </div>
            
            <div class="row mb-3">
                <label class="col-md-3 col-form-label">From Name</label>
                <div class="col-md-9">
                    <input type="text" name="mail_from_name" class="form-control" 
                           value="<?= htmlspecialchars($settings['mail_from_name']) ?>" 
                           placeholder="Advanced Mobile Info">
                    <small class="text-muted d-block mt-1">Name shown in emails (e.g., "Admin" or your company name)</small>
                </div>
            </div>
            
            <!-- Test Email Button -->
            <hr class="my-4">
            
            <div class="row mb-3">
                <div class="col-md-3"></div>
                <div class="col-md-9">
                    <button type="button" class="btn btn-outline-info btn-sm" data-bs-toggle="modal" data-bs-target="#testEmailModal">
                        <i class="feather" data-feather="send"></i> Send Test Email
                    </button>
                    <small class="text-muted d-block mt-2">Click to send a test email to verify settings</small>
                </div>
            </div>
            
            <!-- Submit Button -->
            <div class="row mt-4">
                <div class="col-md-3"></div>
                <div class="col-md-9">
                    <button type="submit" class="btn btn-primary">
                        <i class="feather" data-feather="save"></i> Save Email Settings
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Test Email Modal -->
<div class="modal fade" id="testEmailModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Send Test Email</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="testEmailForm" method="POST">
                <div class="modal-body">
                    <div id="testEmailMessage"></div>
                    <div class="mb-3">
                        <label class="form-label">Test Email Address</label>
                        <input type="email" name="test_email" class="form-control" 
                               placeholder="your-email@example.com" required>
                        <small class="text-muted d-block mt-1">We'll send a test email to this address</small>
                    </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" id="sendTestEmailBtn">Send Test Email</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    feather.replace();
    
    // Test Email Form Handler
    document.getElementById('testEmailForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const testEmail = document.querySelector('input[name="test_email"]').value;
        const messageDiv = document.getElementById('testEmailMessage');
        const submitBtn = document.getElementById('sendTestEmailBtn');
        
        // Clear previous message
        messageDiv.innerHTML = '';
        
        // Disable submit button
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Sending...';
        
        // Send AJAX request
        const formData = new FormData();
        formData.append('test_email', testEmail);
        
        fetch('/extract/admin/api/send_test_email.php', {
            method: 'POST',
            body: formData,
            credentials: 'include'  // Include cookies/session
        })
        .then(response => {
            // Check if response is JSON
            const contentType = response.headers.get("content-type");
            if (!contentType || !contentType.includes("application/json")) {
                throw new Error('Invalid response: ' + response.status);
            }
            if (!response.ok) throw new Error('Network error: ' + response.status);
            return response.json();
        })
        .then(data => {
            // Re-enable button
            submitBtn.disabled = false;
            submitBtn.innerHTML = 'Send Test Email';
            
            if (data.success) {
                messageDiv.innerHTML = '<div class="alert alert-success alert-dismissible fade show" role="alert">' +
                    data.message +
                    '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>' +
                    '</div>';
                
                // Clear email field
                document.querySelector('input[name="test_email"]').value = '';
                
                // Close modal after 3 seconds
                setTimeout(() => {
                    const modal = bootstrap.Modal.getInstance(document.getElementById('testEmailModal'));
                    modal.hide();
                }, 3000);
            } else {
                messageDiv.innerHTML = '<div class="alert alert-danger alert-dismissible fade show" role="alert">' +
                    '❌ ' + data.message +
                    '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>' +
                    '</div>';
            }
        })
        .catch(error => {
            submitBtn.disabled = false;
            submitBtn.innerHTML = 'Send Test Email';
            messageDiv.innerHTML = '<div class="alert alert-danger alert-dismissible fade show" role="alert">' +
                '❌ Error: ' + error.message +
                '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>' +
                '</div>';
        });
    });
</script>
