<style>
    /* Dashboard Modern Styling */
    .region-manager-container { font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #fff; max-width: 1200px; margin: 0 auto; padding: 20px; background-color: #0c0f15 !important; min-height: 100vh; }
    .card { background: rgba(255, 255, 255, 0.05); padding: 25px; border-radius: 12px; margin-bottom: 20px; border: 1px solid rgba(255, 255, 255, 0.1); box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2); }
    .card h3 { margin: 0 0 20px 0; color: #fff; font-size: 1.25rem; border-bottom: 1px solid #333; padding-bottom: 15px; }
    .form-group { margin-bottom: 20px; }
    .form-group label { display: block; margin-bottom: 8px; color: #aaa; font-size: 0.9em; }
    .form-group input[type="text"], .form-group input[type="file"], .form-group select { width: 100%; padding: 10px; background: #1a1a1a; border: 1px solid #333; color: white; border-radius: 6px; box-sizing: border-box; }
    .form-group input[type="color"] { width: 100%; padding: 5px; height: 45px; border-radius: 6px; border: 1px solid #333; cursor: pointer; background: #1a1a1a; }
    .btn { padding: 10px 20px; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; width: 100%; transition: background 0.2s; }
    .btn-primary { background: #3b82f6; color: white; }
    .btn-danger { background: #ef4444; color: white; }
    .btn-warning { background: #f59e0b; color: white; margin-right: 5px; }
    .preview-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 20px; margin-top: 20px; }
    .preview-card { padding: 20px; border-radius: 12px; background: #1a1a1a; border: 1px solid #333; text-align: center; }
    .country-label { font-size: 1.1em; font-weight: bold; margin-bottom: 5px; color: #3b82f6; }
    .code-label { font-size: 0.8em; color: #888; margin-bottom: 15px; text-transform: uppercase; }
    .admin-guide { font-size: 0.75rem; color: #666; margin-bottom: 10px; padding: 5px; border: 1px dashed #333; border-radius: 4px; }
    .success-msg { background: #065f46; padding: 15px; border-radius: 6px; margin-bottom: 20px; border: 1px solid #10b981; color: #fff; }
    .lang-action-group { display: flex; gap: 5px; }
    
    /* Modal Styling */
    #preview-modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.9); z-index: 9999; padding: 50px; box-sizing: border-box; }
    #preview-modal .close-btn { position: absolute; top: 20px; right: 30px; color: white; font-size: 40px; cursor: pointer; font-weight: bold; }
    #preview-modal iframe { width: 100%; height: 100%; border: none; background: white; border-radius: 8px; overflow: auto; }
</style>

<div id="preview-modal">
    <span class="close-btn" onclick="document.getElementById('preview-modal').style.display='none'">&times;</span>
    <iframe id="preview-frame" src=""></iframe>
</div>

<div class="region-manager-container">
    <?php
    if (session_status() === PHP_SESSION_NONE) session_start();
    if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) exit('Access Denied');

    $message = '';
    $countryNames = [
        'ng' => 'Nigeria', 'us' => 'United States', 'gb' => 'United Kingdom', 
        'ca' => 'Canada', 'fr' => 'France', 'de' => 'Germany', 'in' => 'India'
    ];

    try {
        $db = new PDO('sqlite:' . __DIR__ . '/app_feed.db');
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $db->exec("DELETE FROM app_feed_settings WHERE setting_key LIKE 'bg_%' AND (length(setting_key) - length(replace(setting_key, '_', ''))) < 2");
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
            if ($_POST['action'] === 'create_lang') {
                $code = strtolower(trim($_POST['lang_code']));
                $file = "lang/{$code}.php";
                if (!file_exists($file)) {
                    $keys = [
                        'login_title' => 'Login', 'reg_title' => 'Register Account', 
                        'phone_label' => 'Enter Phone Number', 'login_btn' => 'Login Now', 
                        'reg_btn' => 'Complete Registration', 'wait_approval' => 'Wait for Approval', 
                        'logout' => 'Logout',
                        'tier_label' => 'Bronze Tier',
                        'welcome_msg' => 'Welcome, joy',
                        'balance_label' => 'Balance: $0.00',
                        'bank_details_title' => 'Bank Details',
                        'save_bank_btn' => 'Save Bank Details',
                        'clear_bank_btn' => 'Clear Bank Details',
                        'min_withdrawal_label' => 'Min Withdrawal Limit: $0.00',
                        'request_withdrawal_btn' => 'Request Withdrawal',
                        'ai_manager_pending' => "Hello! I'm your Portfolio Manager. I'm currently verifying your documents. Please sit tight—I'll have you active shortly.",
                        'ai_manager_active' => "Welcome back! I've been monitoring your growth. Today is a great day to increase your savings stake to hit that next tier.",
                        'ai_manager_suspended' => "I have some difficult news. Your account has been suspended due to a compliance flag. Please contact our support team immediately to resolve this.",
                        'ai_manager_default' => "Hello. I am here to guide your financial journey. How can I assist you today?"
                    ];
                    $translated = [];
                    foreach ($keys as $key => $text) {
                        $url = "https://api.mymemory.translated.net/get?q=" . urlencode($text) . "&langpair=en|$code";
                        $response = json_decode(@file_get_contents($url), true);
                        $translated[$key] = $response['responseData']['translatedText'] ?? $text;
                    }
                    $content = "<?php\n\$lang = " . var_export($translated, true) . ";";
                    file_put_contents($file, $content);
                    $stmt = $db->prepare("INSERT OR IGNORE INTO app_feed_settings (setting_key, setting_value) VALUES (?, ?)");
                    $stmt->execute(['lang_enabled_' . $code, '1']);
                    $message = "Language '{$code}' created successfully!";
                }
            } elseif ($_POST['action'] === 'delete_lang') {
                $code = $_POST['lang_code'];
                if (file_exists("lang/{$code}.php") && $code !== 'en') {
                    unlink("lang/{$code}.php");
                    $stmt = $db->prepare("DELETE FROM app_feed_settings WHERE setting_key = ?");
                    $stmt->execute(['lang_enabled_' . $code]);
                    $message = "Language '{$code}' deleted.";
                }
            }
        }
        
        $rows = $db->query("SELECT setting_key, setting_value FROM app_feed_settings")->fetchAll(PDO::FETCH_ASSOC);
        $currentSettings = [];
        foreach ($rows as $row) {
            $currentSettings[$row['setting_key']] = $row['setting_value'];
        }
    } catch (Exception $e) {
        die("<div class='card'><h3>Database Error</h3><p>" . $e->getMessage() . "</p></div>");
    }
    ?>

    <?php if ($message): ?>
        <div class="success-msg"><?php echo $message; ?></div>
        <script>setTimeout(() => { window.location.href = window.location.pathname; }, 2000);</script>
    <?php endif; ?>
<div class="admin-wrapper" style="margin-bottom: 20px;">
    <div style="display: flex; justify-content: space-between; align-items: center;">
    <h1 style="font-size: 1.5rem; color: #fff;">⚙️ Platform Control Dashboard</h1>
    <div style="display: flex; align-items: center; white-space: nowrap;">
        <a href="master_adjuster.php" style="background: #fbbf24; color: black; padding: 8px 15px; text-decoration: none; font-size: 14px; font-weight: 600; border-radius: 5px; margin-right: 15px;">Master Adjuster</a>
        
        <a href="manage_branding.php" style="background: #8b5cf6; color: white; padding: 8px 15px; text-decoration: none; font-size: 14px; font-weight: 600; border-radius: 5px; margin-right: 15px;">Branding</a>
        <a href="manage_region.php" style="background: #10b981; color: white; padding: 8px 15px; text-decoration: none; font-size: 14px; font-weight: 600; border-radius: 5px; margin-right: 15px;">Manage Regions</a>
        <a href="code.html" style="background: #3b82f6; color: white; padding: 8px 15px; text-decoration: none; font-size: 14px; font-weight: 600; border-radius: 5px; margin-right: 15px;">Country Code</a>
        <a href="dashboard.php?view=admin" style="color: #60a5fa; text-decoration: none; font-size: 14px; font-weight: 600; margin-right: 15px;">Login</a>
        <a href="index.php" style="color: #60a5fa; text-decoration: none; font-size: 14px; font-weight: 600; margin-right: 15px;">← Back to App</a>
        <a href="logout.php" style="background: #f87171; color: white; padding: 8px 15px; text-decoration: none; font-size: 14px; font-weight: 600; border-radius: 5px;">Logout</a>
    </div>
</div>
    <div class="card">
        <h3>Language Factory</h3>
        <form method="POST">
            <input type="hidden" name="action" value="create_lang">
            <div class="form-group">
                <label>Enter 2-Letter Language Code (e.g., es, it, pt)</label>
                <input type="text" name="lang_code" maxlength="2" placeholder="es" required>
            </div>
            <button type="submit" class="btn btn-primary">Generate & Register Language</button>
        </form>
    </div>

    <div class="card">
        <h3>Manage Existing Languages</h3>
        <?php 
        $langFiles = glob("lang/*.php");
        foreach ($langFiles as $file): 
            $code = basename($file, '.php');
        ?>
            <div style="display: flex; justify-content: space-between; align-items: center; background: #1a1a1a; padding: 10px; margin-bottom: 5px; border-radius: 6px;">
                <span>Code: <strong><?php echo strtoupper($code); ?></strong></span>
                <div class="lang-action-group">
                    <a href="edit_lang.php?code=<?php echo $code; ?>" class="btn btn-warning" style="text-decoration:none; text-align:center; padding: 5px 15px;">Edit</a>
                    <form method="POST" onsubmit="return confirm('Delete this language?')">
                        <input type="hidden" name="action" value="delete_lang">
                        <input type="hidden" name="lang_code" value="<?php echo $code; ?>">
                        <button type="submit" class="btn btn-danger" style="padding: 5px 15px;" <?php echo ($code === 'en') ? 'disabled' : ''; ?>>Delete</button>
                    </form>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <div class="card">
        <h3>Upload Regional Background</h3>
        <div class="admin-guide">Examples: ng (Nigeria), us (United States), gb (UK), ca (Canada), fr (France), de (Germany), in (India)</div>
        <form id="uploadForm">
            <input type="hidden" name="action" value="admin_upload_bg">
            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">
            <div class="form-group">
                <label>Target Page</label>
                <select name="page_type">
                    <option value="index">Index Page (Login/Reg)</option>
                    <option value="dash">Dashboard Page</option>
                </select>
            </div>
            <div class="form-group">
                <label>Country Code</label>
                <input type="text" name="country_code" required>
            </div>
            <div class="form-group">
                <label>Background Image</label>
                <input type="file" name="bg_image" required>
            </div>
            <button type="submit" class="btn btn-primary" id="uploadBtn">Upload & Apply</button>
        </form>
    </div>

    <div class="card">
        <h3>Regional Previews</h3>
        <div class="preview-grid">
       <?php
            $found = false;
            foreach ($currentSettings as $key => $value) {
                if (is_string($key) && strpos($key, 'bg_') === 0 && strpos($key, 'bg_color_') === false) {
                    $parts = explode('_', $key);
                    if (is_array($parts) && count($parts) === 3) {
                        $found = true;
                        $pageType = $parts[1]; 
                        $code = $parts[2];
                        $fullName = $countryNames[$code] ?? 'Unknown Region';
                        
                        echo '<div class="preview-card">';
                        echo '<div class="country-label">' . $fullName . ' (' . strtoupper((string)$pageType) . ')</div>';
                        echo '<div class="code-label">Code: ' . strtoupper((string)$code) . '</div>';
                        
                        echo '<div style="min-height: 150px; background: url(\'' . (is_string($value) ? $value : '') . '?' . time() . '\'); padding: 20px; margin-bottom: 15px; border: 1px solid #333; background-size: cover; background-position: center; border-radius: 8px;"></div>';
                        
                       // Only show the Index button if this is an Index setting card
                        if ($pageType === 'index') {
                            echo '<button type="button" onclick="showPreview(\'index.php?preview_region=' . $code . '\')" class="btn btn-primary" style="margin-bottom: 10px; background: #2563eb;">Preview Index</button>';
                        } 
                        // Only show the Dashboard button if this is a Dashboard setting card
                        elseif ($pageType === 'dash') {
                            echo '<button type="button" onclick="showPreview(\'cdashboard.php?preview_region=' . $code . '\')" class="btn btn-primary" style="margin-bottom: 10px; background: #7c3aed;">Preview Dashboard</button>';
                        }
                       
                       
                       
                        echo '<form class="resetForm" data-code="' . $code . '">';
                        echo '<input type="hidden" name="action" value="admin_reset_bg">';
                        echo '<input type="hidden" name="csrf_token" value="' . ($_SESSION['csrf_token'] ?? '') . '">';
                        echo '<input type="hidden" name="country_code" value="' . $code . '">';
                        echo '<input type="hidden" name="page_type" value="' . $pageType . '">';
                        echo '<button type="submit" class="btn btn-danger" style="padding: 8px;">Reset</button>';
                        echo '</form>';
                        echo '</div>';
                    }
                }
            }
            if (!$found) {
                echo '<div style="grid-column: 1/-1; padding: 20px; border: 1px dashed #444; color: #888;">';
                echo '<p>No valid regional configurations found.</p>';
                echo '</div>';
            }
            ?>
        </div>
    </div>
</div>

<script>
    function showPreview(url) {
        document.getElementById('preview-frame').src = url;
        document.getElementById('preview-modal').style.display = 'block';
    }

    document.getElementById('uploadForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const btn = document.getElementById('uploadBtn');
        btn.innerText = 'Uploading...';
        btn.disabled = true;

        fetch('admin.php', {
            method: 'POST',
            body: new FormData(this)
        })
        .then(() => {
            alert('Successful: picture uploaded.');
            location.reload();
        })
        .catch(() => {
            alert('Upload failed');
            btn.innerText = 'Upload & Apply';
            btn.disabled = false;
        });
    });

    document.querySelectorAll('.resetForm').forEach(form => {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            if(!confirm('Reset background for this region?')) return;
            
            fetch('admin.php', {
                method: 'POST',
                body: new FormData(this)
            })
            .then(() => {
                location.reload();
            })
            .catch(() => alert('Reset failed'));
        });
    });
</script>