<?php include 'layouts/session.php'; ?>
<?php include 'layouts/main.php'; ?>
<?php include 'layouts/dbconn.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'User Roles')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- DataTables CSS -->
    <link href="assets/libs/datatables.net-bs4/css/dataTables.bootstrap4.min.css" rel="stylesheet">
    <link href="assets/libs/datatables.net-responsive-bs4/css/responsive.bootstrap4.min.css" rel="stylesheet">
    <!-- Sweet Alert css -->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css">
</head>

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

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'User Management', 'title' => 'User Roles')); ?>

                    <!-- Display messages -->
                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="mdi mdi-check-all me-2"></i>
                            <?php echo $_SESSION['success_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['success_message']); ?>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="mdi mdi-block-helper me-2"></i>
                            <?php echo $_SESSION['error_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['error_message']); ?>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header d-flex align-items-center">
                                    <h5 class="card-title mb-0 flex-grow-1">All User Roles</h5>
                                    <a href="add_role.php" class="btn btn-primary">
                                        <i class="ri-add-line align-middle me-1"></i> Add New Role
                                    </a>
                                </div>
                                <div class="card-body">
                                    <table id="roles-table" class="table table-bordered dt-responsive nowrap table-striped">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Role Name</th>
                                                <th>Total Users</th>
                                                <th>Created Date</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $sql = "SELECT r.*, COUNT(u.user_id) as user_count 
                                                   FROM user_role r 
                                                   LEFT JOIN users u ON r.role_id = u.role_id 
                                                   GROUP BY r.role_id 
                                                   ORDER BY r.role_name";
                                            $result = $conn->query($sql);

                                            if ($result && $result->num_rows > 0) {
                                                while($row = $result->fetch_assoc()) {
                                                    $statusClass = $row['user_count'] > 0 ? 'badge bg-success' : 'badge bg-warning';
                                                    $statusText = $row['user_count'] > 0 ? 'Active' : 'Unused';
                                                    $created_at = isset($row['created_at']) ? date('d M Y', strtotime($row['created_at'])) : 'N/A';

                                                    echo "<tr>";
                                                    echo "<td>{$row['role_id']}</td>";
                                                    echo "<td>{$row['role_name']}</td>";
                                                    echo "<td>{$row['user_count']}</td>";
                                                    echo "<td>{$created_at}</td>";
                                                    echo "<td><span class='{$statusClass}'>{$statusText}</span></td>";
                                                    echo "<td>
                                                            <div class='d-flex gap-2'>
                                                                <a href='view_role.php?id={$row['role_id']}' 
                                                                   class='btn btn-sm btn-soft-primary'>
                                                                    <i class='ri-eye-fill'></i>
                                                                </a>
                                                                <a href='edit_role.php?id={$row['role_id']}' 
                                                                   class='btn btn-sm btn-soft-info'>
                                                                    <i class='ri-pencil-fill'></i>
                                                                </a>";
                                                    if ($row['user_count'] == 0) {
                                                        echo "<button type='button' 
                                                                    class='btn btn-sm btn-soft-danger delete-role'
                                                                    data-id='{$row['role_id']}'>
                                                                <i class='ri-delete-bin-line'></i>
                                                            </button>";
                                                    }
                                                    echo "</div>
                                                          </td>";
                                                    echo "</tr>";
                                                }
                                            }
                                            ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- DataTables JS -->
    <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables.net-bs4/js/dataTables.bootstrap4.min.js"></script>
    <script src="assets/libs/datatables.net-responsive/js/dataTables.responsive.min.js"></script>
    <script src="assets/libs/datatables.net-responsive-bs4/js/responsive.bootstrap4.min.js"></script>
    
    <!-- Sweet Alerts js -->
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <!-- App js -->
    <script src="assets/js/app.js"></script>
    
    <script>
    $(document).ready(function() {
        // Initialize DataTable
        $('#roles-table').DataTable({
            order: [[1, 'asc']], // Sort by role name ascending
            pageLength: 25,
            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
            language: {
                paginate: {
                    previous: "<i class='mdi mdi-chevron-left'>",
                    next: "<i class='mdi mdi-chevron-right'>"
                }
            },
            drawCallback: function() {
                $('.dataTables_paginate > .pagination').addClass('pagination-rounded');
            }
        });

        // Handle delete button clicks
        $(document).on('click', '.delete-role', function() {
            const roleId = $(this).data('id');
            
            Swal.fire({
                title: 'Are you sure?',
                text: "This action cannot be undone",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, delete it!',
                cancelButtonText: 'No, cancel!',
                confirmButtonClass: 'btn btn-primary w-xs me-2 mt-2',
                cancelButtonClass: 'btn btn-danger w-xs mt-2',
                buttonsStyling: false,
                showCloseButton: true
            }).then((result) => {
                if (result.isConfirmed) {
                    // Send delete request
                    $.ajax({
                        url: 'delete_role.php',
                        type: 'POST',
                        data: { role_id: roleId },
                        success: function(response) {
                            try {
                                const data = JSON.parse(response);
                                if (data.success) {
                                    Swal.fire({
                                        title: 'Deleted!',
                                        text: data.message,
                                        icon: 'success',
                                        confirmButtonClass: 'btn btn-primary w-xs mt-2',
                                        buttonsStyling: false
                                    }).then(() => {
                                        location.reload();
                                    });
                                } else {
                                    Swal.fire({
                                        title: 'Error!',
                                        text: data.message,
                                        icon: 'error',
                                        confirmButtonClass: 'btn btn-primary w-xs mt-2',
                                        buttonsStyling: false
                                    });
                                }
                            } catch (e) {
                                Swal.fire({
                                    title: 'Error!',
                                    text: 'Invalid server response',
                                    icon: 'error',
                                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                                    buttonsStyling: false
                                });
                                console.error(e, response);
                            }
                        },
                        error: function(xhr, status, error) {
                            Swal.fire({
                                title: 'Error!',
                                text: 'Failed to delete role: ' + error,
                                icon: 'error',
                                confirmButtonClass: 'btn btn-primary w-xs mt-2',
                                buttonsStyling: false
                            });
                        }
                    });
                }
            });
        });
    });
    </script>
</body>
</html>