<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\GroupModel;

class GroupController extends Controller
{
    public function list(){

        $data['getGroups'] = GroupModel::geGroups();
        return view("users.list", $data, compact("data"));
    }
    public function add(){

        return redirect()->back()->with('success', 'Grroup Creted Successfully');
    }
    public function insert(Request $request){
        {


            $validatedData = $request->validate([
                'full_name'   => 'required|string|max:255',
                'national_id' => 'required|string|unique:users,national_id',
                'user_code'   => 'required|string|max:50',
                'email'       => 'required|email|unique:users,Email',
                'phone'       => 'required|string|max:15',
                'address'     => 'nullable|string|max:255',
                'role_id'      => 'required|exists:roles_1,id',
                'password'    => 'required|string|min:8|',
            ]);

            try {
                // Start a transaction
                DB::beginTransaction();

                // Store the user
                $user = User::create([
                    'Username'    => $validatedData['full_name'],
                    'FullName'    => $validatedData['full_name'],
                    'National_ID' => $validatedData['national_id'],
                    'UserCode'    => $validatedData['user_code'],
                    'email'       => $validatedData['email'],
                    'Phone'       => $validatedData['phone'],
                    'Address'     => $validatedData['address'],
                    'Role_ID'     => (int) $validatedData['role_id'], // Assuming `role_id` is in the `users` table
                    'password'    => Hash::make($validatedData['password']),
                ]);


                if ($user) {
                    // Commit the transaction if the user was created
                    DB::commit();
                    return redirect('users/')->with('success', 'User added successfully!');
                } else {
                    // Rollback the transaction if the user was not created
                    DB::rollBack();
                    return redirect()->back()->with('error', 'Failed to create the user. Please try again.');
                }
            } catch (\Exception $e) {
                // Rollback in case of exception
                DB::rollBack();
                return redirect()->back()->with('error', 'An error occurred: ' . $e->getMessage());
            }
    }
}
}
