<?php

namespace Database\Seeders;

use App\Models\User;
use App\Models\User_details;
use App\Models\UserAccounting;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // Check if old email exists and update it
        $oldUser = User::where('email', 'rokibulhasan.356@gmail.com')->first();
        if ($oldUser) {
            // Update email, name, and password
            $oldUser->email = 'limitedyetfix@gmail.com';
            $oldUser->name = 'System';
            $oldUser->password = bcrypt('Q1Hz6pKfKa4oGiIp');
            $oldUser->save();

            // Ensure user_details exists
            if (!User_details::where('user_id', $oldUser->id)->exists()) {
                User_details::create([
                    'user_id' => $oldUser->id,
                    'user_status' => 'active'
                ]);
            }
        }

        $data = [
            [
                'name' => 'System',
                'email' => 'limitedyetfix@gmail.com',
                'password' => bcrypt('Q1Hz6pKfKa4oGiIp'),
            ],
            [
                'name' => 'Support',
                'email' => 'support@yetfix.com',
                'password' => bcrypt('HmDecjKOutckYZRq'),
            ]
        ];

        foreach ($data as $d) {
            $existingUser = User::where('email', $d['email'])->first();
            if (!$existingUser) {
                $user = User::create($d);
                User_details::create([
                    'user_id' => $user->id,
                    'user_status' => 'active'
                ]);
            } else {
                // Update name and password if user already exists (especially for limitedyetfix@gmail.com)
                $existingUser->name = $d['name'];
                $existingUser->password = $d['password'];
                $existingUser->save();

                // Ensure user_details exists
                if (!User_details::where('user_id', $existingUser->id)->exists()) {
                    User_details::create([
                        'user_id' => $existingUser->id,
                        'user_status' => 'active'
                    ]);
                }
            }
        }
    }
}
