<?php

namespace App\Http\Controllers;
use App\Enums\RecordStatusEnum;
use App\Enums\UtilEnum;
use App\Http\Controllers\Helper\GlobalController;
use App\Models\AgeGroup;
use App\Models\BaseModel;
use App\Models\Department;
use App\Models\PatientType;
use App\Models\Role;
use App\Models\SampleSource;
use App\Models\User;
use App\Models\UserLabCover;
use App\Models\WardTransaction;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\Laboratory;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Log;

class UserController extends Controller
{

    protected $userModel;
    protected $roleModel;
    protected $userLabCover;
    protected $sampleSourceModel;
    protected $baseLabId;
    protected $labs;
    protected $base;

    public function __construct(User $userModel, Role $roleModel, UserLabCover $userLabCover, SampleSource $sampleSourceModel){
        $this->userModel = $userModel;
        $this->roleModel = $roleModel;
        $this->userLabCover = $userLabCover;
        $this->sampleSourceModel = $sampleSourceModel;
        $this->baseLabId = Session::get('base_lab_id');
        $this->base = Session::get('base_lab');
    }

    public function index(Request $request){
        if(!GlobalController::user_can(Auth::user()->role_id, ['view_user_account'])) return redirect(url('my-profile'));
        $this->labs = parent::getAccessAbleLabs();
        $recordStatusCondition = Auth::id()==1 ? [RecordStatusEnum::DELETE, RecordStatusEnum::ACTIVE] : [RecordStatusEnum::ACTIVE];
        $roles = $this->roleModel::query()->where(BaseModel::RECORD_STATUS_FIELD, RecordStatusEnum::ACTIVE)
            ->when(Auth::user()->role_id != UtilEnum::ADMINISTRATOR_ROLE , function ($roles){
                $roles->whereNotIn('id', [UtilEnum::ADMINISTRATOR_ROLE]);
            })->get();

        $sample_sources = $this->sampleSourceModel::query()->where(BaseModel::RECORD_STATUS_FIELD, RecordStatusEnum::ACTIVE)
            ->when(Auth::user()->role_id != UtilEnum::PHYSICIAN_ROLE && Auth::id()!=1 , function ($sampleSource){
                $sampleSource->where('lab_id', Session::get('base_lab_id'));
            })->get();

        $users = $this->userModel::with(['role','lab_covers'])->whereIn(BaseModel::RECORD_STATUS_FIELD, $recordStatusCondition)
            ->when(Auth::id()!=1, function ($users){
                $users->whereNotIn('id', [UtilEnum::ADMINISTRATOR_USER])
                    ->whereIn('id', $this->labs->pluck('userLabCovers')->flatten()->pluck('user_id')->toArray());
            })->when(!empty($request->kword), function($users) use ($request) {
                $keyword = '%' . str_replace(' ', '', $request->kword) . '%';
                $users->where(function ($q) use ($keyword) {
                    $q->whereRaw("REPLACE(name,' ','') LIKE ?", [$keyword])
                        ->orWhereRaw("REPLACE(email,' ','') LIKE ?", [$keyword]);
                })->where('id', '!=', UtilEnum::ADMINISTRATOR_USER);
            })
            ->orderBy(BaseModel::CREATED_AT,'desc')->paginate(config('labis.pagination.perpage', 10));
        return view('user_account', ['users' => $users, 'roles' => $roles, 'labs' => $this->labs, 'sample_sources' => $sample_sources]);
    }

