<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;

use App\Models\Roles2Model;
use App\Models\RoleModel;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\Hash;
use App\Models\PermissionsModel;
use App\Models\PermissionsUserModel;
class UserController extends Controller
{
    public function list(){
        $data['getUsers'] = User::getUsers();
        
        return view("users.list", $data, compact("data"));
    }
    public function add(){
        $data['getRole'] = Roles2Model::getRecords();
        return view("users.add", $data);

    }
    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_2,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());
            }
    }
}


    public function edit($id){
        $data['getUser'] = User::getUser($id);
        $data['getRole'] = Roles2Model::getRecords();
        return view("users.edit", $data);

    }
    public function update(Request $request, $id)
    {
        $validatedData = $request->validate([
            'full_name'   => 'required|string|max:255',
            'national_id' => 'required|string|unique:users,national_id,' . $id,
            'user_code'   => 'required|string|max:50',
            'email'       => 'required|email|unique:users,email,' . $id,
            'phone'       => 'required|string|max:15',
            'address'     => 'nullable|string|max:255',
            'role_id'     => 'required|exists:roles_2,id',
            'password'    => 'nullable|string|min:8',
        ]);

        try {
            $user = User::findOrFail($id);

            // Update user data
            $user->Username = $validatedData['full_name'];
            $user->FullName = $validatedData['full_name'];
            $user->National_ID = $validatedData['national_id'];
            $user->UserCode = $validatedData['user_code'];
            $user->email = $validatedData['email'];
            $user->Phone = $validatedData['phone'];
            $user->Address = $validatedData['address'];
            $user->Role_ID = (int) $validatedData['role_id'];

            // Update password if provided
            if (!empty($validatedData['password'])) {
                $user->password = Hash::make($validatedData['password']);
            }

            $user->save();

            return redirect('users/')->with('success', 'User updated successfully!');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'An error occurred: ' . $e->getMessage());
        }
    }


    public function addPermissions($id){
        $getPermissions = PermissionsModel::getRecords();
        $data['getPermissions'] = $getPermissions;
        $data["getUserPermissions"] = PermissionsUserModel::getUserPermissions($id);
        $data['getUser'] = User::getUser($id);

        return view("users.permissions", $data, compact("id"));



            }

    public function savePermissions($id, Request $request){

        $save = User::getUser($id);
        $save->Username = $request->username;
        $save->save();
        PermissionsUserModel::InsertUpdateRecord($request->permission_id, $save->id);
        return redirect('users/')->with('success', 'permissions for  updated Successfully');



    }
    public function delete($id)
    {
        try {
            $user = User::findOrFail($id);
            $user->delete();

            return redirect('users/role/')->with('success', 'Role deleted successfully!');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'An error occurred: ' . $e->getMessage());
        }
    }
    public function profile()
    {
        $user = Auth::user(); // Fetch the currently authenticated user
        return view('users.profile', compact('user'));
    }

    /**
     * Update the profile details.
     */
    public function updateProfile(Request $request)
    {
        $validatedData = $request->validate([
            'full_name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email,' . Auth::id(),
            'phone' => 'nullable|string|max:15',
            'address' => 'nullable|string|max:255',
        ]);

        try {
            $user = Auth::user();
            $user->FullName = $validatedData['full_name'];
            $user->email = $validatedData['email'];
            $user->Phone = $validatedData['phone'];
            $user->Address = $validatedData['address'];
            $user->save();

            return redirect()->back()->with('success', 'Profile updated successfully!');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'An error occurred: ' . $e->getMessage());
        }
    }

    /**
     * Change the user password.
     */
    public function changePassword(Request $request)
    {
        $validatedData = $request->validate([
            'current_password' => 'required|string',
            'new_password' => 'required|string|min:8|confirmed',
        ]);

        try {
            $user = Auth::user();
            // Check current password
            if (Hash::check($validatedData['current_password'], $user->password)== false) {
                return redirect()->back()->with('error', 'Current password is incorrect.');
            }

            // Update the password
            $user->password = Hash::make($validatedData['new_password']);
            $user->save();

            return redirect()->back()->with('success', 'password changed successfully!');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'An error occurred: ' . $e->getMessage());
        }
    }


}
