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

// Enable error reporting for development
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors on page
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');

require_once('../includes/admin-security.php');
include_once('includes/config.php');

// Access Check
if (!has_permission('manage_settings')) {
    echo "<script>alert('Access Denied. Redirecting to Dashboard...'); window.location.href='dashboard.php';</script>";
    exit();
}

// Handle Updates
if (isset($_POST['update_permissions'])) {
    // Clear existing role_permissions (Doing a full reset is easiest for a grid UI)
    // Optimization: In a huge system, we'd only update changes. Here, small data = truncate/re-insert safe for this table PARTITION? No, just delete for these roles.
    // Actually, we should only delete for roles we are managing to avoid clearing roles we don't display?
    // Let's assume we display 'admin', 'staff', 'sales', 'vendor'.

    $roles_to_manage = ['admin', 'staff', 'sales', 'vendor'];
    $role_list = "'" . implode("','", $roles_to_manage) . "'";

    // Transaction start
    mysqli_begin_transaction($con);

    try {
        // Delete existing permissions for managed roles
        mysqli_query($con, "DELETE FROM role_permissions WHERE role IN ($role_list)");

        // Insert new selections
        if (isset($_POST['perms']) && is_array($_POST['perms'])) {
            foreach ($_POST['perms'] as $role => $slugs) {
                if (in_array($role, $roles_to_manage)) {
                    foreach ($slugs as $slug => $value) {
                        $r_esc = mysqli_real_escape_string($con, $role);
                        $s_esc = mysqli_real_escape_string($con, $slug);
                        mysqli_query($con, "INSERT INTO role_permissions (role, permission_slug) VALUES ('$r_esc', '$s_esc')");
                    }
                }
            }
        }

        mysqli_commit($con);
        $_SESSION['msg'] = "Permissions updated successfully.";
    } catch (Exception $e) {
        mysqli_rollback($con);
        $_SESSION['error'] = "Failed to update permissions: " . $e->getMessage();
    }
}


// Fetch Permissions
$perm_query = mysqli_query($con, "SELECT * FROM permissions ORDER BY category, description");
$all_permissions = [];
while ($row = mysqli_fetch_assoc($perm_query)) {
    $all_permissions[] = $row;
}

// Fetch Current Grants
$grant_query = mysqli_query($con, "SELECT * FROM role_permissions");
$granted = [];
while ($row = mysqli_fetch_assoc($grant_query)) {
    $granted[$row['role']][$row['permission_slug']] = true;
}

$roles = ['admin', 'staff', 'sales', 'vendor'];
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Manage User Permissions | Admin</title>
    <link href="css/styles.css" rel="stylesheet" />
    <link href="css/admin-professional.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"></script>
</head>

<body class="sb-nav-fixed">
    <?php include_once('includes/header.php'); ?>
    <div id="layoutSidenav">
        <?php include_once('includes/sidebar.php'); ?>
        <div id="layoutSidenav_content">
            <main>
                <div class="container-fluid px-4">
                    <h1 class="mt-4"><i class="fas fa-user-shield me-2"></i>Permission Management</h1>

                    <?php if (isset($_SESSION['msg'])) { ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['msg'];
                            unset($_SESSION['msg']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php } ?>
                    <?php if (isset($_SESSION['error'])) { ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['error'];
                            unset($_SESSION['error']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php } ?>

                    <div class="card mb-4 mt-4">
                        <div class="card-header">
                            <i class="fas fa-table me-1"></i>
                            Role Access Control
                        </div>
                        <div class="card-body">
                            <form method="post">
                                <div class="table-responsive">
                                    <table class="table table-bordered table-striped">
                                        <thead class="table-dark text-center">
                                            <tr>
                                                <th class="text-start">Permission / Feature</th>
                                                <?php foreach ($roles as $role) { ?>
                                                    <th width="15%" class="text-uppercase">
                                                        <?php echo $role; ?>
                                                    </th>
                                                <?php } ?>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $current_cat = '';
                                            foreach ($all_permissions as $perm) {
                                                if ($perm['category'] != $current_cat) {
                                                    $current_cat = $perm['category'];
                                                    echo '<tr class="table-secondary"><td colspan="' . (count($roles) + 1) . '" class="fw-bold">' . $current_cat . '</td></tr>';
                                                }
                                                ?>
                                                <tr>
                                                    <td>
                                                        <div class="fw-bold">
                                                            <?php echo $perm['description']; ?>
                                                        </div>
                                                        <small class="text-muted">
                                                            <?php echo $perm['permission_slug']; ?>
                                                        </small>
                                                    </td>
                                                    <?php foreach ($roles as $role) {
                                                        $isChecked = isset($granted[$role][$perm['permission_slug']]) ? 'checked' : '';
                                                        $isDisabled = ($role == 'admin' && $perm['permission_slug'] != 'dummy_check') ? 'disabled checked' : ''; // Force admin to have all? Maybe too strict. Let's make it flexible but warn? for now let's just make Admin strict checked to prevent lockout.
                                                
                                                        // Actually, let's allow editing admin rights but be careful.
                                                        // Safety: Force admin to have 'manage_settings' and 'manage_users' via backend logic if we wanted.
                                                        // For UI, we'll just check it.
                                                        ?>
                                                        <td class="text-center">
                                                            <div class="form-check d-flex justify-content-center">
                                                                <input class="form-check-input" type="checkbox"
                                                                    name="perms[<?php echo $role; ?>][<?php echo $perm['permission_slug']; ?>]"
                                                                    value="1" <?php echo $isChecked; ?>>
                                                            </div>
                                                        </td>
                                                    <?php } ?>
                                                </tr>
                                            <?php } ?>
                                        </tbody>
                                    </table>
                                </div>
                                <div class="d-grid gap-2 d-md-flex justify-content-md-end mt-3">
                                    <button type="submit" name="update_permissions" class="btn btn-primary"><i
                                            class="fas fa-save me-2"></i>Save Permissions</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </main>
            <?php include_once('includes/footer.php'); ?>
        </div>
    </div>
    <script src="js/bootstrap.bundle.min.js"></script>
    <script src="js/scripts.js"></script>
</body>

</html>
