<?php
session_start();

// Permission Enforcement & Helpers
require_once __DIR__ . '/helpers/subadmin_page_guard.php';
require_once __DIR__ . '/helpers/get_back_button.php';

// Only full admins can manage subadmins (not subadmins themselves)
$pageGuard = new SubAdminPageGuard('manage_subadmins');
if (!$pageGuard->isAdmin()) {
    header('Location: admin_login.php');
    exit;
}

require_once __DIR__ . '/helpers/database_helper.php';
// Attempt DB connection if available (db_config.php sets $conn)
if (file_exists(__DIR__ . '/db_config.php')) require_once __DIR__ . '/db_config.php';

$subadmins = DatabaseHelper::loadJson('subadmins.json', []);
$flash = '';

// Load users from DB for selection (if DB available)
$users = [];
if (isset($conn) && $conn) {
    $res = $conn->query('SELECT id, username, email FROM users ORDER BY id DESC');
    if ($res) {
        while ($r = $res->fetch_assoc()) $users[] = $r;
    }
}

// Migrate old username-keyed entries to numeric user_id keys when possible
if (is_array($subadmins)) {
    $migrated = false;
    foreach ($subadmins as $key => $val) {
        if (!is_numeric((string)$key) && isset($conn) && $conn) {
            // try to find user by username or email
            $k = $conn->real_escape_string($key);
            $q = "SELECT id FROM users WHERE username = '".$k."' OR email = '".$k."' LIMIT 1";
            $r = $conn->query($q);
            if ($r && $r->num_rows > 0) {
                $row = $r->fetch_assoc();
                $newKey = (string)$row['id'];
                if (!isset($subadmins[$newKey])) {
                    $subadmins[$newKey] = $val;
                }
                unset($subadmins[$key]);
                $migrated = true;
            }
        }
    }
    if ($migrated) DatabaseHelper::saveJson('subadmins.json', $subadmins);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // Build permissions map based on available dashboard features
    $available = [
        'manage_site_title' => 'Site Title',
        'manage_logo' => 'Logo',
        'manage_slider_images' => 'Slider Images',
        'manage_colors' => 'Header/Footer Colors',
        'manage_categories' => 'Categories',
        'manage_pages' => 'Pages',
        'manage_social' => 'Social Media',
        'manage_blogs' => 'Blogs',
        'manage_products' => 'Products',
        'manage_users' => 'Users',
        'manage_subadmins' => 'Sub-admins',
        'manage_orders' => 'Orders',
        'manage_news' => 'News/Banners',
        'manage_marquee' => 'Marquee Text',
        'manage_footer_marquee' => 'Footer Marquee',
        'manage_featured_categories' => 'Featured Categories',
        'manage_carousel' => 'Carousel Categories',
        'manage_slider_settings' => 'Slider Settings',
        'manage_awards' => 'Awards',
        'manage_latest_products' => 'Latest Products',
        'manage_video' => 'Video Section',
        'manage_footer_settings' => 'Footer Settings',
        'manage_seo' => 'SEO Manager',
        'manage_homepage' => 'Homepage Features',
        'manage_settings' => 'General Settings'
    ];

    if ($action === 'add_subadmin' || $action === 'edit_subadmin') {
        // Check permission for create/edit
        if ($action === 'add_subadmin') {
            EnforceManageSubadmins::guardAction('create');
        } else {
            EnforceManageSubadmins::guardAction('edit');
        }
        $user_id = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
        $original_user_id = isset($_POST['original_user_id']) ? (int)$_POST['original_user_id'] : 0;
        $display_name = trim($_POST['display_name'] ?? '');
        
        // Build permissions with hierarchy levels
        $perms = [];
        foreach ($available as $pkey => $plabel) {
            $level = $_POST[$pkey . '_level'] ?? 'none';
            // Valid levels: none, viewer, editor, administrator
            if (in_array($level, ['viewer', 'editor', 'administrator'])) {
                $perms[$pkey] = $level;
            } else {
                $perms[$pkey] = 'none';
            }
        }

        if ($user_id <= 0) {
            $flash = 'Please select a user to make sub-admin.';
        } else {
            // For edit mode, use the original_user_id as the key
            $finalUserId = ($action === 'edit_subadmin' && $original_user_id > 0) ? $original_user_id : $user_id;
            
            $subadmins = is_array($subadmins) ? $subadmins : [];
            $now = date('c');
            $subadmins[(string)$finalUserId] = [
                'user_id' => $finalUserId,
                'display_name' => $display_name,
                'permissions' => $perms,
                'updated_at' => $now,
            ];
            DatabaseHelper::saveJson('subadmins.json', $subadmins);
            $flash = ($action === 'add_subadmin') ? 'Sub-admin added successfully.' : 'Sub-admin updated successfully.';
        }
    }

    if ($action === 'delete_subadmin') {
        // Check permission for delete
        EnforceManageSubadmins::guardAction('delete');
        
        $user_id = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
        $key = (string)$user_id;
        if ($user_id > 0 && isset($subadmins[$key])) {
            unset($subadmins[$key]);
            DatabaseHelper::saveJson('subadmins.json', $subadmins);
            $flash = 'Sub-admin removed.';
        }
    }

    // reload
    $subadmins = DatabaseHelper::loadJson('subadmins.json', []);
}

