<?php
require __DIR__ . '/../config/bootstrap.php';

use App\Core\Database;

$db = Database::getInstance();

$options = getopt('', ['conference_id::', 'org_id::', 'apply']);

$conferenceId = isset($options['conference_id']) ? (int)$options['conference_id'] : 0;
$orgId = isset($options['org_id']) ? (int)$options['org_id'] : 0;
$apply = array_key_exists('apply', $options);

function out($msg) {
    echo $msg . PHP_EOL;
}

function table_exists(PDO $db, string $table): bool {
    try {
        $stmt = $db->prepare("SHOW TABLES LIKE ?");
        $stmt->execute([$table]);
        return (bool)$stmt->fetchColumn();
    } catch (Throwable $e) {
        return false;
    }
}

if ($conferenceId <= 0) {
    $conferenceId = (int)$db->query("SELECT id FROM conferences ORDER BY id LIMIT 1")->fetchColumn();
}

$stmt = $db->prepare("SELECT id, org_id, short_name FROM conferences WHERE id=? LIMIT 1");
$stmt->execute([$conferenceId]);
$conference = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$conference) {
    exit("Conference not found.\n");
}

if ($orgId <= 0) {
    $orgId = (int)$conference['org_id'];
}

out("Pack509 Permission Healer");
out("Conference: {$conferenceId} {$conference['short_name']} | Org: {$orgId} | Apply: " . ($apply ? 'YES' : 'NO'));
out("");

