<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Permission;

class MarketedBy extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $data = [
            [
                'permission_name' => 'customer-marketed-by',
                'role_name' => [
                    'Admin',
                    'Accounts Manager',
                    'Accounts Executive',
                    'Accounts',
                    'Asst. Manager',
                    'Marketing Manager',
                    'Super Admin',
                    'POP Incharge',
                    'Marketing Executive'
                ],
            ]
        ];

        foreach ($data as $value) {
            $permission = Permission::where('name', $value['permission_name'])->first();
            if ($permission) {
                foreach ($value['role_name'] as $name) {

                    $role = DB::table('roles')->where('name', $name)->first();

                    if(!$role){
                        DB::insert('insert into roles (name,guard_name) values (?,?)', [$name, 'web']);
                        $role = DB::table('roles')->where('name', $name)->first();
                    }

                    if ($role) {
                        $role_permissions = DB::table('role_has_permissions')->where('permission_id', $permission->id)->where('role_id', $role->id)->first();
                        if (!$role_permissions) {
                            DB::table('role_has_permissions')->insert([
                                'permission_id' => $permission->id,
                                'role_id' => $role->id,
                            ]);
                        }
                    }
                }
            }
        }
    }
}