    public function labUsers(Request $request){
        if(!GlobalController::user_can(Auth::user()->role_id, ['view_user_account'])) return redirect(url('my-profile'));
        $this->labs = parent::getAccessAbleLabs();
        $roles = $this->roleModel::query()->where(BaseModel::RECORD_STATUS_FIELD, RecordStatusEnum::ACTIVE)
            ->whereNotIn('id', [UtilEnum::ADMINISTRATOR_ROLE])->get();
        $sample_sources = $this->sampleSourceModel::query()->where(BaseModel::RECORD_STATUS_FIELD, RecordStatusEnum::ACTIVE)
                                ->where('lab_id', Session::get('base_lab_id'))->get();

        $users = $this->userModel::with(['role','lab_covers'])->where(BaseModel::RECORD_STATUS_FIELD, RecordStatusEnum::ACTIVE)
            ->whereIn('id', $this->labs->pluck('labUsers')->flatten()->pluck('user_id')->toArray())
            ->whereNotIn('role_id', [UtilEnum::ADMINISTRATOR_ROLE])
            ->when(!empty($request->kword), function($users) use ($request) {
                $users->whereRaw("replace(name, ' ','') like '%".str_replace(" ","",$request->kword)."%'")
                    ->orWhereRaw("replace(email, ' ','') like '%".str_replace(" ","",$request->kword)."%'");
            })->orderBy(BaseModel::CREATED_AT,'desc')->paginate(config('labis.pagination.perpage', 10));
        return view('user_account', ['users' => $users, 'roles' => $roles, 'labs' => $this->labs, 'sample_sources' => $sample_sources]);
    }

