<?php
/**
 * Reset and Configure Email Settings Properly
 */

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

$db = Database::getInstance();

// Email credentials provided by user
$email = 's26118152@gmail.com';
$password = 'gyiv ebml hzoc otmh';
$from_email = 's26118152@gmail.com';
$from_name = 'Advanced Mobile Info';

echo "=== Configuring Email with Correct Credentials ===\n\n";

// Step 1: Delete old settings
echo "Step 1: Clearing old settings...\n";
$db->query('DELETE FROM admin_settings WHERE setting_key LIKE "mail%"');
$db->query('DELETE FROM admin_settings WHERE setting_key = "email_mode"');
echo "✅ Old settings cleared\n\n";

// Step 2: Insert new settings using port 465 (SSL - which works)
echo "Step 2: Saving new settings...\n";

$newSettings = [
    'email_mode' => 'smtp',
    'mail_host' => 'smtp.gmail.com',
    'mail_port' => '465',
    'mail_encryption' => 'ssl',
    'mail_username' => $email,
    'mail_password_encrypted' => base64_encode($password),
    'mail_from_email' => $from_email,
    'mail_from_name' => $from_name
];

foreach ($newSettings as $key => $value) {
    try {
        $db->insert('admin_settings', [
            'setting_key' => $key,
            'setting_value' => $value,
            'created_at' => date('Y-m-d H:i:s')
        ]);
        echo "✅ Created: $key\n";
    } catch (Exception $e) {
        echo "⚠️  $key: " . $e->getMessage() . "\n";
    }
}

echo "\n✅ Email configured successfully!\n\n";

// Step 3: Display configured settings
echo "=== Current Configuration ===\n";
$settings = $db->fetchAll('SELECT setting_key, setting_value FROM admin_settings WHERE setting_key LIKE "mail%" OR setting_key = "email_mode" ORDER BY setting_key');

foreach ($settings as $setting) {
    $key = $setting['setting_key'];
    $value = $setting['setting_value'];
    
    if ($key === 'mail_password_encrypted') {
        echo sprintf("%-25s = %s\n", $key, str_repeat('*', 20));
    } else {
        echo sprintf("%-25s = %s\n", $key, $value);
    }
}

echo "\n🎉 Configuration Complete!\n";
echo "\nYour email system is configured and ready to:\n";
echo "✅ Send OTP emails\n";
echo "✅ Send verification emails\n";
echo "✅ Send notifications\n";

echo "\nTo test in Admin Dashboard:\n";
echo "1. Go to: http://localhost/extract/admin/dashboard.php?page=email_settings\n";
echo "2. All settings should be filled\n";
echo "3. Click 'Send Test Email'\n";
echo "4. Check inbox for test OTP\n";

?>
