<?php

namespace App\Http\Controllers;

use App\Models\UserMaster;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;

class UserMasterController extends Controller
{
    /* ================= LIST USERS ================= */
    public function index(Request $request)
    {
        try {
            $users = UserMaster::with(['role', 'department'])
                ->when($request->search, fn ($q) =>
                    $q->search($request->search)
                )
                ->when($request->role_id, fn ($q) =>
                    $q->where('Usr_Role_Id', $request->role_id)
                )
                ->when(!is_null($request->is_active), fn ($q) =>
                    $q->where('is_active', (bool)$request->is_active)
                )
                ->orderByDesc('Usr_Id')
                ->paginate($request->get('per_page', 25));

            return response()->json([
                'success' => true,
                'message' => 'Users fetched successfully',
                'data'    => $users->items(),
                'meta'    => [
                    'current_page' => $users->currentPage(),
                    'per_page'     => $users->perPage(),
                    'total'        => $users->total(),
                    'last_page'    => $users->lastPage()
                ]
            ], 200);

        } catch (\Throwable $e) {
            Log::error('USER_MASTER_INDEX_FAILED', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Unable to fetch users'
            ], 500);
        }
    }

    /* ================= LIST ALL USERS ================= */
    public function getAllUsers()
    {
        try {
            $users = UserMaster::with(['role', 'department'])->get();

            return response()->json([
                'success' => true,
                'message' => 'All users fetched successfully',
                'data'    => $users
            ], 200);

        } catch (\Throwable $e) {
            Log::error('USER_MASTER_LIST_ALL_FAILED', [
                'error' => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch users'
            ], 500);
        }
    }

    /* ================= CREATE USER ================= */
  /* ================= CREATE USER ================= */
public function store(Request $request)
{
    try {
        // Fix: Add proper validation for all required fields
        $validated = $request->validate([
            'Usr_Name'   => 'required|string|max:50',
            'Usr_Email'  => 'nullable|email|unique:user_master,Usr_Email|max:100',
            'Usr_Mobile' => 'nullable|unique:user_master,Usr_Mobile|max:15',
            'Usr_Pas'    => 'required|min:6|confirmed',
            'Usr_Pas_confirmation' => 'required_with:Usr_Pas',
            'Usr_Role_Id'=> 'nullable|exists:role_master,Role_Id',
            'Usr_Dpt_Id' => 'nullable|exists:dept_master,Dpt_Id' // Assuming department table exists
        ]);

        // Fix: Create user with proper default values
        $user = UserMaster::create([
            'Usr_Name'   => $validated['Usr_Name'],
            'Usr_Email'  => $validated['Usr_Email'] ?? null,
            'Usr_Mobile' => $validated['Usr_Mobile'] ?? null,
            'Usr_Pas'    => $validated['Usr_Pas'],
            'Usr_Role_Id'=> $validated['Usr_Role_Id'] ?? null,
            'Usr_Dpt_Id' => $validated['Usr_Dpt_Id'] ?? null,
            'is_active'  => 1,
            'is_locked'   => 0,  // Changed from is_locked
            'failed_loginattempts' => 0,  // Changed from failed_login_attempts
            'session_timeout' => 30,
            'password_expiry_days' => 90,
            'created_at' => now(),
            'updated_at' => now()
        ]);

        return response()->json([
            'success' => true,
            'message' => 'User created successfully',
            'data'    => $user
        ], 201);

    } catch (ValidationException $e) {
        return response()->json([
            'success' => false,
            'errors'  => $e->errors(),
            'message' => 'Validation failed'
        ], 422);

    } catch (\Throwable $e) {
        Log::error('USER_MASTER_CREATE_FAILED', [
            'payload' => $request->all(),
            'error'   => $e->getMessage(),
            'trace'   => $e->getTraceAsString() // Add trace for debugging
        ]);

        return response()->json([
            'success' => false,
            'message' => 'User creation failed: ' . $e->getMessage() // Show error for debugging
        ], 500);
    }
}

    /* ================= SHOW USER ================= */
    public function show($id)
    {
        try {
            $user = UserMaster::with(['role', 'department'])->findOrFail($id);

            return response()->json([
                'success' => true,
                'data'    => $user
            ], 200);

        } catch (\Throwable $e) {
            return response()->json([
                'success' => false,
                'message' => 'User not found'
            ], 404);
        }
    }

    /* ================= UPDATE USER ================= */
    public function update(Request $request, $id)
    {
        try {
            $user = UserMaster::findOrFail($id);

            $validated = $request->validate([
                'Usr_Name'   => 'required|unique:user_master,Usr_Name,' . $id . ',Usr_Id',
                'Usr_Email'  => 'required|email|unique:user_master,Usr_Email,' . $id . ',Usr_Id',
                'Usr_Mobile' => 'required|unique:user_master,Usr_Mobile,' . $id . ',Usr_Id',
                'Usr_Role_Id'=> 'nullable|exists:role_master,Role_Id',
                'Usr_Dpt_Id' => 'nullable',
                'is_active'  => 'boolean'
            ]);

            $user->update($validated);

            return response()->json([
                'success' => true,
                'message' => 'User updated successfully',
                'data'    => $user
            ], 200);

        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'errors'  => $e->errors()
            ], 422);

        } catch (\Throwable $e) {
            Log::error('USER_MASTER_UPDATE_FAILED', [
                'user_id' => $id,
                'error'   => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'message' => 'User update failed'
            ], 500);
        }
    }

    /* ================= DELETE USER ================= */
    public function destroy($id)
    {
        try {
            $user = UserMaster::findOrFail($id);
            $user->delete();

            return response()->json([
                'success' => true,
                'message' => 'User deleted successfully'
            ], 200);

        } catch (\Throwable $e) {
            return response()->json([
                'success' => false,
                'message' => 'User not found'
            ], 404);
        }
    }

    /* ================= RESTORE USER ================= */
    public function restore($id)
    {
        try {
            $user = UserMaster::withTrashed()->findOrFail($id);
            $user->restore();

            return response()->json([
                'success' => true,
                'message' => 'User restored successfully'
            ], 200);

        } catch (\Throwable $e) {
            return response()->json([
                'success' => false,
                'message' => 'Restore failed'
            ], 500);
        }
    }
}
