<?php
/**
 * Configure SMTP Settings Script
 * Sets up SMTP settings for Titan Email
 */

require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/utils/helpers.php';

echo "========================================\n";
echo "Configuring SMTP Settings\n";
echo "========================================\n\n";

// SMTP Configuration
$smtpConfig = [
    'provider' => 'smtp',
    'host' => 'smtp.titan.email',
    'port' => 465,
    'username' => 'no-reply@b-cb.online',
    'password' => 'Grind365Day$',
    'from_email' => 'no-reply@b-cb.online',
    'from_name' => 'FlashCORE',
    'encryption' => 'ssl' // Port 465 uses SSL/Implicit TLS
];

echo "SMTP Configuration:\n";
echo "  Provider: {$smtpConfig['provider']}\n";
echo "  Host: {$smtpConfig['host']}\n";
echo "  Port: {$smtpConfig['port']}\n";
echo "  Username: {$smtpConfig['username']}\n";
echo "  From Email: {$smtpConfig['from_email']}\n";
echo "  From Name: {$smtpConfig['from_name']}\n";
echo "  Encryption: {$smtpConfig['encryption']}\n\n";

try {
    // Start transaction
    $pdo->beginTransaction();
    
    // Deactivate all existing SMTP settings
    $stmt = $pdo->prepare("UPDATE smtp_settings SET is_active = FALSE");
    $stmt->execute();
    echo "✅ Deactivated existing SMTP settings\n";
    
    // Check if SMTP settings already exist
    $stmt = $pdo->prepare("SELECT id FROM smtp_settings WHERE provider = 'smtp' LIMIT 1");
    $stmt->execute();
    $existing = $stmt->fetch();
    
    if ($existing) {
        // Update existing settings
        $stmt = $pdo->prepare("
            UPDATE smtp_settings 
            SET host = ?, port = ?, username = ?, password = ?, 
                from_email = ?, from_name = ?, 
                is_active = TRUE, updated_at = datetime('now') 
            WHERE id = ?
        ");
        $stmt->execute([
            $smtpConfig['host'],
            $smtpConfig['port'],
            $smtpConfig['username'],
            $smtpConfig['password'],
            $smtpConfig['from_email'],
            $smtpConfig['from_name'],
            $existing['id']
        ]);
        $settingsId = $existing['id'];
        echo "✅ Updated existing SMTP settings (ID: $settingsId)\n";
    } else {
        // Insert new settings
        $settingsId = generateUUID();
        $stmt = $pdo->prepare("
            INSERT INTO smtp_settings 
            (id, provider, host, port, username, password, from_email, from_name, is_active, created_at, updated_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, TRUE, datetime('now'), datetime('now'))
        ");
        $stmt->execute([
            $settingsId,
            $smtpConfig['provider'],
            $smtpConfig['host'],
            $smtpConfig['port'],
            $smtpConfig['username'],
            $smtpConfig['password'],
            $smtpConfig['from_email'],
            $smtpConfig['from_name']
        ]);
        echo "✅ Created new SMTP settings (ID: $settingsId)\n";
    }
    
    // Commit transaction
    $pdo->commit();
    
    // Verify the settings
    $stmt = $pdo->prepare("SELECT * FROM smtp_settings WHERE id = ?");
    $stmt->execute([$settingsId]);
    $savedSettings = $stmt->fetch();
    
    if ($savedSettings && $savedSettings['is_active']) {
        echo "\n✅ SMTP settings configured successfully!\n\n";
        echo "Active Settings:\n";
        echo "  Provider: {$savedSettings['provider']}\n";
        echo "  Host: {$savedSettings['host']}\n";
        echo "  Port: {$savedSettings['port']}\n";
        echo "  Username: {$savedSettings['username']}\n";
        echo "  From Email: {$savedSettings['from_email']}\n";
        echo "  From Name: {$savedSettings['from_name']}\n";
        echo "  Active: " . ($savedSettings['is_active'] ? 'Yes' : 'No') . "\n";
    } else {
        throw new Exception("Settings were not saved correctly");
    }
    
} catch (Exception $e) {
    // Rollback transaction
    $pdo->rollback();
    echo "❌ ERROR: " . $e->getMessage() . "\n";
    exit(1);
}

echo "\n========================================\n";
echo "Configuration Complete\n";
echo "========================================\n";