$rules = [
    '/easychair/admin/dashboard' => [
        'label' => 'Dashboard',
        'roles' => ['super_admin','org_admin','admin','organizer','conference_chair','track_chair','section_editor'],
        'crud' => ['view'=>1,'create'=>0,'update'=>0,'delete'=>0],
        'icon' => 'fa-gauge-high',
        'module' => 'core',
        'sort' => 1,
    ],

    '/easychair/admin/branding' => [
        'label' => 'Branding & Logos',
        'roles' => ['super_admin','org_admin','admin','organizer','conference_chair'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>0],
        'icon' => 'fa-image',
        'module' => 'homepage',
        'sort' => 110,
    ],

    '/easychair/admin/conference-home' => [
        'label' => 'Smart Homepage',
        'roles' => ['super_admin','org_admin','admin','organizer','conference_chair'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>0],
        'icon' => 'fa-palette',
        'module' => 'homepage',
        'sort' => 109,
    ],

    '/easychair/admin/committee-images' => [
        'label' => 'Committee & Participant Images',
        'roles' => ['super_admin','org_admin','admin','organizer','conference_chair'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>1],
        'icon' => 'fa-images',
        'module' => 'homepage',
        'sort' => 111,
    ],

    '/easychair/admin/conference-business' => [
        'label' => 'Conference Business',
        'roles' => ['super_admin','org_admin','admin','organizer','conference_chair'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>0],
        'icon' => 'fa-calendar-days',
        'module' => 'conference',
        'sort' => 120,
    ],

    '/easychair/admin/submissions' => [
        'label' => 'Submissions',
        'roles' => ['super_admin','org_admin','admin','conference_chair','track_chair','section_editor'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>0],
        'icon' => 'fa-inbox',
        'module' => 'submissions',
        'sort' => 40,
    ],

    '/easychair/admin/submission-search' => [
        'label' => 'Submission Search',
        'roles' => ['super_admin','org_admin','admin','conference_chair','track_chair','section_editor'],
        'crud' => ['view'=>1,'create'=>0,'update'=>0,'delete'=>0],
        'icon' => 'fa-magnifying-glass',
        'module' => 'submissions',
        'sort' => 39,
    ],

    '/easychair/admin/reviewer-assignments' => [
        'label' => 'Reviewer Assignment',
        'roles' => ['super_admin','org_admin','admin','conference_chair','track_chair','section_editor'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>1],
        'icon' => 'fa-user-plus',
        'module' => 'reviews',
        'sort' => 52,
    ],

    '/easychair/admin/reviewers' => [
        'label' => 'Reviewers',
        'roles' => ['super_admin','org_admin','admin','conference_chair','track_chair'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>0],
        'icon' => 'fa-user-check',
        'module' => 'reviews',
        'sort' => 53,
    ],

    '/easychair/admin/reviewer-expertise' => [
        'label' => 'Reviewer Expertise',
        'roles' => ['super_admin','org_admin','admin','conference_chair','track_chair'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>0],
        'icon' => 'fa-brain',
        'module' => 'reviews',
        'sort' => 54,
    ],

    '/easychair/admin/review-form' => [
        'label' => 'Review Form',
        'roles' => ['super_admin','org_admin','admin','conference_chair'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>1],
        'icon' => 'fa-clipboard-list',
        'module' => 'reviews',
        'sort' => 55,
    ],

    '/easychair/admin/review-monitor' => [
        'label' => 'Review Monitor',
        'roles' => ['super_admin','org_admin','admin','conference_chair','track_chair'],
        'crud' => ['view'=>1,'create'=>0,'update'=>0,'delete'=>0],
        'icon' => 'fa-chart-line',
        'module' => 'reviews',
        'sort' => 56,
    ],

    '/easychair/admin/decisions' => [
        'label' => 'Decisions',
        'roles' => ['super_admin','org_admin','admin','conference_chair'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>0],
        'icon' => 'fa-gavel',
        'module' => 'decisions',
        'sort' => 60,
    ],

    '/easychair/admin/workflow' => [
        'label' => 'Workflow',
        'roles' => ['super_admin','org_admin','admin','conference_chair'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>0],
        'icon' => 'fa-diagram-project',
        'module' => 'workflow',
        'sort' => 70,
    ],

    '/easychair/admin/submission-stage-rules' => [
        'label' => 'Submission Stage Rules',
        'roles' => ['super_admin','org_admin','admin','conference_chair'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>1],
        'icon' => 'fa-list-ol',
        'module' => 'workflow',
        'sort' => 72,
    ],

    '/easychair/admin/workflow-notifications' => [
        'label' => 'Workflow Notifications',
        'roles' => ['super_admin','org_admin','admin','conference_chair'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>0],
        'icon' => 'fa-bell',
        'module' => 'workflow',
        'sort' => 73,
    ],

    '/easychair/admin/production' => [
        'label' => 'Production / Camera-ready',
        'roles' => ['super_admin','org_admin','admin','organizer','conference_chair'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>0],
        'icon' => 'fa-industry',
        'module' => 'production',
        'sort' => 130,
    ],

    '/easychair/admin/issues' => [
        'label' => 'Issues / Proceedings',
        'roles' => ['super_admin','org_admin','admin','organizer','conference_chair'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>0],
        'icon' => 'fa-book',
        'module' => 'production',
        'sort' => 131,
    ],

    '/easychair/admin/certificates' => [
        'label' => 'Certificates',
        'roles' => ['super_admin','org_admin','admin','organizer','conference_chair'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>0],
        'icon' => 'fa-certificate',
        'module' => 'certificates',
        'sort' => 140,
    ],

    '/easychair/admin/conference-mail' => [
        'label' => 'Conference Mail',
        'roles' => ['super_admin','org_admin','admin','conference_chair'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>0],
        'icon' => 'fa-envelope-circle-check',
        'module' => 'mail',
        'sort' => 90,
    ],

    '/easychair/admin/email-templates' => [
        'label' => 'Email Templates',
        'roles' => ['super_admin','org_admin','admin','conference_chair'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>0],
        'icon' => 'fa-envelope-open-text',
        'module' => 'mail',
        'sort' => 91,
    ],

    '/easychair/admin/org-smtp' => [
        'label' => 'Organization SMTP',
        'roles' => ['super_admin','org_admin','admin'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>0],
        'icon' => 'fa-server',
        'module' => 'mail',
        'sort' => 92,
    ],

    '/easychair/admin/test-email' => [
        'label' => 'Test Email',
        'roles' => ['super_admin','org_admin','admin'],
        'crud' => ['view'=>1,'create'=>1,'update'=>0,'delete'=>0],
        'icon' => 'fa-paper-plane',
        'module' => 'mail',
        'sort' => 93,
    ],

    '/easychair/admin/conference-role-permissions' => [
        'label' => 'Conference Role Permissions',
        'roles' => ['super_admin','org_admin','admin'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>0],
        'icon' => 'fa-user-lock',
        'module' => 'rbac',
        'sort' => 996,
    ],

    '/easychair/admin/conference-business-permissions' => [
        'label' => 'Conference Business Permissions',
        'roles' => ['super_admin','org_admin','admin'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>1],
        'icon' => 'fa-shield-halved',
        'module' => 'rbac',
        'sort' => 997,
    ],

    '/easychair/admin/custom-rights' => [
        'label' => 'Custom Rights',
        'roles' => ['super_admin'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>1],
        'icon' => 'fa-key',
        'module' => 'rbac',
        'sort' => 998,
    ],

    '/easychair/admin/rbac-scope' => [
        'label' => 'RBAC Scope Manager',
        'roles' => ['super_admin','org_admin','admin'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>0],
        'icon' => 'fa-copy',
        'module' => 'rbac',
        'sort' => 999,
    ],

    '/easychair/admin/rbac-matrix' => [
        'label' => 'RBAC Matrix',
        'roles' => ['super_admin'],
        'crud' => ['view'=>1,'create'=>1,'update'=>1,'delete'=>1],
        'icon' => 'fa-sliders',
        'module' => 'rbac',
        'sort' => 1000,
    ],
];

