<?php
/**
 * Admin Email Settings Page
 * Digital Marketplace
 */

require_once __DIR__ . '/../config/database.php';
require_login();

if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
    header('Location: ' . BASE_URL . '/index.php');
    exit;
}

$page_title = 'Email Settings';

$errors = [];
$success = false;

// Get current email settings
$email_settings = get_email_settings();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid request. Please try again.';
    } else {
        // Update email settings
        $settings_to_update = [
            'smtp_host',
            'smtp_port',
            'smtp_username',
            'smtp_password',
            'smtp_encryption',
            'smtp_from_email',
            'smtp_from_name'
        ];
        
        foreach ($settings_to_update as $key) {
            $value = sanitize($_POST[$key] ?? '');
            
            // Save to database
            try {
                $stmt = $pdo->prepare("INSERT INTO email_settings (setting_key, setting_value, created_at, updated_at) 
                                       VALUES (?, ?, NOW(), NOW()) 
                                       ON DUPLICATE KEY UPDATE setting_value = ?, updated_at = NOW()");
                $stmt->execute([$key, $value, $value]);
            } catch (PDOException $e) {
                $errors[] = "Failed to save {$key}: " . $e->getMessage();
            }
        }
        
        if (empty($errors)) {
            $success = true;
            set_flash_message('Email settings updated successfully!', 'success');
            
            // Refresh settings
            $email_settings = get_email_settings();
        }
    }
}

include __DIR__ . '/includes/header.php';
?>

<div class="admin-content">
    <div class="admin-header">
        <h1><i class="fas fa-envelope me-2"></i>Email Settings</h1>
    </div>
    
    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <?php foreach ($errors as $error): ?>
                <p class="mb-1"><i class="fas fa-exclamation-circle me-2"></i><?php echo $error; ?></p>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
    
    <div class="row">
        <div class="col-lg-8">
            <form method="POST">
                <?php echo csrf_field(); ?>
                
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-server me-2"></i>SMTP Configuration</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-8 mb-3">
                                <label class="form-label">SMTP Host</label>
                                <input type="text" name="smtp_host" class="form-control" 
                                       value="<?php echo sanitize($email_settings['smtp_host'] ?? 'smtp.gmail.com'); ?>"
                                       placeholder="smtp.gmail.com">
                                <small class="text-muted">e.g., smtp.gmail.com, smtp.office365.com</small>
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">SMTP Port</label>
                                <input type="number" name="smtp_port" class="form-control" 
                                       value="<?php echo sanitize($email_settings['smtp_port'] ?? '587'); ?>"
                                       placeholder="587">
                                <small class="text-muted">Usually 587 (TLS) or 465 (SSL)</small>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Encryption</label>
                            <select name="smtp_encryption" class="form-select">
                                <option value="tls" <?php echo ($email_settings['smtp_encryption'] ?? 'tls') === 'tls' ? 'selected' : ''; ?>>TLS</option>
                                <option value="ssl" <?php echo ($email_settings['smtp_encryption'] ?? '') === 'ssl' ? 'selected' : ''; ?>>SSL</option>
                                <option value="" <?php echo ($email_settings['smtp_encryption'] ?? '') === '' ? 'selected' : ''; ?>>None</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">SMTP Username</label>
                            <input type="text" name="smtp_username" class="form-control" 
                                   value="<?php echo sanitize($email_settings['smtp_username'] ?? ''); ?>"
                                   placeholder="your-email@gmail.com">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">SMTP Password</label>
                            <input type="password" name="smtp_password" class="form-control" 
                                   value="<?php echo sanitize($email_settings['smtp_password'] ?? ''); ?>"
                                   placeholder="Your SMTP password or app password">
                            <small class="text-muted">For Gmail, use an <a href="https://myaccount.google.com/apppasswords" target="_blank">App Password</a></small>
                        </div>
                    </div>
                </div>
                
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-user me-2"></i>Sender Information</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">From Email</label>
                            <input type="email" name="smtp_from_email" class="form-control" 
                                   value="<?php echo sanitize($email_settings['smtp_from_email'] ?? ''); ?>"
                                   placeholder="noreply@yourdomain.com">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">From Name</label>
                            <input type="text" name="smtp_from_name" class="form-control" 
                                   value="<?php echo sanitize($email_settings['smtp_from_name'] ?? 'Digital Marketplace'); ?>">
                        </div>
                    </div>
                </div>
                
                <div class="d-flex gap-2">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-2"></i>Save Settings
                    </button>
                    
                    <button type="button" class="btn btn-info" data-bs-toggle="modal" data-bs-target="#testEmailModal">
                        <i class="fas fa-paper-plane me-2"></i>Send Test Email
                    </button>
                </div>
            </form>
        </div>
        
        <div class="col-lg-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-info-circle me-2"></i>Setup Guide</h5>
                </div>
                <div class="card-body">
                    <h6>Gmail SMTP</h6>
                    <ul class="small text-muted">
                        <li>Host: smtp.gmail.com</li>
                        <li>Port: 587</li>
                        <li>Encryption: TLS</li>
                        <li>Use App Password (not your regular password)</li>
                    </ul>
                    
                    <h6>Outlook/Hotmail</h6>
                    <ul class="small text-muted">
                        <li>Host: smtp.office365.com</li>
                        <li>Port: 587</li>
                        <li>Encryption: TLS</li>
                    </ul>
                    
                    <h6>Yahoo Mail</h6>
                    <ul class="small text-muted">
                        <li>Host: smtp.mail.yahoo.com</li>
                        <li>Port: 587</li>
                        <li>Encryption: TLS</li>
                    </ul>
                    
                    <hr>
                    
                    <h6>Important Notes</h6>
                    <ul class="small text-muted">
                        <li>Always use App Passwords for Gmail</li>
                        <li>Enable "Less secure app access" if needed</li>
                        <li>Test settings before going live</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Test Email Modal -->
<div class="modal fade" id="testEmailModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content bg-dark">
            <div class="modal-header">
                <h5 class="modal-title">Send Test Email</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="testEmailForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Test Email Address</label>
                        <input type="email" id="testEmail" class="form-control" placeholder="your-email@example.com" required>
                    </div>
                    <div id="testEmailResult"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-paper-plane me-2"></i>Send Test
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.getElementById('testEmailForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const email = document.getElementById('testEmail').value;
    const resultDiv = document.getElementById('testEmailResult');
    
    resultDiv.innerHTML = '<div class="alert alert-info"><i class="fas fa-spinner fa-spin me-2"></i>Sending test email...</div>';
    
    // AJAX request to send test email
    fetch('<?php echo ADMIN_URL; ?>/ajax/send-test-email.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'email=' + encodeURIComponent(email)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            resultDiv.innerHTML = '<div class="alert alert-success"><i class="fas fa-check-circle me-2"></i>' + data.message + '</div>';
        } else {
            resultDiv.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle me-2"></i>' + data.message + '</div>';
        }
    })
    .catch(error => {
        resultDiv.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle me-2"></i>Failed to send test email</div>';
    });
});
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
