<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddAlertesCatalogPermission extends Migration
{
    public function up()
    {
        $db = $this->db;

        $permission = [
            'name'        => 'Voir Alertes Catalog',
            'slug'        => 'alertes_catalog.voir',
            'description' => 'Accès à la zone Alertes Catalogue (superadmin uniquement)',
            'created_at'  => date('Y-m-d H:i:s'),
            'updated_at'  => date('Y-m-d H:i:s'),
        ];

        $existing = $db->table('permissions')
            ->where('slug', $permission['slug'])
            ->get()
            ->getRow();

        if ($existing) {
            return;
        }

        $db->table('permissions')->insert($permission);
        $permissionId = $db->insertID();

        $role = $db->table('roles')->where('slug', 'superadmin')->get()->getRow();

        if ($role && $permissionId) {
            $db->table('role_permissions')->insert([
                'role_id'       => $role->id,
                'permission_id' => $permissionId,
            ]);
        }
    }

    public function down()
    {
        $db = $this->db;

        $permission = $db->table('permissions')
            ->where('slug', 'alertes_catalog.voir')
            ->get()
            ->getRow();

        if ($permission) {
            $db->table('role_permissions')
                ->where('permission_id', $permission->id)
                ->delete();

            $db->table('permissions')
                ->where('id', $permission->id)
                ->delete();
        }
    }
}
