<?php

namespace App\Modules\Hr\controllers\api\v1;

use Illuminate\Support\Facades\Response;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;
use App\Modules\Hr\UserDetails;

class UserDetailsControllerREST extends BaseController
{
    public function index(Request $request)
    {
        // Use the original Laravel 5 logic with RIGHT JOIN
        $query = UserDetails::join('users', 'users.id', '=', 'hr_user_details.user_id', 'right')
            ->where('users.active', 1)
            ->select('hr_user_details.*', 'users.id')
            ->orderBy('users.first_name');

        // Fetch the latest time log for each user
        $query->with('latest_time_log', 'user', 'pending_change_requests');

        if (!Auth::user()->hasPermission('access_hr')) {
            $user = auth()->user();
            $query->where('user_id', $user->id);
        }

        // Paginate the results
        $userDetails = $query->paginate($request->input('limit', 50));

        // Intelligently create the users_details entries that are missing
        $reload = false;
        foreach ($userDetails as $user) {
            if (!$user->user_id) {
                $details = UserDetails::create(['user_id' => $user->id]);
                $reload = true;
            }
        }

        // Prepare the response
        $response = [
            'data'         => $userDetails->getCollection()->toArray(),
            'reload'       => $reload,
            'total'        => $userDetails->total(),
            'current_page' => $userDetails->currentPage(),
            'last_page'    => $userDetails->lastPage(),
            'per_page'     => $userDetails->perPage(),
            'from'         => $userDetails->firstItem(),
            'to'           => $userDetails->lastItem(),
        ];

        return $response;
    }

    public function show($user_id)
    {
        // $user = auth()->user();
        // if ($user_id != $user->id || Auth::user()->hasPermission('access_hr')) {
        //     abort(403, 'Unauthorized action.');
        // }

        $query = UserDetails::join('users', 'users.id', '=', 'hr_user_details.user_id', 'right')
            ->where('users.id', $user_id)
            ->select('*', 'users.id')
            ->orderBy('users.first_name');
        // ->join('profile_photos', 'users.id', '=', 'profile_photos.user_id', 'right');
        $user = $query->first();
        $user->password = null;
        $user->remember_token = null;
        return $user;
    }

    public function update(Request $request, $user_id)
    {
        $user = auth()->user();
        if ($user_id != $user->id && !Auth::user()->hasPermission('access_hr')) {
            abort(403, 'Unauthorized action.');
        }

        $user_details = UserDetails::findOrFail($user_id);
        $user_details->fill($request->all());

        $user = User::findOrFail($user_id);
        $user->fill($request->all());

        if (!$user_details->save()) {
            return Response::json(['errors' => $user_details->errors->all()], 400);
        }
        if (!$user->save()) {
            return Response::json(['errors' => $user->errors->all()], 400);
        }
        return $user_details;
    }
}
