<?php
/**
 * Debug Email Settings Form Submission
 */

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

$db = Database::getInstance();

echo "=== Email Settings Form Debug ===\n\n";

// Check if form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo "✅ Form submitted via POST\n\n";
    
    // Show all POST data
    echo "POST Data Received:\n";
    foreach ($_POST as $key => $value) {
        if ($key === 'mail_password') {
            echo "  $key = " . str_repeat('*', strlen($value)) . "\n";
        } else {
            echo "  $key = " . substr($value, 0, 50) . (strlen($value) > 50 ? '...' : '') . "\n";
        }
    }
    
    echo "\n";
    
    // Check if save_email_settings is set
    if (isset($_POST['save_email_settings'])) {
        echo "✅ save_email_settings field detected\n";
        
        // Get form values
        $email_mode = trim($_POST['email_mode'] ?? 'smtp');
        $mail_host = trim($_POST['mail_host'] ?? 'smtp.gmail.com');
        $mail_port = trim($_POST['mail_port'] ?? '465');
        $mail_encryption = trim($_POST['mail_encryption'] ?? 'ssl');
        $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');
        
        echo "\nParsed Values:\n";
        echo "  email_mode = $email_mode\n";
        echo "  mail_host = $mail_host\n";
        echo "  mail_port = $mail_port\n";
        echo "  mail_encryption = $mail_encryption\n";
        echo "  mail_username = $mail_username\n";
        echo "  mail_password = " . str_repeat('*', strlen($mail_password)) . "\n";
        echo "  mail_from_email = $mail_from_email\n";
        echo "  mail_from_name = $mail_from_name\n";
        
        // Try to update database
        echo "\n\nAttempting to save to database...\n";
        
        try {
            $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') {
                    echo "⏭️  Skipping empty field: $key\n";
                    continue;
                }
                
                // Check if setting exists
                $exists = $db->fetch(
                    'SELECT id FROM admin_settings WHERE setting_key = ?',
                    [$key]
                );
                
                if ($exists) {
                    $result = $db->update(
                        'admin_settings',
                        ['setting_value' => $value],
                        'setting_key = ?',
                        [$key]
                    );
                    echo "✅ Updated: $key = " . ($value === $mail_password ? str_repeat('*', strlen($value)) : $value) . "\n";
                } else {
                    $result = $db->insert(
                        'admin_settings',
                        [
                            'setting_key' => $key,
                            'setting_value' => $value,
                            'created_at' => date('Y-m-d H:i:s')
                        ]
                    );
                    echo "✅ Created: $key\n";
                }
            }
            
            // Handle password
            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']
                    );
                    echo "✅ Updated: mail_password_encrypted\n";
                } else {
                    $db->insert(
                        'admin_settings',
                        [
                            'setting_key' => 'mail_password_encrypted',
                            'setting_value' => $encrypted_password,
                            'created_at' => date('Y-m-d H:i:s')
                        ]
                    );
                    echo "✅ Created: mail_password_encrypted\n";
                }
            }
            
            echo "\n✅✅✅ EMAIL SETTINGS SAVED SUCCESSFULLY! ✅✅✅\n";
            
        } catch (Exception $e) {
            echo "\n❌ ERROR: " . $e->getMessage() . "\n";
        }
    } else {
        echo "❌ save_email_settings field NOT found\n";
        echo "Make sure the hidden input field is in the form\n";
    }
} else {
    echo "❌ No POST data received\n";
    echo "REQUEST_METHOD = " . $_SERVER['REQUEST_METHOD'] . "\n";
    
    echo "\n=== Current Database Settings ===\n\n";
    $settings = $db->fetchAll('SELECT setting_key, setting_value FROM admin_settings WHERE setting_key LIKE "mail%" OR setting_key = "email_mode"');
    
    foreach ($settings as $setting) {
        echo $setting['setting_key'] . " = " . $setting['setting_value'] . "\n";
    }
}

?>
