<?php

class Migration_20240712000015_role_resources_tbl_update
{
    public static function up(PDO $pdo)
    {
        $sql = "
            DROP TABLE IF EXISTS role_resources;
        ";

        $pdo->exec($sql);

        $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),
                FOREIGN KEY(resource_id) REFERENCES resources(id),
                FOREIGN KEY(action_id) REFERENCES actions(id)
            );
        ";

        $pdo->exec($sql);

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

        foreach ($roles as $role) {
            if (isset($resources[$role])) {
                foreach ($resources[$role] 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);
    }

    public static function down(PDO $pdo)
    {
        $sql = "
            DROP TABLE IF EXISTS role_resources;
        ";

        $pdo->exec($sql);
    }
}
