<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Requests\ADUserAddRequest;
use App\Models\Worker;
use App\Models\WorkReq;
use Illuminate\Support\Facades\Auth;

class WorkerController extends Controller
{
    public function show()
    {
        $perPage = 25;
        $page = request()->input('page', 1);
        $role = request()->input('role');
        $userId = request()->input('userId');
        $first_name = request()->input('first_name');
        $last_name = request()->input('last_name');
        $phone = request()->input('phone');
        $melli_code = request()->input('melli_code');

        $query = User::select('users.*');

        if (isset($role) && $role != '0') {
            $query->where('users.role', $role);
        } else {
            $query->whereIn('users.role', ['transporter', 'factory_receiver', 'distributor', 'contractor', 'chief_worker', 'worker', 'dryer', 'packager']);
        }

        if (isset($userId)) {
            $query->where('users.id', $userId);
        }

        if (isset($first_name)) {
            $query->where('users.first_name', $first_name);
        }

        if (isset($last_name)) {
            $query->where('users.last_name', $last_name);
        }

        if (isset($phone)) {
            $query->where('users.phone', $phone);
        }

        if (isset($melli_code)) {
            $query->where('users.melli_code', $melli_code);
        }

        $UserInfo = $query->orderBy('id', 'desc')
            ->paginate($perPage, ['*'], 'page', $page);

        $chiefWorkers = User::where('role', 'chief_worker')->get();

        return view('Admin.user', compact(['UserInfo', 'chiefWorkers']));
    }


    public function add(ADUserAddRequest $request)
    {
        if ($request->input('role') == 'worker' && ($request->input('chief') == null || $request->input('chief') == 0)) {
            return redirect()->back()->with('error', 'برای کارگران باید سرتیم مشخص کنید.');
        }

        $user_input = [
            'first_name' => $request->input('first_name'),
            'last_name' => $request->input('last_name'),
            'melli_code' => $request->input('melli_code'),
            'phone' => $request->input('phone'),
            'username' => $request->input('username'),
            'password' => $request->input('password'),
            'role' => $request->input('role')
        ];

        $returned_user = User::create($user_input);

        if ($returned_user !== null) {

            if ($request->input('role') == 'chief_worker') {
                $wrok_req = new Worker();
                $wrok_req->user_id = $returned_user->id;
                $wrok_req->sub_users = [];
                $wrok_req->save();
            }

            if ($request->input('role') == 'worker' && $request->input('chief') !== null && $request->input('chief') != 0) {
                $ChiefProfile = Worker::where('user_id', $request->input('chief'))->first();
                $subusers = $ChiefProfile->sub_users;
                $subusers[] = $returned_user->id;
                $ChiefProfile->sub_users = $subusers;
                $ChiefProfile->save();
            }

            return redirect()->back()->with('success', 'کاربر جدید اضافه شد.');
        }

        return redirect()->back()->with('error', 'مشکلی در افزودن کاربر رخ داد.');
    }

    public function view($id = null)
    {
        if ($id != null && $id > 0) {
            $UserInfo = User::where('id', $id)->first();
            $chiefWorkers = User::where('role', 'chief_worker')->get();
            if ($UserInfo->role == 'worker') {
                $selectedchiefWorker = Worker::whereJsonContains('sub_users', (int) $id)->first();
                return view('Admin.userView', compact(['UserInfo', 'chiefWorkers', 'selectedchiefWorker']));
            }

            return view('Admin.userView', compact(['UserInfo', 'chiefWorkers']));
        }
        return redirect()->back();
    }

    public function delete(Request $request)
    {
        if (Auth::check() && Auth::user()->role == 'admin') {
            $selected_user = User::find($request->input('userId'));

            if ($selected_user !== null) {
                $userid = $request->input('userId');
                if ($selected_user->role == 'worker') {
                    $worker_sub = Worker::whereJsonContains('sub_users', $request->input('userId'))->first();

                    if ($worker_sub) {
                        $subUsers = $worker_sub->sub_users;
                        $updatedSubUsers = array_filter($subUsers, function ($value) use ($userid) {
                            return $value != $userid;
                        });

                        $worker_sub->update(['sub_users' => array_values($updatedSubUsers)]);
                    }
                } else if ($selected_user->role == 'chief_worker') {
                    $Chiefworker = Worker::where('user_id', $userid)->first();
                    if($Chiefworker != null)
                    {
                        $Chiefworker->delete();
                    }
                    
                }

                $workreqs = WorkReq::where('user_id', $userid)->get();

                if ($workreqs !== null) {
                    foreach ($workreqs as $req) {
                        $req->delete();
                    }
                }

                $selected_user->delete();



                return redirect()->route('admin.user')->with('success', 'کاربر حذف شد.');
            }
        }

        return redirect()->back()->with('error', 'مشکلی در حذف کاربر رخ داد.');
    }

    public function edit(Request $request)
    {
        $userid = $request->input('userid');

        if ($userid !== null && (int) $userid > 0) {
            $UserInfo = User::where('id', $userid)->first();
            $UserInfo->first_name = $request->input('first_name');
            $UserInfo->last_name = $request->input('last_name');
            $UserInfo->melli_code = $request->input('melli_code');
            $UserInfo->phone = $request->input('phone');
            $UserInfo->username = $request->input('username');

            if ($request->input('password') != null) {
                $UserInfo->password = $request->input('password');
            }

            if ($UserInfo->role == 'worker' && $request->input('role') != 'worker') {
                $worker = Worker::whereJsonContains('sub_users', (int) $userid)->first();

                if ($worker) {
                    $subUsers = $worker->sub_users;
                    $updatedSubUsers = array_filter($subUsers, function ($value) use ($userid) {
                        return $value != $userid;
                    });

                    $worker->update(['sub_users' => array_values($updatedSubUsers)]);
                }
            } else if ($UserInfo->role != 'worker' && $request->input('role') == 'worker') {
                $ChiefWorker = Worker::where('user_id', $request->input('chief'))->first();
                $subusers = $ChiefWorker->sub_users;
                $subusers[] = $userid;
                $ChiefWorker->sub_users = $subusers;
                $ChiefWorker->save();
            } else if ($UserInfo->role == 'worker' && $request->input('role') == 'worker') {
                $worker = Worker::whereJsonContains('sub_users', (int) $userid)->first();
                if ($worker) {
                    if ($worker->user_id != $request->input('chief')) {
                        $subUsers = $worker->sub_users;
                        $updatedSubUsers = array_filter($subUsers, function ($value) use ($userid) {
                            return $value != $userid;
                        });

                        $worker->update(['sub_users' => array_values($updatedSubUsers)]);

                        $ChiefWorker = Worker::where('user_id', $request->input('chief'))->first();
                        $subusers = $ChiefWorker->sub_users;
                        $subusers[] = $userid;
                        $ChiefWorker->sub_users = $subusers;
                        $ChiefWorker->save();
                    }
                }
            }
            $UserInfo->role = $request->input('role');

            $UserInfo->save();

            return redirect()->back()->with('success', 'کاربر ویرایش شد.');
        }

        return redirect()->back()->with('error', 'مشکلی در ویرایش رخ داد.');
    }
}
