<?php
/**
 * Razorhost OTP Email Setup Script
 * Sets up database tables and verifies configuration
 */

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

$db = Database::getInstance();
$pdo = $db->getConnection();

echo "╔════════════════════════════════════════════════════════╗\n";
echo "║  RAZORHOST OTP EMAIL SETUP & VERIFICATION              ║\n";
echo "╚════════════════════════════════════════════════════════╝\n\n";

// Step 1: Verify email configuration
echo "STEP 1: Checking Email Configuration\n";
echo "─────────────────────────────────────\n";

$emailConfig = require 'config/email_config.php';
echo "✓ Email Mode: " . $emailConfig['mode'] . "\n";
echo "✓ From Email: " . $emailConfig['from_email'] . "\n";
echo "✓ From Name: " . $emailConfig['from_name'] . "\n";
echo "✓ OTP Expiry: " . $emailConfig['otp_expiry_minutes'] . " minutes\n";
echo "✓ Max Attempts: " . $emailConfig['otp_max_attempts'] . "\n\n";

if ($emailConfig['mode'] === 'mail_relay') {
    echo "✓ Mail Relay Config:\n";
    echo "  • Host: " . ($emailConfig['mail_relay']['host'] ?? 'localhost') . "\n";
    echo "  • Port: " . ($emailConfig['mail_relay']['port'] ?? 25) . "\n";
    echo "  • Auth Required: " . (($emailConfig['mail_relay']['require_auth'] ?? false) ? 'Yes' : 'No') . "\n\n";
}

// Step 2: Create database tables
echo "STEP 2: Creating Database Tables\n";
echo "───────────────────────────────────\n";

try {
    // Create email_otps table
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS email_otps (
            id INT PRIMARY KEY AUTO_INCREMENT,
            email VARCHAR(255) NOT NULL,
            otp VARCHAR(6) NOT NULL,
            attempts INT DEFAULT 0,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            expires_at DATETIME NOT NULL,
            UNIQUE KEY unique_email (email)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");
    echo "✓ email_otps table created/verified\n";
    
    // Create admin_settings table if needed
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS admin_settings (
            id INT PRIMARY KEY AUTO_INCREMENT,
            setting_key VARCHAR(100) UNIQUE,
            setting_value LONGTEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");
    echo "✓ admin_settings table created/verified\n\n";
    
    // Check users table columns
    $result = $pdo->query("SHOW COLUMNS FROM users")->fetchAll(PDO::FETCH_ASSOC);
    $columnNames = array_column($result, 'Field');
    
    $requiredColumns = ['email_verified', 'email_verified_at', 'is_active'];
    $missingColumns = array_diff($requiredColumns, $columnNames);
    
    if (!empty($missingColumns)) {
        echo "✓ Adding missing columns to users table...\n";
        
        if (in_array('email_verified', $missingColumns)) {
            $pdo->exec("ALTER TABLE users ADD COLUMN email_verified TINYINT DEFAULT 0");
            echo "  • Added email_verified column\n";
        }
        
        if (in_array('email_verified_at', $missingColumns)) {
            $pdo->exec("ALTER TABLE users ADD COLUMN email_verified_at DATETIME NULL");
            echo "  • Added email_verified_at column\n";
        }
        
        if (in_array('is_active', $missingColumns)) {
            $pdo->exec("ALTER TABLE users ADD COLUMN is_active TINYINT DEFAULT 1");
            echo "  • Added is_active column\n";
        }
    } else {
        echo "✓ All required users table columns exist\n";
    }
    
    echo "\n";
    
} catch (PDOException $e) {
    if (strpos($e->getMessage(), 'already exists') !== false) {
        echo "✓ Tables already exist\n\n";
    } else {
        echo "✗ Error: " . $e->getMessage() . "\n\n";
        exit(1);
    }
}

// Step 3: Verify database connection
echo "STEP 3: Testing Database Connection\n";
echo "────────────────────────────────────\n";

try {
    $test = $pdo->query("SELECT 1")->fetch();
    echo "✓ Database connection successful\n\n";
} catch (Exception $e) {
    echo "✗ Database connection failed: " . $e->getMessage() . "\n\n";
    exit(1);
}

// Step 4: Test OTP functions
echo "STEP 4: Testing OTP Manager\n";
echo "──────────────────────────────\n";

try {
    require_once 'classes/OTPManager.php';
    
    $otpManager = new OTPManager($db);
    echo "✓ OTPManager initialized successfully\n";
    
    // Test with a test email
    $testEmail = 'setup-test@example.com';
    echo "✓ Ready to generate OTP (test email: $testEmail)\n\n";
    
} catch (Exception $e) {
    echo "✗ OTPManager error: " . $e->getMessage() . "\n\n";
    exit(1);
}

// Summary
echo "╔════════════════════════════════════════════════════════╗\n";
echo "║  SETUP COMPLETE - READY FOR OTP EMAIL VERIFICATION    ║\n";
echo "╚════════════════════════════════════════════════════════╝\n\n";

echo "NEXT STEPS:\n";
echo "──────────\n";
echo "1. Visit: https://simplechecks.xyz/extract/test_razorhost_otp.php\n";
echo "2. Enter a test email address\n";
echo "3. Click 'Send Test OTP Email'\n";
echo "4. Check your email inbox (and spam folder)\n";
echo "5. If not received, check error logs:\n";
echo "   • /error_log (main application logs)\n";
echo "   • Contact Razorhost support if mail relay is blocked\n\n";

echo "CURRENT CONFIGURATION:\n";
echo "──────────────────────\n";
echo "Mode: " . $emailConfig['mode'] . "\n";
echo "From: " . $emailConfig['from_email'] . "\n";
echo "Database: " . DB_NAME . "\n";
echo "Host: " . DB_HOST . "\n\n";

echo "✅ All systems ready for OTP email verification!\n";
?>
