<?php
include('../includes/config.php');

// 1. Get all permission slugs from database
$db_permissions = [];
$query = mysqli_query($con, "SELECT permission_slug FROM permissions");
if ($query) {
    while ($row = mysqli_fetch_array($query)) {
        $db_permissions[] = $row['permission_slug'];
    }
}

// 2. Define required permissions for new features
$required_permissions = [
    'manage_locations' => ['category' => 'System', 'description' => 'Manage Product Locations'],
    'manage_inventory' => ['category' => 'Products', 'description' => 'Manage Inventory Stock'],
    'manage_vendors' => ['category' => 'Vendors', 'description' => 'Manage Vendor Accounts'],
    'view_reports' => ['category' => 'Reports', 'description' => 'View System Reports']
];

// 3. Check for missing permissions and insert them
$missing_count = 0;
foreach ($required_permissions as $slug => $details) {
    if (!in_array($slug, $db_permissions)) {
        $cat = $details['category'];
        $desc = $details['description'];
        mysqli_query($con, "INSERT INTO permissions (permission_slug, category, description) VALUES ('$slug', '$cat', '$desc')");
        echo "Added permission: $slug\n";

        // Auto-grant to admin
        mysqli_query($con, "INSERT INTO role_permissions (role, permission_slug) VALUES ('admin', '$slug')");
        echo "Granted $slug to admin\n";

        $missing_count++;
    }
}

if ($missing_count == 0) {
    echo "Permissions are up to date.\n";
} else {
    echo "Successfully added $missing_count new permissions.\n";
}
?>
