<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddShopServicesViewPermission extends Migration
{
    public function up()
    {
        $perm = ['title' => 'Shop Services View', 'code' => 'shop_services_view'];
        $exists = $this->db->table('permissions')->where('code', $perm['code'])->countAllResults();
        if (!$exists) {
            $this->db->table('permissions')->insert($perm);
        }

        $roles = ['Admin', 'Shopkeeper'];
        foreach ($roles as $roleTitle) {
            $role = $this->db->table('roles')->select('id')->where('title', $roleTitle)->get()->getRow();
            if (!$role) {
                continue;
            }
            $rpExists = $this->db->table('role_permissions')->where(['role' => $role->id, 'permission' => $perm['code']])->countAllResults();
            if (!$rpExists) {
                $this->db->table('role_permissions')->insert(['role' => $role->id, 'permission' => $perm['code']]);
            }
        }
    }

    public function down()
    {
        $this->db->table('role_permissions')->where('permission', 'shop_services_view')->delete();
        $this->db->table('permissions')->where('code', 'shop_services_view')->delete();
    }
}

