<?php

class Migration_20250207170704_hide_myroles_global
{
    public static function up(PDO $pdo)
    {
        $pdo->exec('DELETE FROM role_resources WHERE resource_id = 6;');
    }

    public static function down(PDO $pdo)
    {
        $pdo->exec("SET FOREIGN_KEY_CHECKS = 0;");

        $pdo->exec("DROP TABLE IF EXISTS role_resources;");

        $pdo->exec("SET FOREIGN_KEY_CHECKS = 1;");

        $sql = "
            CREATE TABLE IF NOT EXISTS role_resources (
                role_id INT NOT NULL,
                resource_id INT NOT NULL,
                action_id INT NOT NULL,
                PRIMARY KEY(role_id, resource_id, action_id),
                FOREIGN KEY(role_id) REFERENCES roles(id) ON DELETE CASCADE,
                FOREIGN KEY(resource_id) REFERENCES resources(id) ON DELETE CASCADE,
                FOREIGN KEY(action_id) REFERENCES actions(id) ON DELETE CASCADE
            );
        ";
        $pdo->exec($sql);

        $roles = [
            'super_admin' => ['admin_panel', 'admin_setup', 'dashboard', 'my_iis', 'my_properties', 'property_builder', 'integrations', 'my_roles', 'users', 'visitors', 'command_center', 'events', 'settings'],
            'admin' => ['dealer_setup', 'dashboard', 'my_iis', 'my_properties', 'property_builder', 'integrations', 'my_roles', 'users', 'visitors', 'command_center', 'events', 'settings'],
            'dealer' => ['dashboard', 'my_iis', 'my_properties', 'property_builder', 'integrations', 'my_roles', 'users', 'visitors', 'command_center', 'events', 'settings'],
            'sub_dealer' => ['dashboard', 'my_iis', 'my_properties', 'property_builder', 'integrations', 'my_roles', 'users', 'visitors', 'command_center', 'events', 'settings'],
            'organization admin' => ['dashboard', 'my_iis', 'my_properties', 'property_builder', 'integrations', 'my_roles', 'users', 'visitors', 'command_center', 'events', 'settings'],
            'property admin' => ['dashboard', 'my_iis', 'property_builder', 'integrations', 'my_roles', 'users', 'visitors', 'command_center', 'events', 'settings'],
            'user' => ['dashboard', 'visitors', 'command_center', 'events']
        ];
        $actions = ['read', 'write'];
        $sql = '';

        foreach ($roles as $role => $resources) {
            foreach ($resources as $resource) {
                foreach ($actions as $action) {
                    $sql .= "
                        INSERT INTO role_resources (role_id, resource_id, action_id)
                        VALUES (
                            (SELECT id FROM roles WHERE name = '$role'),
                            (SELECT id FROM resources WHERE name = '$resource'),
                            (SELECT id FROM actions WHERE name = '$action')
                        );\n";
                }
            }
        }
        $pdo->exec($sql);
    }
}