<?php
session_start();

// Only admin can access
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
    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','manage_logo','manage_slider_images','manage_colors','manage_categories',
        'manage_pages','manage_social','manage_blogs','manage_products','manage_users','manage_subadmins',
        'manage_orders','manage_news','manage_marquee','manage_footer_marquee','manage_featured_categories',
        'manage_carousel','manage_slider_settings','manage_awards','manage_latest_products','manage_video',
        'manage_footer_settings','manage_seo','manage_homepage','manage_settings'
    ];

    if ($action === 'add_subadmin' || $action === 'edit_subadmin') {
        $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'] ?? '');
        $perms = [];
        foreach ($available as $p) {
            $perms[$p] = !empty($_POST[$p]) ? true : false;
        }

        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') {
        $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:1000px; 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; }
.checkbox-grid { display:flex; gap:12px; flex-wrap:wrap; }
.small { font-size:13px; color:#666; }
.actions { display:flex; gap:8px; }
input, select { padding:6px; border:1px solid #ddd; border-radius:4px; font-size:13px; }
</style>
</head>
<body>
<div class="container">
    <a href="admin_dashboard.php" class="btn">← Back to Dashboard</a>
    <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">
            <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:8px;">
                <label style="display:block; margin-bottom:6px; font-weight:600;">Permissions (select features the sub-admin may access)</label>
                <div class="checkbox-grid">
                    <?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): ?>
                        <label><input type="checkbox" name="<?php echo $key; ?>"> <?php echo $label; ?></label>
                    <?php endforeach; ?>
                </div>
            </div>
                <div style="margin-top:12px; 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">Note: Sub-admins are stored in data/subadmins.json and are linked to existing users. Permissions control which admin features they can access.</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 (10 of many shown...)</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'])):
                                $ps = [];
                                $count = 0;
                                foreach ($info['permissions'] as $k=>$v) {
                                    if ($v) $ps[] = $k;
                                    if (++$count > 10) break;
                                }
                                echo htmlspecialchars(implode(', ', $ps)) . (count($info['permissions']) > 10 ? ' ...' : '');
                            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) {
    // key is the user_id as string
    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; // Prevent changing user once editing
        }
        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 || '';
        
        // uncheck all first
        document.querySelectorAll('.checkbox-grid input[type="checkbox"]').forEach(cb => cb.checked = false);
        if (entry.permissions) {
            Object.keys(entry.permissions).forEach(k => {
                const el = document.querySelector('.checkbox-grid input[name="' + k + '"]');
                if (el) el.checked = !!entry.permissions[k];
            });
        }
        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.querySelectorAll('form')[0].reset();
}
</script>

