<?php
// Server Environment Detection & Configuration
// Automatically detects if running on localhost (XAMPP) or live server

// Check if running on localhost/development environment
$is_localhost = (
    $_SERVER['HTTP_HOST'] == 'localhost' || 
    $_SERVER['HTTP_HOST'] == '127.0.0.1' || 
    strpos($_SERVER['HTTP_HOST'], 'localhost:') === 0 ||
    strpos($_SERVER['HTTP_HOST'], '192.168.') === 0
);

if ($is_localhost) {
    // XAMPP Local Development Configuration
    $db_server = 'localhost';
    $db_username = 'root';
    $db_password = '';
    $db_name = 'shubank_db';
    
    // Show detailed errors for development
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
} else {
    // Live Server Configuration
    $db_server = 'localhost';
    $db_username = 'shubank_sk_king';
    $db_password = '@sk_king-%100';
    $db_name = 'shubank_db';
    
    // Hide errors for production security
    ini_set('display_errors', 0);
    ini_set('display_startup_errors', 0);
    error_reporting(0);
}

// Set timezone
date_default_timezone_set('Asia/Kolkata');

// Create connection with robust error handling
try {
    $link = mysqli_connect($db_server, $db_username, $db_password);
    
    if (!$link) {
        throw new mysqli_sql_exception("Connection failed: " . mysqli_connect_error());
    }
    
    // Check if database exists, if not create it (only on localhost)
    if ($is_localhost) {
        $db_check = mysqli_query($link, "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$db_name'");
        
        if (mysqli_num_rows($db_check) == 0) {
            // Create database if it doesn't exist
            $create_db = mysqli_query($link, "CREATE DATABASE IF NOT EXISTS `$db_name` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            if (!$create_db) {
                throw new mysqli_sql_exception("Error creating database: " . mysqli_error($link));
            }
            if ($is_localhost) {
                echo "<div style='background: #22c55e; color: white; padding: 10px; margin: 10px; border-radius: 5px;'>✅ Database '$db_name' created successfully!</div>";
            }
        }
    }
    
    // Select the database
    if (!mysqli_select_db($link, $db_name)) {
        throw new mysqli_sql_exception("Database selection failed: " . mysqli_error($link));
    }
    
    // Set charset to utf8mb4 for proper emoji and international character support
    mysqli_set_charset($link, "utf8mb4");
    
} catch (mysqli_sql_exception $e) {
    if ($is_localhost) {
        // Show detailed error on localhost for debugging
        die("<div style='background: #ef4444; color: white; padding: 15px; margin: 10px; border-radius: 5px;'>
                <h3>❌ Database Connection Error</h3>
                <p><strong>Error:</strong> " . $e->getMessage() . "</p>
                <h4>Quick Fix Instructions:</h4>
                <ol>
                    <li><strong>Start XAMPP:</strong> Open XAMPP Control Panel</li>
                    <li><strong>Start Apache:</strong> Click 'Start' next to Apache</li>
                    <li><strong>Start MySQL:</strong> Click 'Start' next to MySQL</li>
                    <li><strong>Refresh this page</strong> after both services are running</li>
                </ol>
                <p><em>If MySQL fails to start, try stopping any existing MySQL services first.</em></p>
             </div>");
    } else {
        // Generic error for live server security
        die("<div style='background: #ef4444; color: white; padding: 15px; margin: 10px; border-radius: 5px; text-align: center;'>
                <h3>🔧 Website Under Maintenance</h3>
                <p>We're experiencing technical difficulties. Please try again in a few minutes.</p>
                <p>If the problem persists, please contact support.</p>
             </div>");
    }
}

// Create required tables function
function createRequiredTables($connection, $is_localhost = false) {
    // Create results table
    $create_results = "CREATE TABLE IF NOT EXISTS `results` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `result_date` date NOT NULL,
        `game` varchar(50) NOT NULL,
        `result_number` varchar(10) NOT NULL,
        `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
        PRIMARY KEY (`id`),
        KEY `result_date` (`result_date`),
        KEY `game` (`game`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
    
    // Create users table
    $create_users = "CREATE TABLE IF NOT EXISTS `users` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `username` varchar(50) NOT NULL,
        `email` varchar(100) NOT NULL,
        `password` varchar(255) NOT NULL,
        `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
        PRIMARY KEY (`id`),
        UNIQUE KEY `username` (`username`),
        UNIQUE KEY `email` (`email`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
    
    // Create admin table
    $create_admin = "CREATE TABLE IF NOT EXISTS `admin` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `username` varchar(50) NOT NULL,
        `password` varchar(255) NOT NULL,
        `email` varchar(100) DEFAULT NULL,
        `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
        PRIMARY KEY (`id`),
        UNIQUE KEY `username` (`username`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
    
    // Create entries table
    $create_entries = "CREATE TABLE IF NOT EXISTS `entries` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `user_id` int(11) NOT NULL,
        `game` varchar(50) NOT NULL,
        `type` varchar(20) NOT NULL,
        `subtype` varchar(20) DEFAULT NULL,
        `number` varchar(10) NOT NULL,
        `amount` decimal(10,2) NOT NULL,
        `entry_time` timestamp NOT NULL DEFAULT current_timestamp(),
        PRIMARY KEY (`id`),
        KEY `user_id` (`user_id`),
        KEY `game` (`game`),
        KEY `entry_time` (`entry_time`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
    
    // Create blogs table
    $create_blogs = "CREATE TABLE IF NOT EXISTS `blogs` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `title` varchar(255) NOT NULL,
        `slug` varchar(255) NOT NULL,
        `content` longtext NOT NULL,
        `excerpt` text DEFAULT NULL,
        `featured_image` varchar(255) DEFAULT NULL,
        `category` varchar(100) DEFAULT 'general',
        `tags` text DEFAULT NULL,
        `status` enum('draft','published','archived') DEFAULT 'draft',
        `views` int(11) DEFAULT 0,
        `author_id` int(11) DEFAULT 1,
        `meta_title` varchar(255) DEFAULT NULL,
        `meta_description` text DEFAULT NULL,
        `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
        `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
        PRIMARY KEY (`id`),
        UNIQUE KEY `slug` (`slug`),
        KEY `status` (`status`),
        KEY `category` (`category`),
        KEY `created_at` (`created_at`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
    
    // Create blog categories table
    $create_blog_categories = "CREATE TABLE IF NOT EXISTS `blog_categories` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `name` varchar(100) NOT NULL,
        `slug` varchar(100) NOT NULL,
        `description` text DEFAULT NULL,
        `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
        PRIMARY KEY (`id`),
        UNIQUE KEY `slug` (`slug`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
    
    // Execute table creation
    $tables = [
        'results' => $create_results,
        'users' => $create_users,
        'admin' => $create_admin,
        'entries' => $create_entries,
        'blogs' => $create_blogs,
        'blog_categories' => $create_blog_categories
    ];
    
    foreach ($tables as $table_name => $sql) {
        if (!mysqli_query($connection, $sql)) {
            if ($is_localhost) {
                echo "<div style='background: #f59e0b; color: white; padding: 10px; margin: 5px; border-radius: 5px;'>⚠️ Warning: Could not create $table_name table - " . mysqli_error($connection) . "</div>";
            }
        }
    }
    
    // Create default admin user if not exists
    $admin_check = mysqli_query($connection, "SELECT COUNT(*) as count FROM admin");
    if ($admin_check && mysqli_fetch_assoc($admin_check)['count'] == 0) {
        $default_password = password_hash('admin123', PASSWORD_DEFAULT);
        $insert_admin = "INSERT INTO admin (username, password, email) VALUES ('admin', '$default_password', 'admin@shubank.co')";
        if (mysqli_query($connection, $insert_admin)) {
            if ($is_localhost) {
                echo "<div style='background: #3b82f6; color: white; padding: 10px; margin: 5px; border-radius: 5px;'>ℹ️ Default admin user created - Username: admin, Password: admin123</div>";
            }
        }
    }
    
    // Insert default blog categories (only show messages on localhost)
    $categories_check = mysqli_query($connection, "SELECT COUNT(*) as count FROM blog_categories");
    if ($categories_check && mysqli_fetch_assoc($categories_check)['count'] == 0) {
        $categories = [
            "('Tips & Strategies', 'tips', 'Winning strategies and professional tips for matka gaming')",
            "('Market Analysis', 'analysis', 'In-depth analysis of various matka markets and trends')",
            "('Platform Updates', 'platform', 'Latest updates and features about Shubank platform')",
            "('Educational', 'educational', 'Educational content for beginners and advanced players')",
            "('News & Updates', 'news', 'Latest news and updates from the matka world')"
        ];
        
        $insert_categories = "INSERT INTO blog_categories (name, slug, description) VALUES " . implode(', ', $categories);
        if (mysqli_query($connection, $insert_categories)) {
            if ($is_localhost) {
                echo "<div style='background: #3b82f6; color: white; padding: 10px; margin: 5px; border-radius: 5px;'>ℹ️ Default blog categories created</div>";
            }
        }
    }
    
    // Insert sample blogs if none exist (only on localhost to avoid duplicate content)
    if ($is_localhost) {
        $blogs_check = mysqli_query($connection, "SELECT COUNT(*) as count FROM blogs");
        if ($blogs_check && mysqli_fetch_assoc($blogs_check)['count'] == 0) {
            $sample_blogs = [
                [
                    'title' => 'Ultimate Guide to Satta Matka Winning Strategies',
                    'slug' => 'ultimate-guide-satta-matka-winning-strategies',
                    'content' => '<h2>Introduction to Satta Matka</h2><p>Satta Matka is one of India\'s most popular gambling games that originated in the 1960s. What started as a simple lottery has evolved into a sophisticated betting system with multiple markets and strategies.</p><h3>Understanding the Basics</h3><p>Before diving into winning strategies, it\'s crucial to understand the fundamentals:</p><ul><li><strong>Single:</strong> Betting on a single number (0-9)</li><li><strong>Jodi/Pair:</strong> Betting on a pair of numbers (00-99)</li><li><strong>Panna/Patti:</strong> Three-digit numbers with specific patterns</li></ul>',
                    'excerpt' => 'Learn the ultimate strategies and tips for winning at Satta Matka. Comprehensive guide covering basics, markets, and proven winning techniques.',
                    'category' => 'tips',
                    'tags' => 'satta matka,winning strategies,matka tips,kalyan matka',
                    'meta_title' => 'Ultimate Satta Matka Winning Strategies - Tips & Tricks',
                    'meta_description' => 'Complete guide to Satta Matka winning strategies, tips, and techniques. Learn from experts and improve your game.'
                ],
                [
                    'title' => 'How to Read Matka Charts Like a Pro',
                    'slug' => 'how-to-read-matka-charts-like-pro',
                    'content' => '<h2>Understanding Matka Charts</h2><p>Matka charts are the backbone of strategic satta matka playing. Learning to read and interpret these charts can significantly improve your chances of making informed bets.</p><h3>Types of Matka Charts</h3><h4>1. Kalyan Chart</h4><p>The most popular chart showing Kalyan matka results. Updated twice daily with open and close numbers.</p>',
                    'excerpt' => 'Master the art of reading matka charts with professional techniques and strategies. Learn pattern recognition and analysis methods.',
                    'category' => 'educational',
                    'tags' => 'matka charts,chart reading,kalyan chart,pattern analysis',
                    'meta_title' => 'How to Read Matka Charts Like a Pro - Complete Guide',
                    'meta_description' => 'Learn professional matka chart reading techniques, pattern recognition, and analysis strategies for better results.'
                ],
                [
                    'title' => 'Shubank vs Other Platforms: Why We\'re Different',
                    'slug' => 'shubank-vs-other-platforms-why-different',
                    'content' => '<h2>Why Choose Shubank?</h2><p>In the crowded world of online matka platforms, Shubank stands out as India\'s most trusted and reliable choice. Here\'s what makes us different.</p><h3>Security First Approach</h3><h4>Advanced Encryption</h4><p>We use bank-grade SSL encryption to protect all user data and transactions.</p>',
                    'excerpt' => 'Discover what makes Shubank different from other matka platforms. Security, transparency, fast payments, and excellent user experience.',
                    'category' => 'platform',
                    'tags' => 'shubank,online matka,secure platform,fast payments',
                    'meta_title' => 'Shubank vs Others - Why We\'re India\'s Best Matka Platform',
                    'meta_description' => 'Compare Shubank with other matka platforms. Learn about our security, transparency, fast payments, and user-friendly features.'
                ]
            ];
            
            foreach ($sample_blogs as $blog) {
                $insert_blog = "INSERT INTO blogs (title, slug, content, excerpt, category, tags, status, views, meta_title, meta_description) VALUES ('" . 
                    mysqli_real_escape_string($connection, $blog['title']) . "', '" .
                    mysqli_real_escape_string($connection, $blog['slug']) . "', '" .
                    mysqli_real_escape_string($connection, $blog['content']) . "', '" .
                    mysqli_real_escape_string($connection, $blog['excerpt']) . "', '" .
                    mysqli_real_escape_string($connection, $blog['category']) . "', '" .
                    mysqli_real_escape_string($connection, $blog['tags']) . "', 'published', 0, '" .
                    mysqli_real_escape_string($connection, $blog['meta_title']) . "', '" .
                    mysqli_real_escape_string($connection, $blog['meta_description']) . "')";
                
                if (mysqli_query($connection, $insert_blog)) {
                    echo "<div style='background: #22c55e; color: white; padding: 5px; margin: 2px; border-radius: 3px; font-size: 12px;'>✅ Sample blog created: " . $blog['title'] . "</div>";
                }
            }
        }
    }
}

// Auto-create tables with environment awareness
createRequiredTables($link, $is_localhost);
?>
