<?php
$settings_file = 'theme_settings.json';

// 1. Handle Reset
if (isset($_GET['reset'])) {
    if (file_exists($settings_file)) unlink($settings_file);
    header("Location: " . $_SERVER['PHP_SELF']); exit;
}

// 2. Handle Save
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_settings'])) {
    $data = json_encode([
        'blur'   => $_POST['blur'], 
        'hue'    => $_POST['hue'], 
        'region' => $_POST['region']
    ]);
    file_put_contents($settings_file, $data);
}

// 3. Load Settings (or use Defaults)
$config = file_exists($settings_file) ? json_decode(file_get_contents($settings_file), true) : 
          ['blur' => 12, 'hue' => 120, 'region' => 'global'];

// --- DYNAMIC REGION & BRAND NAME LOADING ---
$db = new PDO('sqlite:' . __DIR__ . '/app_feed.db');
$stmt = $db->query("SELECT setting_key, setting_value FROM app_feed_settings WHERE setting_key LIKE 'brand_name_%'");
$brand_map = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

// Mapping for display names
$countryNames = [
    'ng' => 'Nigeria', 'us' => 'United States', 'gb' => 'United Kingdom', 
    'ca' => 'Canada', 'fr' => 'France', 'de' => 'Germany', 'in' => 'India',
    'en' => 'English (Global)'
];

$available_regions = ['global' => 'Global (Default)'];
foreach (glob("lang/*.php") as $filename) {
    $code = basename($filename, '.php');
    $brand_name = isset($brand_map['brand_name_' . $code]) ? ' - ' . str_replace('Apex ', '', $brand_map['brand_name_' . $code]) : '';
    $available_regions[$code] = strtoupper($code) . $brand_name;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Master Digital Adjuster</title>
    <style>
        /* Your original styles preserved exactly */
        :root { 
            --blur: <?=$config['blur']?>px; 
            --hue: <?=$config['hue']?>; 
        }
        body { background-color: #0c0f15 !important; color: white; padding: 40px; font-family: 'Segoe UI', sans-serif; display: flex; flex-direction: column; align-items: center; }
        .controls { width: 100%; max-width: 800px; background: rgba(255, 255, 255, 0.05); padding: 25px; border-radius: 12px; border: 1px solid rgba(255, 255, 255, 0.1); margin-bottom: 20px; }
        label { display: block; margin: 15px 0 5px; font-size: 13px; color: #ccc; }
        
        .container { 
            width: 100%; max-width: 440px; padding: 32px; border-radius: 24px;
            /* Using the live variables for background and blur */
            background: linear-gradient(145deg, hsla(var(--hue), 80%, 30%, 0.7), #0f1624);
            backdrop-filter: blur(var(--blur)); border: 1px solid rgba(255,255,255,0.1); 
            text-align: center; color: white; font-weight: bold;
        }

        /* Preview Grid styles added to maintain consistency */
        .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; }
        #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; }
        #preview-modal iframe { width: 100%; height: 100%; border: none; background: white; border-radius: 8px; }
    </style>
</head>
<body>

<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="controls">
    <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;">⚙️ Master Control Center</h1>
            <div style="display: flex; align-items: center; white-space: nowrap;">
                <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="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>

    <form method="POST">
        <label>Select Professional Theme</label>
        <div style="display:grid; grid-template-columns: repeat(5, 1fr); gap: 5px; margin-bottom: 15px;">
            <?php 
            $presets = [['n'=>'Midnight','h'=>240,'b'=>10],['n'=>'Emerald','h'=>150,'b'=>12],['n'=>'Sunset','h'=>20,'b'=>8],['n'=>'Ocean','h'=>200,'b'=>15],['n'=>'Ruby','h'=>350,'b'=>5],['n'=>'Gold','h'=>45,'b'=>12],['n'=>'Forest','h'=>100,'b'=>10],['n'=>'Violet','h'=>280,'b'=>12],['n'=>'Sky','h'=>190,'b'=>20],['n'=>'Cyber','h'=>310,'b'=>15]];
            foreach($presets as $p): ?>
                <button type="button" onclick="applyTheme(<?=$p['h']?>, <?=$p['b']?>)" style="padding:8px; border:none; background:#333; color:#fff; border-radius:4px; cursor:pointer; font-size:10px;"><?=$p['n']?></button>
            <?php endforeach; ?>
        </div>

        <label>Container Blur (Live): <span id="val-blur"><?=$config['blur']?></span>px</label>
        <input type="range" id="blur-slider" name="blur" min="0" max="50" value="<?=$config['blur']?>" 
               oninput="updateLiveView()">
        
        <label>Theme Color Hue (Live): <span id="val-hue"><?=$config['hue']?></span>°</label>
        <input type="range" id="hue-slider" name="hue" min="0" max="360" value="<?=$config['hue']?>" 
               oninput="updateLiveView()">
        
        <label>Target Region</label>
        <select name="region" style="width:100%; padding:10px; background:#1a1a1a; color:white; border: 1px solid #333; border-radius:8px;">
            <?php foreach ($available_regions as $code => $label): ?>
                <option value="<?=$code?>" <?=($config['region'] == $code ? 'selected' : '')?>><?=$label?></option>
            <?php endforeach; ?>
        </select>
        
        <button type="submit" name="save_settings" style="margin-top:20px; width:100%; padding:15px; background:#3b82f6; border:none; color:white; cursor:pointer; border-radius:8px;">
            Save & Apply Globally
        </button>
        
        <a href="?reset=1" style="display:block; text-align:center; margin-top:15px; color:#ef4444; text-decoration:none;">Reset to Normal</a>
    </form>
</div>

<div class="controls">
    <h3>Regional Language Previews</h3>
    <div class="preview-grid">
        <?php
        foreach (glob("lang/*.php") as $file): 
            $code = basename($file, '.php');
            $fullName = $countryNames[$code] ?? 'Region: ' . strtoupper($code);
        ?>
            <div class="preview-card">
                <div class="country-label"><?php echo $fullName; ?></div>
                <div class="code-label">Code: <?php echo strtoupper($code); ?></div>
                <button type="button" onclick="loadPreview('index.php?preview_region=<?=$code?>')" 
                        style="width:100%; padding:10px; margin-bottom:5px; background:#2563eb; color:white; border:none; border-radius:5px; cursor:pointer;">Preview Index</button>
                <button type="button" onclick="loadPreview('cdashboard.php?preview_region=<?=$code?>')" 
                        style="width:100%; padding:10px; background:#7c3aed; color:white; border:none; border-radius:5px; cursor:pointer;">Preview Dash</button>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<script>
    function updateLiveView() {
        const h = document.getElementById('hue-slider').value;
        const b = document.getElementById('blur-slider').value;
        
        // Update display text
        document.getElementById('val-hue').innerText = h;
        document.getElementById('val-blur').innerText = b;
    }

    function applyTheme(h, b) {
        document.getElementById('hue-slider').value = h;
        document.getElementById('blur-slider').value = b;
        updateLiveView();
    }

    function loadPreview(url) {
        const frame = document.getElementById('preview-frame');
        const modal = document.getElementById('preview-modal');
        const h = document.getElementById('hue-slider').value;
        const b = document.getElementById('blur-slider').value;
        
        frame.src = url + (url.includes('?') ? '&' : '?') + 'hue=' + h + '&blur=' + b;
        
        frame.onload = function() {
            const doc = frame.contentDocument || frame.contentWindow.document;
            doc.documentElement.style.setProperty('--hue', h);
            doc.documentElement.style.setProperty('--blur', b + 'px');
        };
        
        modal.style.display = 'block';
    }
</script>

</body>
</html>