<?php

namespace App\Http\Controllers;

use App\Models\EmployeeSetup;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Inertia\Inertia;
use Spatie\Permission\Models\Role;

class EmployeeSetupController extends Controller
{
    /**
     * Return employees where is_sr = true (for POS SR dropdown).
     */
    public function srEmployees()
    {
        $employees = EmployeeSetup::with('user')
            ->where('is_sr', true)
            ->orderBy('id', 'desc')
            ->get();

        return response()->json(['sr_employees' => $employees]);
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $employees = EmployeeSetup::with(['user', 'user.role'])->orderBy('created_at', 'desc')->get();
        $roles = Role::orderBy('name')->get();

        return Inertia::render('Employee/EmployeeSetup', [
            'employees' => $employees,
            'roles' => $roles,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        return DB::transaction(function () use ($request) {
            // Validate the request
            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'employee_id' => 'required|string|unique:employee_setups,employee_id|max:50',
                'designation' => 'required|string|max:255',
                'department' => 'required|string|max:255',
                'phone' => 'required|string|max:20',
                'email' => 'required|email|max:255|unique:users,email',
                'address' => 'nullable|string',
                'joining_date' => 'required|date',
                'basic_salary' => 'required|numeric|min:0',
                'is_sr' => 'nullable|boolean',
                // User account fields
                'password' => 'required|string|min:6',
                'role_id' => 'nullable|exists:roles,id',
                'status' => 'required|in:active,inactive',
            ]);

            // Create the user account first
            $user = User::create([
                'name' => $validated['name'],
                'email' => $validated['email'],
                'password' => Hash::make($validated['password']),
                'role_id' => $validated['role_id'] ?? 2,
                'status' => $validated['status'],
            ]);

            // Prepare employee data
            $employeeData = $validated;
            $employeeData['user_id'] = $user->id;
            $employeeData['created_by'] = auth()->id();

            // Remove user-specific fields
            unset($employeeData['name'], $employeeData['password'], $employeeData['role_id'], $employeeData['status'], $employeeData['email']);

            // Create employee record
            $employee = EmployeeSetup::create($employeeData);

            // Fetch updated employee list with user relation (same as index)
            $employees = EmployeeSetup::with(['user', 'user.role'])->orderBy('created_at', 'desc')->get();

            return response()->json([
                'success' => 'Employee and user account created successfully',
                'employees' => $employees,
            ]);
        });
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, EmployeeSetup $employeeSetup)
    {
        return DB::transaction(function () use ($request, $employeeSetup) {
            // Validate the request
            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'employee_id' => 'required|string|unique:employee_setups,employee_id,'.$employeeSetup->id.'|max:50',
                'designation' => 'required|string|max:255',
                'department' => 'required|string|max:255',
                'phone' => 'required|string|max:20',
                'email' => 'required|email|max:255|unique:users,email,'.$employeeSetup->user_id,
                'address' => 'nullable|string',
                'joining_date' => 'required|date',
                'basic_salary' => 'required|numeric|min:0',
                'password' => 'nullable|string|min:6',
                'is_sr' => 'nullable|boolean',
                // User account fields
                'role_id' => 'nullable|exists:roles,id',
                'status' => 'required|in:active,inactive',
            ]);

            // Update the user account
            $user = User::find($employeeSetup->user_id);
            if ($user) {
                $user->update([
                    'name' => $validated['name'],
                    'email' => $validated['email'],
                    'role_id' => $validated['role_id'] ?? 2,
                    'status' => $validated['status'],
                ]);
            }
            if (! empty($validated['password'])) {
                $user->update([
                    'password' => Hash::make($validated['password']),
                ]);
            }

            // Prepare employee data
            $employeeData = $validated;
            $employeeData['updated_by'] = auth()->id();

            // Remove user-specific fields
            unset($employeeData['name'], $employeeData['password'], $employeeData['role_id'], $employeeData['status'], $employeeData['email']);

            // Update employee record
            $employeeSetup->update($employeeData);

            // Fetch updated employee list with user relation (same as index)
            $employees = EmployeeSetup::with(['user', 'user.role'])->orderBy('created_at', 'desc')->get();

            return response()->json([
                'success' => 'Employee and user account updated successfully',
                'employees' => $employees,
            ]);
        });
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(EmployeeSetup $employeeSetup)
    {
        // Delete associated user account
        if ($employeeSetup->user_id) {
            $user = User::find($employeeSetup->user_id);
            if ($user) {
                $user->delete();
            }
        }

        $employeeSetup->delete();

        // Fetch updated employee list with user relation (same as index)
        $employees = EmployeeSetup::with(['user', 'user.role'])->orderBy('created_at', 'desc')->get();

        return response()->json([
            'success' => 'Employee deleted successfully',
            'employees' => $employees,
        ]);
    }
}
