<?php

namespace Database\Seeders;

use App\Models\Company;
use App\Models\Role;
use Illuminate\Database\Seeder;
use App\Models\User;
use App\Scopes\CompanyScope;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */

    public function run()
    {
        Model::unguard();


        DB::table('users')->delete();
        DB::table('role_user')->delete();

        DB::statement('ALTER TABLE users AUTO_INCREMENT = 1');
        DB::statement('ALTER TABLE role_user AUTO_INCREMENT = 1');

        $count = env('SEED_RECORD_COUNT', 30);

        $company = Company::with(['currency' => function ($query) {
            return $query->withoutGlobalScope(CompanyScope::class);
        }, 'subscriptionPlan'])->where('is_global', 0)->first();

        // Admin User
        $adminRole = Role::where('company_id', $company->id)->where('name', 'admin')->first();

        $user = new User();
        $user->company_id = $company->id;
        $user->name = 'Admin';
        $user->email = 'admin@example.com';
        $user->password = '12345678';
        $user->role_id = $adminRole->id;
        $user->user_type = "staff_members";
        $user->save();

        $user->attachRole($adminRole->id);

        $company->admin_id = $user->id;
        $company->save();

        // Website Manager User
        $websiteManagerRole = Role::where('company_id', $company->id)->where('name', 'website_manager')->first();

        $websiteManager = new User();
        $websiteManager->company_id = $company->id;
        $websiteManager->name = 'Website Manager';
        $websiteManager->email = 'manager@example.com';
        $websiteManager->password = '12345678';
        $websiteManager->role_id = $websiteManagerRole->id;
        $websiteManager->user_type = "staff_members";
        $websiteManager->save();

        $websiteManager->attachRole($websiteManagerRole->id);

        // Content Editor User
        $contentEditorRole = Role::where('company_id', $company->id)->where('name', 'content_editor')->first();

        $contentEditor = new User();
        $contentEditor->company_id = $company->id;
        $contentEditor->name = 'Content Editor';
        $contentEditor->email = 'editor@example.com';
        $contentEditor->password = '12345678';
        $contentEditor->role_id = $contentEditorRole->id;
        $contentEditor->user_type = "staff_members";
        $contentEditor->save();

        $contentEditor->attachRole($contentEditorRole->id);
    }
}
