<?php
require_once 'config/database.php';

echo "Checking and creating required database tables...\n";

try {
    // Create settings table if it doesn't exist
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS settings (
            id INT PRIMARY KEY AUTO_INCREMENT,
            setting_key VARCHAR(100) UNIQUE,
            setting_value TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )
    ");
    echo "✓ Settings table created/verified\n";

    // Create messages_log table if it doesn't exist
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS messages_log (
            id INT AUTO_INCREMENT PRIMARY KEY,
            message_type VARCHAR(50) NOT NULL,
            message_content LONGTEXT NOT NULL,
            recipient_count INT DEFAULT 0,
            recipients JSON,
            sent_recipients JSON,
            failed_recipients JSON,
            sender_id INT,
            status ENUM('pending', 'sent', 'delivered', 'failed', 'partial') DEFAULT 'pending',
            method ENUM('sms', 'email', 'push_notification', 'non_musking') DEFAULT 'sms',
            delivery_report TEXT,
            sent_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            delivered_at TIMESTAMP NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_status (status),
            INDEX idx_method (method),
            INDEX idx_sent_at (sent_at),
            INDEX idx_sender (sender_id)
        )
    ");
    echo "✓ Messages log table created/verified\n";

    // Check if default non-masking settings exist
    $stmt = $pdo->query("SELECT COUNT(*) FROM settings WHERE setting_key LIKE 'non_musking_%'");
    $count = $stmt->fetchColumn();
    
    if ($count == 0) {
        // Insert default settings
        $default_settings = [
            ['non_musking_enabled', '0'],
            ['non_musking_method', 'sms'],
            ['non_musking_api_url', ''],
            ['non_musking_api_key', ''],
            ['non_musking_username', ''],
            ['non_musking_password', ''],
            ['non_musking_sender_id', 'SCHOOL'],
            ['non_musking_tpl_general_message', 'প্রিয় {name}, {message}. ধন্যবাদ।'],
            ['non_musking_tpl_admission_confirmation', 'প্রিয় {name}, আপনার ভর্তি আবেদন সফলভাবে জমা দেওয়া হয়েছে। আবেদন নম্বর: {application_no}। ধন্যবাদ।'],
            ['non_musking_rate_limit', '60'],
            ['non_musking_max_retries', '3']
        ];

        $stmt = $pdo->prepare("INSERT IGNORE INTO settings (setting_key, setting_value) VALUES (?, ?)");
        
        foreach ($default_settings as $setting) {
            $stmt->execute($setting);
        }
        
        echo "✓ Default non-masking settings inserted\n";
    } else {
        echo "ℹ️ Non-masking settings already exist\n";
    }

    echo "\n✅ Database setup completed successfully!\n";
    echo "\n👉 Next steps:\n";
    echo "   1. Go to Admin Panel → Non-Masking Settings\n";
    echo "   2. Enter your SMS provider credentials\n";
    echo "   3. Enable the non-masking SMS functionality\n";
    echo "   4. Test the configuration\n";

} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
}
?>