<?php
require_once './database/shikanisha.kts.php';

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if user is logged in
if (!isset($_SESSION['eid']) || !isset($_SESSION['role_id'])) {
    header("Location: logout.php");
    exit();
}

// Check if user has access to this page
$current_page = basename($_SERVER['PHP_SELF']);
$check_access = $conn->prepare("SELECT 1 FROM access_control ac 
                              JOIN pages p ON ac.page_id = p.page_id 
                              WHERE p.link = ? AND ac.role_id = ?");
$check_access->bind_param("si", $current_page, $_SESSION['role_id']);
$check_access->execute();
$has_access = $check_access->get_result()->num_rows > 0;
$check_access->close();

if (!$has_access) {
    header("Location: unauthorized.php");
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Access Control</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <style>
        :root {
            --glass-color: rgba(255, 255, 255, 0.2);
            --glass-border: 1px solid rgba(255, 255, 255, 0.3);
            --glass-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
            --blur: blur(10px);
            --primary-color: #4a6bff;
        }

        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: white;
        }

        .glass-card {
            background: var(--glass-color);
            backdrop-filter: var(--blur);
            -webkit-backdrop-filter: var(--blur);
            border-radius: 15px;
            padding: 1.5rem;
            border: var(--glass-border);
            box-shadow: var(--glass-shadow);
            transition: all 0.3s ease;
        }

        .glass-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
        }

        .nav-tabs .nav-link {
            color: rgba(255, 255, 255, 0.8);
        }

        .nav-tabs .nav-link.active {
            background: var(--glass-color);
            color: white;
            border-color: var(--glass-border);
        }

        .table {
            color: white;
        }

        .dataTables_wrapper .dataTables_filter input {
            color: white;
            background: var(--glass-color);
            border: var(--glass-border);
        }

        .dataTables_wrapper .dataTables_length select {
            color: white;
            background: var(--glass-color);
            border: var(--glass-border);
        }

        .dataTables_wrapper .dataTables_info {
            color: rgba(255, 255, 255, 0.8);
        }

        .form-control, .form-select {
            background: var(--glass-color);
            border: var(--glass-border);
            color: white;
        }

        .form-control:focus, .form-select:focus {
            background: var(--glass-color);
            border: var(--glass-border);
            color: white;
            box-shadow: 0 0 0 0.25rem rgba(74, 107, 255, 0.25);
        }

        .toast {
            background: var(--glass-color);
            backdrop-filter: var(--blur);
            -webkit-backdrop-filter: var(--blur);
            border: var(--glass-border);
        }

        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }

        .form-check-input:checked {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
    </style>
</head>
<body>
    <div class="container-fluid py-4">
        <div class="row">
            <div class="col-md-12">
                <div class="glass-card">
                    <div class="card-header bg-transparent border-bottom">
                        <h4><i class="fas fa-lock me-2"></i>Access Control Management</h4>
                    </div>
                    <div class="card-body">
                        <ul class="nav nav-tabs" id="myTab" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="pages-tab" data-bs-toggle="tab" data-bs-target="#pages" type="button" role="tab">
                                    <i class="fas fa-file me-2"></i>Pages
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="access-tab" data-bs-toggle="tab" data-bs-target="#access" type="button" role="tab">
                                    <i class="fas fa-key me-2"></i>Permissions
                                </button>
                            </li>
                        </ul>
                        <div class="tab-content mt-3" id="myTabContent">
                            <div class="tab-pane fade show active" id="pages" role="tabpanel">
                                <button class="btn btn-primary mb-3" id="addPageBtn">
                                    <i class="fas fa-plus me-2"></i>Add New Page
                                </button>
                                <div class="table-responsive">
                                    <table class="table table-borderless" id="pagesTable">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Page Name</th>
                                                <th>Link</th>
                                                <th>Icon</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <!-- Pages loaded via AJAX -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="tab-pane fade" id="access" role="tabpanel">
                                <div class="row mb-3">
                                    <div class="col-md-4">
                                        <select class="form-select" id="roleSelect">
                                            <!-- Roles loaded via AJAX -->
                                        </select>
                                    </div>
                                </div>
                                <div class="table-responsive">
                                    <table class="table table-borderless" id="accessTable">
                                        <thead>
                                            <tr>
                                                <th>Page Name</th>
                                                <th>Access</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <!-- Permissions loaded via AJAX -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Page Modal -->
    <div class="modal fade" id="pageModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content glass-card">
                <div class="modal-header border-bottom">
                    <h5 class="modal-title" id="modalTitle">Add New Page</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="pageForm">
                        <input type="hidden" id="pageId">
                        <div class="mb-3">
                            <label for="pageName" class="form-label">Page Name</label>
                            <input type="text" class="form-control" id="pageName" required>
                        </div>
                        <div class="mb-3">
                            <label for="pageLink" class="form-label">Link</label>
                            <input type="text" class="form-control" id="pageLink" required>
                        </div>
                        <div class="mb-3">
                            <label for="pageIcon" class="form-label">Icon</label>
                            <input type="text" class="form-control" id="pageIcon" required>
                            <small class="text-muted">e.g. fas fa-home</small>
                        </div>
                    </form>
                </div>
                <div class="modal-footer border-top">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="savePageBtn">Save</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script>
    $(document).ready(function() {
        // Initialize DataTables
        const pagesTable = $('#pagesTable').DataTable({
            ajax: {
                url: './database/get_pages.kts.php',
                dataSrc: ''
            },
            columns: [
                { data: 'page_id' },
                { data: 'page_name' },
                { data: 'link' },
                { 
                    data: 'icon',
                    render: function(data) {
                        return `<i class="${data} me-2"></i>${data}`;
                    }
                },
                {
                    data: 'page_id',
                    render: function(data) {
                        return `
                            <div class="btn-group">
                                <button class="btn btn-sm btn-primary edit-page" data-id="${data}">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-sm btn-danger delete-page" data-id="${data}">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        `;
                    },
                    orderable: false
                }
            ]
        });

        const accessTable = $('#accessTable').DataTable({
            columns: [
                { 
                    data: 'page_name',
                    render: function(data, type, row) {
                        return `<i class="${row.icon} me-2"></i>${data}`;
                    }
                },
                {
                    data: 'has_access',
                    render: function(data, type, row) {
                        const checked = data ? 'checked' : '';
                        return `
                            <div class="form-check form-switch">
                                <input class="form-check-input access-checkbox" type="checkbox" 
                                    data-page-id="${row.page_id}" ${checked}>
                            </div>
                        `;
                    },
                    orderable: false
                }
            ]
        });

        // Load roles
        $.get('./database/get_roles.kts.php', function(roles) {
            let options = '<option value="">Select Role</option>';
            roles.forEach(role => {
                options += `<option value="${role.role_id}">${role.role_name}</option>`;
            });
            $('#roleSelect').html(options);
        }).fail(() => alert('Error loading roles'));

        // Role selection change
        $('#roleSelect').change(function() {
            const roleId = $(this).val();
            if (roleId) {
                $.get('./database/get_access_permissions.kts.php', { role_id: roleId }, function(data) {
                    accessTable.clear().rows.add(data).draw();
                }).fail(() => alert('Error loading permissions'));
            } else {
                accessTable.clear().draw();
            }
        });

        // Add Page button
        $('#addPageBtn').click(function() {
            $('#pageId').val('');
            $('#pageForm')[0].reset();
            $('#modalTitle').text('Add New Page');
            $('#pageModal').modal('show');
        });

        // Edit Page button
        $(document).on('click', '.edit-page', function() {
            const pageId = $(this).data('id');
            $.get('./database/get_page.kts.php', { page_id: pageId }, function(page) {
                $('#pageId').val(page.page_id);
                $('#pageName').val(page.page_name);
                $('#pageLink').val(page.link);
                $('#pageIcon').val(page.icon);
                $('#modalTitle').text('Edit Page');
                $('#pageModal').modal('show');
            }).fail(() => alert('Error loading page'));
        });

        // Save Page
        $('#savePageBtn').click(function() {
            const pageId = $('#pageId').val();
            const pageData = {
                page_name: $('#pageName').val(),
                link: $('#pageLink').val(),
                icon: $('#pageIcon').val()
            };

            if (!pageData.page_name || !pageData.link || !pageData.icon) {
                showToast('Please fill all fields', 'danger');
                return;
            }

            const url = pageId ? './database/update_page.kts.php' : './database/add_page.kts.php';
            if (pageId) pageData.page_id = pageId;

            $.post(url, pageData, function(response) {
                if (response.success) {
                    $('#pageModal').modal('hide');
                    pagesTable.ajax.reload();
                    showToast('Page saved successfully');
                } else {
                    showToast(response.message || 'Error saving page', 'danger');
                }
            }, 'json').fail(() => showToast('Error communicating with server', 'danger'));
        });

        // Delete Page
        $(document).on('click', '.delete-page', function() {
            if (confirm('Are you sure you want to delete this page?')) {
                const pageId = $(this).data('id');
                $.post('./database/delete_page.kts.php', { page_id: pageId }, function(response) {
                    if (response.success) {
                        pagesTable.ajax.reload();
                        showToast('Page deleted successfully');
                    } else {
                        showToast(response.message || 'Error deleting page', 'danger');
                    }
                }, 'json').fail(() => showToast('Error deleting page', 'danger'));
            }
        });

        // Toggle Access Permission
        $(document).on('change', '.access-checkbox', function() {
            const pageId = $(this).data('page-id');
            const roleId = $('#roleSelect').val();
            const hasAccess = $(this).is(':checked') ? 1 : 0;

            if (!roleId) {
                $(this).prop('checked', !hasAccess);
                showToast('Please select a role first', 'danger');
                return;
            }

            $.post('./database/update_access.kts.php', { 
                page_id: pageId, 
                role_id: roleId, 
                has_access: hasAccess 
            }, function(response) {
                if (!response.success) {
                    $(this).prop('checked', !hasAccess);
                    showToast(response.message || 'Error updating access', 'danger');
                } else {
                    showToast('Access updated successfully');
                }
            }, 'json').fail(() => {
                $(this).prop('checked', !hasAccess);
                showToast('Error updating access', 'danger');
            });
        });

        // Toast notification
        function showToast(message, type = 'success') {
            const bgClass = type === 'success' ? 'bg-primary' : 'bg-danger';
            const toast = `
                <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11">
                    <div class="toast show" role="alert" aria-live="assertive" aria-atomic="true">
                        <div class="toast-header ${bgClass} text-white">
                            <strong class="me-auto">${type === 'success' ? 'Success' : 'Error'}</strong>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast" aria-label="Close"></button>
                        </div>
                        <div class="toast-body">${message}</div>
                    </div>
                </div>
            `;
            $(toast).appendTo('body').delay(3000).fadeOut(400, function() { $(this).remove(); });
        }
    });
    </script>
</body>
</html>