<?php
/**
 * Add reports.expiry permission to manager roles
 */

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/config/database.php';

echo "Adding reports.expiry permission to manager roles...\n";

// Get the permission ID
$stmt = db()->prepare("SELECT id FROM permissions WHERE name = ?");
$stmt->execute(['reports.expiry']);
$perm = $stmt->fetch();

if (!$perm) {
    echo "❌ Permission 'reports.expiry' not found\n";
    exit(1);
}

echo "Found permission ID: {$perm['id']}\n";

// Get all manager roles
$stmt = db()->query("SELECT id, tenant_id FROM roles WHERE name = 'Manager'");
$managerRoles = $stmt->fetchAll();

echo "Found " . count($managerRoles) . " manager roles\n";

if (empty($managerRoles)) {
    echo "No manager roles found\n";
    exit(0);
}

$added = 0;
foreach ($managerRoles as $role) {
    // Check if already has permission
    $checkStmt = db()->prepare("SELECT COUNT(*) FROM role_permissions WHERE role_id = ? AND permission_id = ?");
    $checkStmt->execute([$role['id'], $perm['id']]);
    
    if ($checkStmt->fetchColumn() == 0) {
        // Add permission
        $insertStmt = db()->prepare("INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)");
        $insertStmt->execute([$role['id'], $perm['id']]);
        $added++;
        echo "Added to Manager role ID {$role['id']} (Tenant {$role['tenant_id']})\n";
    }
}

echo "✅ Added reports.expiry permission to $added manager roles\n";
echo "Manager roles can now access expiry reports\n";