?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Manage Sub-admins</title>
<link rel="stylesheet" href="styles.css">
<style>
.container { max-width:1200px; margin:24px auto; padding:16px; }
.card { background:#fff; padding:16px; border-radius:8px; box-shadow:0 4px 12px rgba(0,0,0,0.06); }
.form-row { display:flex; gap:8px; align-items:center; margin-bottom:8px; }
.small { font-size:13px; color:#666; }
.actions { display:flex; gap:8px; }
.perm-table { width:100%; border-collapse:collapse; margin-top:12px; }
.perm-table thead { background:#f5f5f5; }
.perm-table th, .perm-table td { padding:10px; border:1px solid #ddd; text-align:left; }
.perm-table th { font-weight:600; background:#f0f0f0; }
.perm-table tbody tr:nth-child(odd) { background:#fafafa; }
.perm-table tbody tr:hover { background:#f0f8ff; }
.level-select { padding:6px; border:1px solid #ddd; border-radius:4px; width:100%; cursor:pointer; }
.level-viewer { color:#2196F3; }
.level-editor { color:#FF9800; }
.level-administrator { color:#4CAF50; }
.level-none { color:#999; }
input[type="text"], select { padding:8px; border:1px solid #ddd; border-radius:4px; }
</style>
</head>
<body>
<div class="container">
    <?php echo getBackButton('← Back'); ?>
    <h2>Manage Sub-admins</h2>
    <?php if (!empty($flash)): ?>
        <div class="card" style="background:#eef8ee; color:#085;"><?php echo htmlspecialchars($flash); ?></div>
    <?php endif; ?>

    <div class="card" style="margin-top:12px;">
        <h3><span id="formTitle">Add New Sub-admin</span></h3>
        <form method="post" id="subadminForm">
            <div class="form-row">
                <div style="flex:1;">
                    <label>Select user</label>
                    <select name="user_id" id="user_id_select" required>
                        <option value="">-- Select user --</option>
                        <?php foreach ($users as $u): ?>
                            <option value="<?php echo (int)$u['id']; ?>"><?php echo htmlspecialchars($u['username'] . ' (' . $u['email'] . ')'); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div style="flex:1;">
                    <label>Display Name</label>
                    <input type="text" name="display_name" id="display_name_input" placeholder="Display name (optional)">
                </div>
            </div>

            <div style="margin-top:16px;">
                <label style="display:block; margin-bottom:12px; font-weight:600;">Permission Hierarchy for Features</label>
                <p class="small" style="margin-bottom:12px; padding:8px; background:#e3f2fd; border-radius:4px;">
                    <strong>Levels:</strong> 
                    <span class="level-none">None</span> = No access | 
                    <span class="level-viewer">Viewer</span> = View only | 
                    <span class="level-editor">Editor</span> = View, Add, Edit (no delete) | 
                    <span class="level-administrator">Administrator</span> = Full access (View, Add, Edit, Delete)
                </p>
                
                <table class="perm-table">
                    <thead>
                        <tr>
                            <th>Feature</th>
                            <th style="width:150px;">Permission Level</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $permLabels = [
                            'manage_site_title' => 'Site Title',
                            'manage_logo' => 'Logo',
                            'manage_slider_images' => 'Slider Images',
                            'manage_colors' => 'Header/Footer Colors',
                            'manage_categories' => 'Categories',
                            'manage_pages' => 'Pages',
                            'manage_social' => 'Social Media',
                            'manage_blogs' => 'Blogs',
                            'manage_products' => 'Products',
                            'manage_users' => 'Users',
                            'manage_subadmins' => 'Sub-admins',
                            'manage_orders' => 'Orders',
                            'manage_news' => 'News/Banners',
                            'manage_marquee' => 'Marquee Text',
                            'manage_footer_marquee' => 'Footer Marquee',
                            'manage_featured_categories' => 'Featured Categories',
                            'manage_carousel' => 'Carousel Categories',
                            'manage_slider_settings' => 'Slider Settings',
                            'manage_awards' => 'Awards',
                            'manage_latest_products' => 'Latest Products',
                            'manage_video' => 'Video Section',
                            'manage_footer_settings' => 'Footer Settings',
                            'manage_seo' => 'SEO Manager',
                            'manage_homepage' => 'Homepage Features',
                            'manage_settings' => 'General Settings'
                        ];
                        foreach ($permLabels as $key => $label): ?>
                            <tr>
                                <td><strong><?php echo htmlspecialchars($label); ?></strong></td>
                                <td>
                                    <select name="<?php echo $key; ?>_level" class="level-select" id="level_<?php echo $key; ?>">
                                        <option value="none" class="level-none">None</option>
                                        <option value="viewer" class="level-viewer">Viewer</option>
                                        <option value="editor" class="level-editor">Editor</option>
                                        <option value="administrator" class="level-administrator">Administrator</option>
                                    </select>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <div style="margin-top:16px; display:flex; gap:8px;">
                <input type="hidden" name="original_user_id" id="original_user_id" value="">
                <input type="hidden" name="action" id="subadmin_action" value="add_subadmin">
                <button class="btn" type="submit" id="saveSubadminBtn" style="background:#4CAF50; color:#fff;">Save Sub-admin</button>
                <button class="btn" type="button" onclick="resetForm()" style="background:#f0f0f0; color:#333;">Reset</button>
            </div>
            <p class="small" style="margin-top:12px;">
                <strong>Note:</strong> Sub-admins are stored in data/subadmins.json. Permission levels control:
                <ul style="margin:4px 0; padding-left:20px;">
                    <li><strong>Viewer:</strong> Can only view/read content, no modifications</li>
                    <li><strong>Editor:</strong> Can view, create, and edit - but cannot delete</li>
                    <li><strong>Administrator:</strong> Can view, create, edit, and delete (full control)</li>
                </ul>
            </p>
        </form>
    </div>

    <div class="card" style="margin-top:16px;">
        <h3>Existing Sub-admins</h3>
        <?php if (empty($subadmins)): ?>
            <p class="small">No sub-admins configured yet.</p>
        <?php else: ?>
            <table width="100%" cellpadding="8" style="border-collapse:collapse;">
                <thead>
                    <tr style="background:#fafafa; text-align:left;"><th>User</th><th>Display Name</th><th>Permissions</th><th>Actions</th></tr>
                </thead>
                <tbody>
                <?php foreach ($subadmins as $key => $info): 
                    $uid = (int)($info['user_id'] ?? $key);
                    $userLabel = $info['display_name'] ?? '';
                    if (isset($conn) && $conn && $uid > 0) {
                        $uStmt = $conn->prepare('SELECT username, email FROM users WHERE id = ? LIMIT 1');
                        $uStmt->bind_param('i', $uid);
                        $uStmt->execute();
                        $ures = $uStmt->get_result();
                        if ($ures && $ures->num_rows) {
                            $ur = $ures->fetch_assoc();
                            $userLabel = htmlspecialchars($ur['username'] . ' (' . $ur['email'] . ')');
                        }
                        $uStmt->close();
                    }
                ?>
                    <tr style="border-top:1px solid #eee;">
                        <td style="vertical-align:top;"><?php echo $userLabel; ?></td>
                        <td style="vertical-align:top;"><?php echo htmlspecialchars($info['display_name'] ?? ''); ?></td>
                        <td style="vertical-align:top; font-size:12px;">
                            <?php if (!empty($info['permissions']) && is_array($info['permissions'])):
                                $permDisplay = [];
                                foreach ($info['permissions'] as $k=>$level) {
                                    if ($level !== 'none') {
                                        $permDisplay[] = htmlspecialchars($k) . ': <span class="level-' . $level . '">' . ucfirst($level) . '</span>';
                                    }
                                }
                                if (empty($permDisplay)) {
                                    echo '<span class="level-none">No permissions</span>';
                                } else {
                                    echo implode(', ', $permDisplay);
                                }
                            else:
                                echo '<span class="level-none">No permissions</span>';
                            endif; ?>
                        </td>
                        <td style="vertical-align:top;">
                            <div class="actions">
                                <button class="btn" type="button" onclick="editSubadmin('<?php echo htmlspecialchars($key); ?>')" style="background:#4caf50; color:#fff; border:none; cursor:pointer;">Edit</button>
                                <form method="post" style="display:inline;" onsubmit="return confirm('Remove sub-admin?');">
                                    <input type="hidden" name="action" value="delete_subadmin">
                                    <input type="hidden" name="user_id" value="<?php echo htmlspecialchars($key); ?>">
                                    <button class="btn" type="submit" style="background:#e74c3c; color:#fff; border:none; cursor:pointer;">Delete</button>
                                </form>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

</div>
</body>
</html>
<script>
async function editSubadmin(key) {
    try {
        const response = await fetch('data/subadmins.json');
        if (!response.ok) {
            alert('Unable to load sub-admin data (HTTP ' + response.status + ')');
            return;
        }
        const data = await response.json();
        const entry = data[key];
        if (!entry) {
            alert('Entry not found');
            return;
        }
        
        // Update form title
        document.getElementById('formTitle').textContent = 'Edit Sub-admin';
        
        // set select to user
        const sel = document.querySelector('select[name="user_id"]');
        if (sel) { 
            sel.value = key;
            sel.disabled = true;
        }
        document.getElementById('original_user_id').value = key;
        document.getElementById('subadmin_action').value = 'edit_subadmin';
        document.getElementById('saveSubadminBtn').textContent = 'Update Sub-admin';
        document.querySelector('input[name="display_name"]').value = entry.display_name || '';
        
        // Reset all permission levels to 'none'
        document.querySelectorAll('.level-select').forEach(sel => sel.value = 'none');
        
        // Set permission levels from data
        if (entry.permissions) {
            Object.keys(entry.permissions).forEach(k => {
                const el = document.getElementById('level_' + k);
                if (el) el.value = entry.permissions[k] || 'none';
            });
        }
        
        window.scrollTo({ top: 0, behavior: 'smooth' });
    } catch (err) { 
        console.error('Error loading subadmins data:', err);
        alert('Unable to load sub-admin data: ' + err.message);
    }
}

function resetForm() {
    document.getElementById('formTitle').textContent = 'Add New Sub-admin';
    document.getElementById('subadmin_action').value = 'add_subadmin';
    document.getElementById('original_user_id').value = '';
    document.getElementById('saveSubadminBtn').textContent = 'Save Sub-admin';
    const sel = document.querySelector('select[name="user_id"]');
    if (sel) sel.disabled = false;
    document.getElementById('subadminForm').reset();
    document.querySelectorAll('.level-select').forEach(s => s.value = 'none');
}
</script>
