<?php
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) exit('Access Denied');

$db = new PDO('sqlite:' . __DIR__ . '/app_feed.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$message = '';

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] === 'save_brand') {
            $code = strtolower(trim($_POST['country_code']));
            $brand = 'Apex ' . trim($_POST['brand_name']);
            $stmt = $db->prepare("INSERT OR REPLACE INTO app_feed_settings (setting_key, setting_value) VALUES (?, ?)");
            $stmt->execute(['brand_name_' . $code, $brand]);
            $message = "Brand for " . strtoupper($code) . " saved as: " . $brand;
        } elseif ($_POST['action'] === 'delete_brand') {
            $code = $_POST['country_code'];
            $stmt = $db->prepare("DELETE FROM app_feed_settings WHERE setting_key = ?");
            $stmt->execute(['brand_name_' . $code]);
            $message = "Brand entry deleted.";
        }
    }
}

// Fetch existing brands for both the table and the dropdown
$stmt = $db->query("SELECT setting_key, setting_value FROM app_feed_settings WHERE setting_key LIKE 'brand_name_%'");
$savedBrands = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
?>
<style>
    html, body { background-color: #0c0f15 !important; margin: 0; padding: 0; min-height: 100vh; }
    .brand-container { font-family: 'Segoe UI', sans-serif; color: #fff; max-width: 800px; margin: 20px auto; padding: 20px; background: #0c0f15; border-radius: 12px; }
    .card { background: rgba(255, 255, 255, 0.05); padding: 20px; border-radius: 12px; border: 1px solid rgba(255, 255, 255, 0.1); margin-bottom: 20px; }
    .form-group { margin-bottom: 15px; }
    input, select { width: 100%; padding: 10px; background: #1a1a1a; border: 1px solid #333; color: white; border-radius: 6px; box-sizing: border-box; }
    .btn { padding: 10px 20px; border: none; border-radius: 6px; cursor: pointer; background: #3b82f6; color: white; width: 100%; }
    .btn-danger { background: #ef4444; }
    table { width: 100%; border-collapse: collapse; margin-top: 10px; }
    th, td { padding: 12px; text-align: left; border-bottom: 1px solid #333; color: #ccc; }
</style>

<div class="brand-container">
    <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="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="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>

    <?php if ($message) echo "<div style='background:#065f46; padding:10px; border-radius:6px; margin-bottom:15px;'>$message</div>"; ?>
    
    <div class="card">
        <h3>Manage Regional Brand Names</h3>
        <form method="POST">
            <input type="hidden" name="action" value="save_brand">
            <div class="form-group">
                <label>1. Select/Type Region Code (e.g., ng, ke, us)</label>
                <input type="text" name="country_code" maxlength="3" placeholder="ng" required>
            </div>
            <div class="form-group">
                <label>2. Brand Suffix (e.g., "Nigeria" for "Apex Nigeria")</label>
                <input type="text" name="brand_name" placeholder="Enter Suffix" required>
            </div>
            <button type="submit" class="btn">Save / Update Brand</button>
        </form>
    </div>

    <div class="card">
        <h3>Region Dropdown List</h3>
        <div class="form-group">
            <label>Current Available Regions:</label>
            <select>
                <?php if (empty($savedBrands)): ?>
                    <option>No regions set yet</option>
                <?php else: ?>
                    <?php foreach($savedBrands as $key => $value): 
                        $code = strtoupper(str_replace('brand_name_', '', $key));
                    ?>
                        <option><?php echo $code . " - " . htmlspecialchars($value); ?></option>
                    <?php endforeach; ?>
                <?php endif; ?>
            </select>
        </div>
    </div>

    <div class="card">
        <h3>Currently Set Brand Names (Management Table)</h3>
        <table>
            <tr><th>Code</th><th>Brand Name</th><th>Action</th></tr>
            <?php foreach($savedBrands as $key => $value): 
                $code = str_replace('brand_name_', '', $key);
            ?>
            <tr>
                <td><?php echo strtoupper($code); ?></td>
                <td><?php echo htmlspecialchars($value); ?></td>
                <td>
                    <form method="POST" onsubmit="return confirm('Delete this brand entry?');">
                        <input type="hidden" name="action" value="delete_brand">
                        <input type="hidden" name="country_code" value="<?php echo $code; ?>">
                        <button type="submit" class="btn btn-danger" style="padding: 5px 10px; font-size: 12px;">Delete</button>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
        </table>
    </div>
</div>