    public function save(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['create_user_account'])) return false;
            $validator = \Validator::make($request->all(), [
                'name' => 'required',
                'email' => 'required|email|unique:users',
                'password' => 'required',
                'role_id' => 'required',
                'sample_source_id' => 'nullable'
            ]);
            if ($validator->fails()) return response()->json(['success' => false, 'message' => __('user_account.create_fail'), 'errors' => $validator->errors()->all()]);
            $data = array(
                'name' => $request->name,
                'email' => $request->email,
                'password' => Hash::make($request->password),
                'is_manager' => ($request->role_id==3 ? 1: 0),
                'sample_source_id' => $request->sample_source_id,
                'role_id' => $request->role_id,
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => Auth::id(),
            );
            $user = $this->userModel::query()->create($data);
            Log::channel('account_creation')->info(array('action' => 'create', 'raw' => $request->all(), 'prepared' => $data));
            $requests = new Request(array('uid' => $user->id, 'lab_ids' => [Session::get('base_lab_id')]));
            $this->assignLabs($requests);
            return response()->json(['success' => true, 'message' => __('user_account.create_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('user_account.create_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function update(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['update_user_account'])) return false;
            $validator = \Validator::make($request->all(), [
                'name' => 'required',
                'email' => 'required|email|unique:users,email, ' . $request->uid . ',id',
                'password' => 'required',
                'role_id' => 'required'
            ]);
            if ($validator->fails()) return response()->json(['success' => false, 'message' => __('user_account.update_fail'), 'errors' => $validator->errors()->all()]);
            $data = array(
                'name' => $request->name,
                'email' => $request->email,
                'role_id' => $request->role_id,
                'is_manager' => ($request->role_id==3 ? 1: 0),
                'sample_source_id' => $request->sample_source_id,
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => Auth::id()
            );
            $this->userModel::query()->where('id', $request->uid)->update($data);
            Log::channel('account_creation')->info(array('action' => 'update', 'raw' => $request->all(), 'prepared' => $data));
            return response()->json(['success' => true, 'message' => __('user_account.update_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('user_account.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function resetPassword(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['update_user_account'])) return false;
            $validator = \Validator::make($request->all(), [
                'uid' => 'required',
                'password' => 'required'
            ]);
            if ($validator->fails()) return response()->json(['success' => false, 'message' => __('user_account.update_fail'), 'errors' => $validator->errors()->all()]);
            $data = array(
                'password' => Hash::make($request->password),
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => Auth::id()
            );
            $this->userModel::query()->find($request->uid)->update($data);
            return response()->json(['success' => true, 'message' => __('user_account.update_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('user_account.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function get(Request $request){
        try{
            $user = $this->userModel::with(['lab_covers'])->find($request->uid);
            return response()->json(['success' => true, 'message' => __('user_account.get_success'), 'data' => $user]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('user_account.get_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function delete(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['delete_user_account'])) return false;
            $this->userModel::query()->where('id', $request->uid)->update(array( BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::DELETE));
            return response()->json(['success' => true, 'message' => __('user_account.delete_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('user_account.delete_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function restore(Request $request){
        try{
            $this->userModel::query()->where('id', $request->uid)->update(array(BaseModel::RECORD_STATUS_FIELD=> RecordStatusEnum::ACTIVE));
            return response()->json(['success' => true, 'message' => __('user_account.restore_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('user_account.restore_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function assignLabs(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['assign_lab'])) return false;
            $validator = \Validator::make($request->all(), [ 'uid' => 'required']);
            if ($validator->fails()) return response()->json(['success' => false, 'message' => __('user_account.assign_lab_fail'), 'errors'=>$validator->errors()->all()]);
            $this->userLabCover::query()->where('user_id', $request->uid)
                ->update(['end_date' => date('Y-m-d'), BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::DELETE, BaseModel::UPDATED_AT_FIELD => date('Y-m-d H:i:s'), BaseModel::UPDATED_BY_FIELD =>Auth::id()]);
            $data = array();
            foreach ($request->lab_ids as $lab_id){
                $data[] = array(
                    'user_id' => $request->uid,
                    'lab_id' => $lab_id,
                    'start_date' => date('Y-m-d'),
                    'created_at' => date('Y-m-d H:i:s'),
                    'created_by' => Auth::id()
                );
            }
            $this->userLabCover::query()->insert($data);
            return response()->json(['success' => true, 'message' => __('user_account.assign_lab_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('user_account.assign_lab_fail'), 'errors' => $e->getMessage()]);
        }

    }

    public function uploadSignature(Request $request){
        try {
            $image = $request->file('signature');
            $imageName = 'signature_'.Auth::id().date('YmdHis').'.' . $image->getClientOriginalExtension();
            $user = User::find(Auth::id());
            $user->update(array('signature' => $imageName));
            $image->move(public_path('storage/images/signature'), $imageName);
            return back()->with(['success' => true, 'message' => __('singnature updated'), 'data' => 'signature']);
        }catch (\Exception $e){
            Log::error($e);
            return response()->json(['success'=> false , 'message' => __('user_account.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function removeSignature(Request $request){
        try {
            $user = $this->userModel::query()->find(Auth::id());
            if(!empty($user->signature)) {
                if (file_exists(public_path('storage/images/signature/' . $user->signature))) {
                    unlink(public_path('storage/images/signature/' . $user->signature));
                    $user->signature = null;
                }
            }
            $user->save();
            return response()->json(['success' => true, 'message' => __('user_account.update_success'), 'data' => $user]);
        }catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => __('user_account.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function changePassword(Request $request)
    {
    try {

        $request->validate([
            'current_password' => 'required|string',
            'new_password' => 'required|confirmed|min:8|string'
        ]);

        $auth = Auth::user();

        // Check current password
        if (!Hash::check($request->current_password, $auth->password)) {
            // return response()->json([
            //     'success' => false,
            //     'message' => __('user_account.invalid_current_password')
            // ]);
            return redirect()->back()->withErrors(['current_password' => __('user_account.invalid_current_password')]);
        }

        // Check new password not same as old
        if ($request->current_password === $request->new_password) {
            return redirect()->back()->withErrors(['new_password' => __('user_account.new_password_same_old_password')]);
        }

        // Update password
        $user = User::where('id', $auth->id)->update([
            'password' => Hash::make($request->new_password)
        ]);

        Log::channel('account_creation')->info([
            'action' => 'change-password',
            'user_id' => $auth->id
        ]);

        // return response()->json([
        //     'success' => true,
        //     'message' => __('user_account.change_password_success')
        //     //'data' => $user
        // ]);
        return redirect()->back()->with('success', __('user_account.change_password_success'));

    } catch (\Exception $e) {

        // return response()->json([
        //     'success' => false,
        //     'message' => __('user_account.change_password_fail'),
        //     'errors' => $e->getMessage()
        // ]);
        return redirect()->back()->withErrors(['error' => __('user_account.change_password_fail') . ': ' . $e->getMessage()]);

    }
    }

    function my_profile()
    {
        $user = $this->userModel::query()->with(['role','lab_covers'])->find(Auth::id());
        //return response()->json(['success' => true, 'message' => __('user_account.get_success'), 'data' => $user]);
        return view('my_profiles',[
            // 'labSettings' => (object) $this->base,
            'users' => $user
        ]);

    }




}
