<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('user_management');

$pdo = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add' || $action === 'edit') {
        $id = (int)($_POST['id'] ?? 0);
        $permission_key = trim($_POST['permission_key']);
        $permission_name = trim($_POST['permission_name']);
        $module_name = trim($_POST['module_name']);

        if (empty($permission_key) || empty($permission_name)) {
            $_SESSION['error'] = 'Permission key and name are required.';
        } else {
            try {
                if ($action === 'add') {
                    $stmt = $pdo->prepare("INSERT INTO permissions (permission_key, permission_name, module_name) VALUES (?,?,?)");
                    $stmt->execute([$permission_key, $permission_name, $module_name]);
                    logActivity('Created Permission', 'Permissions', $pdo->lastInsertId(), "Permission: $permission_key");
                    $_SESSION['success'] = 'Permission created successfully.';
                } else {
                    $stmt = $pdo->prepare("UPDATE permissions SET permission_key=?, permission_name=?, module_name=? WHERE id=?");
                    $stmt->execute([$permission_key, $permission_name, $module_name, $id]);
                    logActivity('Updated Permission', 'Permissions', $id, "Permission: $permission_key");
                    $_SESSION['success'] = 'Permission updated successfully.';
                }
            } catch (PDOException $e) {
                $_SESSION['error'] = 'Error: ' . $e->getMessage();
            }
        }
        header('Location: permissions.php');
        exit;
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id) {
            $stmt = $pdo->prepare("DELETE FROM role_permissions WHERE permission_id=?");
            $stmt->execute([$id]);
            $stmt = $pdo->prepare("DELETE FROM permissions WHERE id=?");
            $stmt->execute([$id]);
            logActivity('Deleted Permission', 'Permissions', $id);
            $_SESSION['success'] = 'Permission deleted successfully.';
        }
        header('Location: permissions.php');
        exit;
    }
}

$edit_perm = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM permissions WHERE id=?");
    $stmt->execute([(int)$_GET['edit']]);
    $edit_perm = $stmt->fetch();
}

$permissions = $pdo->query("SELECT p.*, COALESCE(rp.role_count, 0) as assigned_roles FROM permissions p LEFT JOIN (SELECT permission_id, COUNT(*) as role_count FROM role_permissions GROUP BY permission_id) rp ON p.id = rp.permission_id ORDER BY p.module_name, p.permission_name")->fetchAll();
$modules = $pdo->query("SELECT DISTINCT module_name FROM permissions ORDER BY module_name")->fetchAll(PDO::FETCH_COLUMN);

include __DIR__ . '/../includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
    <h4 class="mb-0"><i class="fas fa-key me-2"></i>Permission Management</h4>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#permModal"><i class="fas fa-plus me-1"></i>Add Permission</button>
</div>

<?php if (isset($_SESSION['success'])): ?>
    <div class="alert alert-success alert-dismissible fade show"><?= htmlspecialchars($_SESSION['success']) ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
    <?php unset($_SESSION['success']); ?>
<?php endif; ?>
<?php if (isset($_SESSION['error'])): ?>
    <div class="alert alert-danger alert-dismissible fade show"><?= htmlspecialchars($_SESSION['error']) ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
    <?php unset($_SESSION['error']); ?>
<?php endif; ?>

<div class="card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover no-datatable" id="permissionsTable">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Module</th>
                        <th>Permission Key</th>
                        <th>Permission Name</th>
                        <th>Assigned Roles</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($permissions as $p): ?>
                        <tr>
                            <td><?= $p['id'] ?></td>
                            <td><span class="badge bg-secondary"><?= htmlspecialchars($p['module_name']) ?></span></td>
                            <td><code><?= htmlspecialchars($p['permission_key']) ?></code></td>
                            <td><?= htmlspecialchars($p['permission_name']) ?></td>
                            <td><span class="badge bg-info"><?= $p['assigned_roles'] ?></span></td>
                            <td>
                                <a href="?edit=<?= $p['id'] ?>" class="btn btn-sm btn-outline-primary edit-perm" data-id="<?= $p['id'] ?>" data-key="<?= htmlspecialchars($p['permission_key']) ?>" data-name="<?= htmlspecialchars($p['permission_name']) ?>" data-module="<?= htmlspecialchars($p['module_name']) ?>"><i class="fas fa-edit"></i></a>
                                <form method="POST" class="d-inline" onsubmit="return confirm('Delete this permission? This will remove it from all roles.');">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= $p['id'] ?>">
                                    <button class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add/Edit Modal -->
<div class="modal fade" id="permModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="<?= $edit_perm ? 'edit' : 'add' ?>">
                <input type="hidden" name="id" value="<?= $edit_perm['id'] ?? 0 ?>">
                <div class="modal-header">
                    <h5 class="modal-title"><?= $edit_perm ? 'Edit Permission' : 'Add Permission' ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Module <span class="text-danger">*</span></label>
                        <select name="module_name" class="form-control" required>
                            <option value="">Select Module</option>
                            <?php foreach (['Dashboard', 'Products', 'Suppliers', 'Purchases', 'POS', 'Customers', 'Repairs', 'Warranty', 'Returns', 'Expenses', 'Payments', 'Reports', 'Users', 'Roles', 'Permissions', 'Settings'] as $m): ?>
                                <option value="<?= $m ?>" <?= ($edit_perm['module_name'] ?? '') === $m ? 'selected' : '' ?>><?= $m ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Permission Key <span class="text-danger">*</span></label>
                        <input type="text" name="permission_key" class="form-control" value="<?= htmlspecialchars($edit_perm['permission_key'] ?? '') ?>" required placeholder="e.g. dashboard_view">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Permission Name <span class="text-danger">*</span></label>
                        <input type="text" name="permission_name" class="form-control" value="<?= htmlspecialchars($edit_perm['permission_name'] ?? '') ?>" required placeholder="e.g. View Dashboard">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary"><?= $edit_perm ? 'Update' : 'Save' ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php if ($edit_perm): ?>
<script>
    new bootstrap.Modal(document.getElementById('permModal')).show();
</script>
<?php endif; ?>

<script>
$(document).ready(function() {
    $('#permissionsTable').DataTable({ pageLength: 25 });
    $('.edit-perm').click(function(e) {
        e.preventDefault();
        $('#permModal input[name="action"]').val('edit');
        $('#permModal input[name="id"]').val($(this).data('id'));
        $('#permModal input[name="permission_key"]').val($(this).data('key'));
        $('#permModal input[name="permission_name"]').val($(this).data('name'));
        $('#permModal select[name="module_name"]').val($(this).data('module'));
        $('#permModal .modal-title').text('Edit Permission');
        $('#permModal').modal('show');
    });
    $('#permModal').on('hidden.bs.modal', function() {
        $('#permModal input[name="action"]').val('add');
        $('#permModal input[name="id"]').val(0);
        $('#permModal input[name="permission_key"]').val('');
        $('#permModal input[name="permission_name"]').val('');
        $('#permModal select[name="module_name"]').val('');
        $('#permModal .modal-title').text('Add Permission');
    });
});
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
