<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

//error_reporting(E_ALL);
//ini_set('display_errors', 1);

// Test queries
$test = $conn->query("SELECT * FROM menu_items LIMIT 1");
if (!$test) {
    die("Menu items query failed: " . $conn->error);
}

if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    header('Location: login.php');
    exit();
}

// Database connection check
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Verify required tables
$tables = ['menu_items', 'role_permissions', 'user_role'];
foreach ($tables as $table) {
    $result = $conn->query("SHOW TABLES LIKE '$table'");
    if ($result->num_rows === 0) {
        die("Required table '$table' does not exist");
    }
}

// Fetch all roles
$roles_sql = "SELECT * FROM user_role ORDER BY role_name";
$roles_result = $conn->query($roles_sql);

// Get active role id
$active_role_id = $_GET['role_id'] ?? $_SESSION['role_id'];

/**
 * Build the menu tree recursively for the given role ID.
 *
 * @param int $roleId The role ID of the user.
 * @param int|null $parentId The parent ID of the menu item (null for top-level).
 * @return array The menu tree as a nested array.
 */
function buildMenuTree($roleId, $parentId = null) {
    global $conn;

    $sql = "SELECT 
            m.menu_id, 
            m.menu_name, 
            m.menu_url, 
            m.menu_icon, 
            m.parent_id, 
            m.menu_order,
            CASE WHEN rp.menu_id IS NOT NULL THEN 1 ELSE 0 END as has_permission
        FROM menu_items m
        LEFT JOIN role_permissions rp ON m.menu_id = rp.menu_id AND rp.role_id = ?
        WHERE m.parent_id " . ($parentId === null ? "IS NULL" : "= ?") . "
        AND m.is_active = 1
        ORDER BY m.menu_order";

    $stmt = $conn->prepare($sql);
    if ($parentId === null) {
        $stmt->bind_param('i', $roleId);
    } else {
        $stmt->bind_param('ii', $roleId, $parentId);
    }

    $stmt->execute();
    $result = $stmt->get_result();
    $menu = [];

    while ($row = $result->fetch_assoc()) {
        $menuItem = [
            'id' => (int)$row['menu_id'],
            'name' => $row['menu_name'],
            'icon' => $row['menu_icon'],
            'url' => $row['menu_url'],
            'has_permission' => (bool)$row['has_permission'],
            'children' => buildMenuTree($roleId, $row['menu_id'])
        ];
        $menu[] = $menuItem;
    }

    return $menu;
}

// Initialize menu items
$menu_items = [];
try {
    $menu_items = buildMenuTree($active_role_id); // Correct function name
} catch (Exception $e) {
    die("Error building menu: " . $e->getMessage());
}

