<?php
require_once '../config/database.php';
header('Content-Type: application/json');

try {
    // Check if user is authenticated
    if (!isAuthenticated()) {
        echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
        exit;
    }

    $pdo = getDBConnection();

    // Basic email configuration test
    $email_settings = [
        'smtp_host' => $_POST['smtp_host'] ?? 'localhost',
        'smtp_port' => $_POST['smtp_port'] ?? '587',
        'smtp_username' => $_POST['smtp_username'] ?? '',
        'smtp_password' => $_POST['smtp_password'] ?? '',
        'from_email' => $_POST['from_email'] ?? '',
        'from_name' => $_POST['from_name'] ?? 'KSO Chandigarh'
    ];

    // Simple validation
    if (empty($email_settings['smtp_host']) || empty($email_settings['from_email'])) {
        echo json_encode([
            'success' => false,
            'message' => 'SMTP host and from email are required'
        ]);
        exit;
    }

    // Test email configuration (basic check)
    if (filter_var($email_settings['from_email'], FILTER_VALIDATE_EMAIL)) {
        echo json_encode([
            'success' => true,
            'message' => 'Email configuration appears valid',
            'details' => [
                'smtp_host' => $email_settings['smtp_host'],
                'smtp_port' => $email_settings['smtp_port'],
                'from_email' => $email_settings['from_email']
            ]
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Invalid email address format'
        ]);
    }

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