$roleIds = [];
foreach ($db->query("SELECT id, code FROM roles")->fetchAll(PDO::FETCH_ASSOC) as $r) {
    $roleIds[$r['code']] = (int)$r['id'];
}

$menuStmt = $db->prepare("
    INSERT INTO rbac_menu_items
    (menu_key, label, label_ar, i18n_key, url, icon, module_key, sort_order, is_active)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)
    ON DUPLICATE KEY UPDATE
        label=VALUES(label),
        icon=VALUES(icon),
        module_key=VALUES(module_key),
        sort_order=VALUES(sort_order),
        is_active=1
");

$findMenu = $db->prepare("SELECT id FROM rbac_menu_items WHERE url=? ORDER BY id LIMIT 1");

$upsert = $db->prepare("
    INSERT INTO rbac_role_menu_permissions
    (org_id, conference_id, role_id, menu_item_id, is_allowed, can_view, can_create, can_update, can_delete, updated_by)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)
    ON DUPLICATE KEY UPDATE
        is_allowed=VALUES(is_allowed),
        can_view=VALUES(can_view),
        can_create=VALUES(can_create),
        can_update=VALUES(can_update),
        can_delete=VALUES(can_delete),
        updated_at=NOW()
");

$db->beginTransaction();

try {
    foreach ($rules as $url => $rule) {
        $menuKey = 'auto_' . preg_replace('/[^a-z0-9]+/', '_', strtolower(trim(str_replace('/easychair/admin/', '', $url), '/')));
        $i18nKey = 'menu.' . preg_replace('/[^a-z0-9]+/', '_', strtolower($rule['label']));

        $menuStmt->execute([
            $menuKey,
            $rule['label'],
            $rule['label'],
            $i18nKey,
            $url,
            $rule['icon'],
            $rule['module'],
            $rule['sort'],
        ]);

        $findMenu->execute([$url]);
        $menuId = (int)$findMenu->fetchColumn();

        if ($menuId <= 0) {
            continue;
        }

        foreach ($roleIds as $roleCode => $roleId) {
            $allow = in_array($roleCode, $rule['roles'], true) ? 1 : 0;

            $canView = $allow ? (int)$rule['crud']['view'] : 0;
            $canCreate = $allow ? (int)$rule['crud']['create'] : 0;
            $canUpdate = $allow ? (int)$rule['crud']['update'] : 0;
            $canDelete = $allow ? (int)$rule['crud']['delete'] : 0;

            if ($roleCode === 'super_admin') {
                $allow = 1;
                $canView = 1;
                $canCreate = 1;
                $canUpdate = 1;
                $canDelete = 1;
            }

            $upsert->execute([
                $orgId,
                $conferenceId,
                $roleId,
                $menuId,
                $allow,
                $canView,
                $canCreate,
                $canUpdate,
                $canDelete,
            ]);

            out(str_pad($roleCode, 18) . str_pad($allow ? 'ALLOW' : 'DENY', 8) . $url);
        }
    }

    $db->commit();
    out("");
    out("Done.");
} catch (Throwable $e) {
    $db->rollBack();
    out("FAILED: " . $e->getMessage());
    exit(1);
}