?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Role Permissions')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .role-list { height: calc(100vh - 240px); overflow-y: auto; }
        .menu-list { height: calc(100vh - 240px); overflow-y: auto; }
        .role-card { cursor: pointer; transition: all 0.2s; }
        .role-card:hover { background-color: #f8f9fa; }
        .role-card.active { background-color: #e9ecef; border-left: 4px solid var(--vz-primary); }
        .menu-section { border-bottom: 1px solid #eee; padding: 1rem; }
        .menu-item { padding: 0.5rem 1rem; margin-left: 2rem; }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row">
                        <!-- Roles Column -->
                        <div class="col-md-3">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Roles</h5>
                                </div>
                                <div class="card-body p-0 role-list">
                                    <?php while($role = $roles_result->fetch_assoc()): ?>
                                    <div class="role-card p-3 <?php echo $role['role_id'] == $active_role_id ? 'active' : ''; ?>"
                                         onclick="loadRolePermissions(<?php echo $role['role_id']; ?>)">
                                        <h6 class="mb-1"><?php echo htmlspecialchars($role['role_name']); ?></h6>
                                        <small class="text-muted">
                                            <?php
                                            $count_sql = "SELECT COUNT(*) as count FROM users WHERE role_id = " . $role['role_id'];
                                            $count = $conn->query($count_sql)->fetch_assoc()['count'];
                                            echo $count . ' user' . ($count != 1 ? 's' : '');
                                            ?>
                                        </small>
                                    </div>
                                    <?php endwhile; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Permissions Column -->
                        <div class="col-md-9">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="card-title mb-0">Menu Permissions</h5>
                                    <button class="btn btn-secondary me-2" onclick="toggleAllPermissions(false)">
                                        <i class="ri-close-circle-line align-middle me-1"></i> Unselect All
                                    </button>
                                    <button class="btn btn-secondary me-2" onclick="toggleAllPermissions(true)">
                                        <i class="ri-checkbox-circle-line align-middle me-1"></i> Select All
                                    </button>
                                    <?php if ($active_role_id): ?>
                                    <button class="btn btn-primary" onclick="savePermissions()">
                                        <i class="ri-save-line align-middle me-1"></i> Save Changes
                                    </button>
                                    <?php endif; ?>
                                </div>
                                <div class="card-body menu-list">
                                    <?php if ($active_role_id): ?>
                                        <?php
                                        // Build the menu tree based on the active role ID
                                        $menu_tree = buildMenuTree($active_role_id);
                                        ?>
                                
                                        <?php if (!empty($menu_tree)): ?>
                                        <form id="permissionsForm">
                                            <input type="hidden" name="role_id" value="<?php echo $active_role_id; ?>">
                                
                                            <?php
                                            /**
                                             * Render the dynamic menu tree.
                                             *
                                             * @param array $menuItems Menu items to render.
                                             */
                                            function renderMenu($menuItems) {
                                    foreach ($menuItems as $menu) {
                                        echo '<div class="menu-section">';
                                        echo '<div class="form-check mb-3">';
                                        echo '<input class="form-check-input section-toggle"
                                                     type="checkbox"
                                                     id="section_' . $menu['id'] . '"
                                                     data-section="' . $menu['id'] . '"
                                                     name="permissions[]"
                                                     value="' . $menu['id'] . '"
                                                     ' . ($menu['has_permission'] ? 'checked' : '') . '>';
                                        echo '<label class="form-check-label" for="section_' . $menu['id'] . '">';
                                        if (!empty($menu['icon'])) {
                                            echo '<i class="' . htmlspecialchars($menu['icon']) . ' align-middle me-1"></i>';
                                        }
                                        echo htmlspecialchars($menu['name']);
                                        echo ' <small class="text-' . ($menu['has_permission'] ? 'success' : 'danger') . '">(' . 
                                             ($menu['has_permission'] ? 'Assigned' : 'Not Assigned') . ')</small>';
                                        echo '</label>';
                                        echo '</div>';
                                
                                        if (!empty($menu['children'])) {
                                            echo '<div class="menu-items">';
                                            foreach ($menu['children'] as $child) {
                                                echo '<div class="form-check menu-item">';
                                                echo '<input class="form-check-input menu-item-check"
                                                             type="checkbox"
                                                             id="item_' . $child['id'] . '"
                                                             data-parent="' . $menu['id'] . '"
                                                             name="permissions[]"
                                                             value="' . $child['id'] . '"
                                                             ' . ($child['has_permission'] ? 'checked' : '') . '>';
                                                echo '<label class="form-check-label" for="item_' . $child['id'] . '">';
                                                if (!empty($child['icon'])) {
                                                    echo '<i class="' . htmlspecialchars($child['icon']) . ' align-middle me-1"></i>';
                                                }
                                                echo htmlspecialchars($child['name']);
                                                echo ' <small class="text-' . ($child['has_permission'] ? 'success' : 'danger') . '">(' . 
                                                     ($child['has_permission'] ? 'Assigned' : 'Not Assigned') . ')</small>';
                                                echo '</label>';
                                                echo '</div>';
                                            }
                                            echo '</div>';
                                        }
                                        echo '</div>';
                                    }
                                }
                                
                                            // Render the menu tree
                                            renderMenu($menu_tree);
                                            ?>
                                        </form>
                                        <?php else: ?>
                                        <div class="alert alert-info">
                                            <i class="ri-information-line me-2"></i>
                                            No menu items found. Please check the database configuration.
                                        </div>
                                        <?php endif; ?>
                                    <?php else: ?>
                                    <div class="text-center p-4">
                                        <i class="ri-folder-lock-line display-4 text-muted"></i>
                                        <h5 class="mt-3">Select a role to manage permissions</h5>
                                    </div>
                                    <?php endif; ?>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Handle parent checkbox change
            document.querySelectorAll('.section-toggle').forEach(toggle => {
                toggle.addEventListener('change', function() {
                    const section = this.dataset.section;
                    const items = document.querySelectorAll(`.menu-item-check[data-parent="${section}"]`);
                    items.forEach(item => item.checked = this.checked);
                });
            });

            // Handle child checkbox change
            document.querySelectorAll('.menu-item-check').forEach(item => {
                item.addEventListener('change', function() {
                    const parentId = this.dataset.parent;
                    const parentCheckbox = document.querySelector(`#section_${parentId}`);
                    const siblings = document.querySelectorAll(`.menu-item-check[data-parent="${parentId}"]`);
                    const allChecked = Array.from(siblings).every(sib => sib.checked);
                    parentCheckbox.checked = allChecked;
                });
            });
        });
        
        function toggleAllPermissions(state) {
            document.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
                checkbox.checked = state;
                // Update parent checkboxes if needed
                if (checkbox.classList.contains('menu-item-check')) {
                    const parentId = checkbox.dataset.parent;
                    const parentCheckbox = document.querySelector(`#section_${parentId}`);
                    const siblings = document.querySelectorAll(`.menu-item-check[data-parent="${parentId}"]`);
                    const allChecked = Array.from(siblings).every(sib => sib.checked);
                    parentCheckbox.checked = allChecked;
                }
            });
        }

        function loadRolePermissions(roleId) {
            window.location.href = `role_permissions.php?role_id=${roleId}`;
        }

        function savePermissions() {
            const form = document.getElementById('permissionsForm');
            const formData = new FormData(form);

            fetch('save_permissions.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: 'Permissions saved successfully'
                    }).then(() => {
                        window.location.reload();
                    });
                } else {
                    throw new Error(data.error || 'Failed to save permissions');
                }
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error.message
                });
            });
        }
    </script>
</body>
</html>
