<?php

namespace App\Http\Controllers\ChiefWorker;

use App\Http\Controllers\Controller;
use App\Models\AppRequest;
use App\Models\Settings;
use App\Models\User;
use App\Models\Worker;
use App\Models\WorkReq;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Morilog\Jalali\Jalalian;

class UserController extends Controller
{
    public function show()
    {
        /*
        $info = [
                'weight' => $weights[$key] . ' ' . $weightUnits[$key],
                'chiefprice' => $chiefprices[$key],
                'workerprice' => $workerprices[$key],
                'enddate' => $enddates[$key],
                'ispast' => false,
                'action' => 'در حال کار',
                'vaziat' => 1
            ];
        */
        $perPage = 25;
        $page = request()->input('page', 1);

        $UserRequests = WorkReq::where('user_requests.user_id', Auth::id())
            ->join('requests', 'requests.id', 'user_requests.request_id')
            ->join('users', 'users.id', 'requests.user_id')
            ->where('user_requests.info->vaziat', 1)
            ->where('requests.step', '>=', 6)
            ->where('requests.step', '<=', 7)
            ->select('requests.*', 'users.first_name', 'users.last_name', 'user_requests.info', 'user_requests.id as urid')
            ->orderBy('requests.id', 'desc')
            ->paginate($perPage, ['*'], 'page', $page);

        foreach ($UserRequests as $key => $userreq) {
            if (!is_array($userreq->step_info)) {
                $userreq->step_info = json_decode($userreq->step_info, true);
            }

            foreach ($userreq->step_info as $step_info) {
                if ($step_info['action'] == 'به کارگران تخصیص یافت' && $step_info['user_id'] == Auth::id()) {
                    unset($UserRequests[$key]);
                }
            }
        }

        return view('chiefWorker.index', compact('UserRequests'));
    }

    public function viewEdit($id = null)
    {
        if ($id != null && (int) $id > 0) {
            $RequestInfo = WorkReq::where('user_requests.id', $id)
                ->join('requests', 'requests.id', '=', 'user_requests.request_id')
                ->join('users', 'requests.user_id', '=', 'users.id')
                ->select('requests.*', 'users.first_name', 'users.last_name', 'user_requests.info', 'user_requests.id as urid')
                ->first();

            $worker_sub = Worker::where('user_id', Auth::id())->first();
            $subusers = $worker_sub->sub_users;

            $user_workers = User::whereIn('id', $subusers)->get();

            $myUserReq = WorkReq::where('user_id', Auth::id())->where('request_id', $RequestInfo->id)->first();

            $Settings = Settings::where('title', 'worker_salary')->first();
            $worker_salary = $Settings->value; 

            return view('chiefWorker.edit', compact(['RequestInfo', 'user_workers', 'myUserReq' , 'worker_salary']));
        }

        return redirect()->route('chief.panel');
    }

    public function accept(Request $request)
    {
        $RequestInfo = AppRequest::where('id', $request->requestId)->first();
        $workers = $request->input('worker');
        $weights = $request->input('weight');
        $weightUnits = $request->input('weightUnit');
        $workerprices = $request->input('workerprice');
        $enddates = $request->input('enddate');

        if (count($workers) > 0) {
            foreach ($workers as $key => $worker) {

                $hasRow = WorkReq::where('user_id', $worker)
                    ->where('request_id', $request->requestId)
                    ->exists();
                if (!$hasRow) {
                    $newWorkerReq = new WorkReq();

                    if (empty($enddates[$key])) {
                        return redirect() -> back() -> with('error', 'تاریخ ها به شکل درست وارد نشده.');
                    }

                    if (empty($workerprices[$key])) {
                        return redirect()-> back() -> with('error', 'قیمت ها به شکل درست وارد نشده.');
                    }

                    $info = [
                        'weight' => $weights[$key] . ' ' . $weightUnits[$key],
                        'workerprice' => $workerprices[$key],
                        'enddate' => $enddates[$key],
                        'ispast' => false,
                        'action' => 'در حال کار',
                        'vaziat' => 1
                    ];

                    $newWorkerReq->user_id = $worker;
                    $newWorkerReq->request_id = $request->requestId;
                    $newWorkerReq->info = $info;
                    $newWorkerReq->save();
                }
            }

            $RequestInfo->step = 7;

            $stepInfo = $RequestInfo->step_info;

            if (!is_array($stepInfo)) {
                $stepInfo = [];
            }

            $stepInfo[] = [
                'action' => 'به کارگران تخصیص یافت',
                'user_id' => Auth::id(),
                'date' => Jalalian::now()->format('Y/m/d H:i:s')
            ];

            $RequestInfo->step_info =  $stepInfo;

            $RequestInfo->save();
        }
        return redirect()->route('chief.panel');
    }

    public function disagree(Request $request)
    {
        $RequestInfo = AppRequest::where('id', $request->reqId)->first();

        $stepInfo = $RequestInfo->step_info;

        if (!is_array($stepInfo)) {
            $stepInfo = [];
        }

        $stepInfo[] = [
            'action' => 'اعلام مغایرت توسط ' . Auth::user()->first_name . ' ' . Auth::user()->last_name . ' توضیح: ' . $request->reason,
            'user_id' => Auth::id(),
            'date' => Jalalian::now()->format('Y/m/d H:i:s')
        ];

        $RequestInfo->step_info =  $stepInfo;

        $oldstep =  $RequestInfo->step;

        if ((int) $oldstep > 0) {
            $RequestInfo->step = $oldstep * -1;
        }
        $RequestInfo->save();

        return redirect()->route('chief.panel');
    }

    public function current()
    {
        $userprofiles = Worker::where('user_id', Auth::id())->first();
        $ids = $userprofiles->sub_users;

        $perPage = 25;
        $page = request()->input('page', 1);

        $mcode = request()->input('mcode');
        $phone = request()->input('phone');

        $query = WorkReq::join('requests', 'requests.id', 'user_requests.request_id')
            ->whereNotNull('user_requests.info')
            ->where('requests.step', '>', 6)
            ->where('requests.step', '<', 9)
            ->whereIn('user_requests.user_id', $ids)
            ->join('users', 'users.id', 'user_requests.user_id')
            ->where('users.role', 'worker')
            ->select(
                'user_requests.id as user_request_id',
                'user_requests.info',
                'requests.*',
                'users.first_name',
                'users.last_name',
                'users.melli_code',
                'users.phone'
            );


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

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

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

        foreach ($UserRequests as $UserRequest) {
            $oldinfo = $UserRequest->info;
            if (isset($UserRequest->info['enddate'])) {
                $oldinfo['ispast'] = $this->isPastDate($UserRequest->info['enddate']);
            } else {
                $oldinfo['ispast'] = false;
            }
            $UserRequest->info =  $oldinfo;
        }

        return view('chiefWorker.current', compact('UserRequests'));
    }

    public function listCurrent()
    {
        $perPage = 25;
        $page = request()->input('page', 1);

        $UserRequests = WorkReq::where('user_requests.user_id', Auth::id())
            ->join('requests', 'requests.id', 'user_requests.request_id')
            ->join('users', 'users.id', 'requests.user_id')
            ->where('user_requests.info->vaziat', 1)
            ->where('requests.step', '>', 6)
            ->where('requests.step', '<', 9)
            ->select('requests.*', 'users.first_name', 'users.last_name', 'user_requests.info', 'user_requests.id as urid')
            ->orderBy('requests.id', 'desc')
            ->paginate($perPage, ['*'], 'page', $page);

        return view('chiefWorker.index', compact('UserRequests'));
    }

    public function currentInfo($id = null)
    {
        if ($id != null && (int) $id > 0) {
            $RequestInfo = AppRequest::where('requests.id', $id)
                ->join('users', 'requests.user_id', '=', 'users.id')
                ->join('farmer_profiles', 'requests.user_id', '=', 'farmer_profiles.user_id')
                ->select('requests.*', 'users.first_name', 'users.last_name')
                ->first();

            $WorkerInfo = WorkReq::where('user_requests.request_id', $id)
                ->whereNotNull('user_requests.info')
                ->join('users', 'users.id', 'user_requests.user_id')
                ->where('users.role', 'worker')
                ->select('users.id', 'user_requests.info', 'users.first_name', 'users.last_name', 'users.phone')
                ->get();

            $myUserReq = WorkReq::where('user_id', Auth::id())->where('request_id', $id)->first();
            $myUserProf = Worker::where('user_id', Auth::id())->first();

            return view('chiefWorker.request', compact(['RequestInfo', 'WorkerInfo', 'myUserReq', 'myUserProf']));
        }

        return redirect()->route('chief.panel');
    }

    public function workerAccept(Request $request)
    {
        $RequestInfo = AppRequest::where('id', $request->requestId)->first();

        $myUserReq = WorkReq::where('user_id', $request->userId)->where('request_id', $request->requestId)->first();

        $workerUserInfo = User::where('id', $request->userId)->first();

        $allUserReq = WorkReq::where('user_requests.request_id', $request->requestId)
            ->whereNotNull('user_requests.info')
            ->join('users', 'users.id', 'user_requests.user_id')
            ->where('users.role', 'chief_worker')
            ->select('user_requests.*')
            ->get();

        $chiefWorkerIds = $allUserReq->pluck('user_id')->toArray();
        $stepUserIds = [];
        foreach ($RequestInfo->step_info as $step_info) {
            if ($step_info['action'] == 'به کارگران تخصیص یافت') {
                if (isset($step_info['user_id'])) {
                    $stepUserIds[] = $step_info['user_id'];

                    $allChiefWorkersInStep = empty(array_diff($chiefWorkerIds, $stepUserIds));

                    if ($allChiefWorkersInStep && !empty($chiefWorkerIds)) {
                        $RequestInfo->step = 8;
                    }
                }
            }
        }

        $urinfo = $myUserReq->info;

        $urinfo['action'] = 'کار را به اتمام رساند';
        $urinfo['vaziat'] = 2;
        $myUserReq->info = $urinfo;
        $myUserReq->save();

        //$RequestInfo->step = 8;

        $stepInfo = $RequestInfo->step_info;

        if (!is_array($stepInfo)) {
            $stepInfo = [];
        }

        $stepInfo[] = [
            'action' => 'کارگر ' . $workerUserInfo->first_name . ' ' . $workerUserInfo->last_name . ' کار خود را تمام کرد.',
            'user_id' => $request->userId,
            'date' => Jalalian::now()->format('Y/m/d H:i:s')
        ];

        $RequestInfo->step_info =  $stepInfo;

        $RequestInfo->save();

        return redirect()->back();
    }

    public function isPastDate($persianDate)
    {

        $dateParts = explode(' ', $persianDate);
        $date = explode('/', $dateParts[0]);
        $time = explode(':', $dateParts[1]);


        $jalali = new Jalalian(
            (int)$date[0], // سال
            (int)$date[1], // ماه
            (int)$date[2], // روز
            (int)$time[0], // ساعت
            (int)$time[1], // دقیقه
            (int)$time[2]  // ثانیه
        );

        return $jalali->toCarbon()->lt(now());
    }

    public function currentAccept(Request $request)
    {
        $colale = $request->input('colale');
        $flower = $request->input('flower');
        $root = $request->input('root');
        $reqid = $request->input('reqId');

        if(isset($colale) && isset($flower) && isset($root) && ctype_digit($colale) && ctype_digit($flower) && ctype_digit($root) && (int) $colale > 0 && (int) $flower > 0 && (int) $root > 0)
        {

        $RequestInfo = AppRequest::where('id', $reqid)->first();
        $userreq = WorkReq::where('user_id', Auth::id())->where('request_id', $reqid)->first();

        $worker_sub = Worker::where('user_id', Auth::id())->first();
        $subusers = $worker_sub->sub_users;

        $allUserReq = WorkReq::where('user_requests.request_id', $reqid)
            ->whereNotNull('user_requests.info')
            ->join('users', 'users.id', 'user_requests.user_id')
            ->where('users.role', 'chief_worker')
            ->select('user_requests.*')
            ->get();

        $chiefWorkerIds = $allUserReq->pluck('user_id')->toArray();

        $canenter = false;
        $subenter = true;

        $stepUserIds = [];
        foreach ($RequestInfo->step_info as $step_info) {
            if ($step_info['action'] == 'به کارگران تخصیص یافت') {
                if (isset($step_info['user_id'])) {
                    $stepUserIds[] = $step_info['user_id'];

                    $allChiefWorkersInStep = empty(array_diff($chiefWorkerIds, $stepUserIds));

                    if ($allChiefWorkersInStep && !empty($chiefWorkerIds)) {
                        $canenter = true;
                    }
                }
            }
        }


        foreach ($subusers as $wsubuser) {
            $userreq1 = WorkReq::where('user_id', $wsubuser)->where('request_id', $reqid)->first();

            if (isset($userreq1->info) && $userreq1->info['vaziat'] == 1) {
                $subenter = false;
            }
        }

        if ($subenter) {
            $allworkeruserreq = WorkReq::where('user_requests.request_id', $reqid)
                ->join('users', 'users.id', 'user_requests.user_id')
                ->where('users.role', 'worker')
                ->whereIn('users.id', $subusers)
                ->get();

            $notfinishedworkernum = 0;

            foreach ($allworkeruserreq as $oneuserreq) {
                if ($oneuserreq->info['vaziat'] == 1) {
                    $notfinishedworkernum = $notfinishedworkernum + 1;
                }
            }

            if ($notfinishedworkernum == 0) {

                $oldinfo = $userreq->info;
                $oldinfo['action'] = "اعلام اتمام کار و ارسال به واحد خشک کن";
                $oldinfo['vaziat'] = 2;
                $userreq->info = $oldinfo;
                $userreq->save();

                $alluserreq = WorkReq::where('user_requests.request_id', $reqid)
                    ->join('users', 'users.id', 'user_requests.user_id')
                    ->where('users.role', 'chief_worker')
                    ->get();

                $stepInfo = $RequestInfo->step_info;
                if (!is_array($stepInfo)) {
                    $stepInfo = [];
                }

                $stepInfo[] = [
                    'action' => 'اتمام و اعلام مشخصات وزن توسط سرتیم: ' . Auth::user()->first_name . ' ' . Auth::user()->last_name . ' کلاله تر: ' . $colale . ' ریشه: ' . $root . ' گل: ' . $flower,
                    'user_id' => Auth::id(),
                    'date' => Jalalian::now()->format('Y/m/d H:i:s')
                ];

                $oldweight = $RequestInfo->weight;

                $oldweight['chief'][Auth::id()] = [
                    'کلاله' => $colale,
                    'ریشه' => $root,
                    'گل' => $flower
                ];
                $RequestInfo->weight = $oldweight;

                $notfinishednum = 0;

                foreach ($alluserreq as $oneuserreq) {
                    if ($oneuserreq->info['vaziat'] == 1) {
                        $notfinishednum = $notfinishednum + 1;
                    }
                }

                if ($notfinishednum == 0 && $canenter) {
                    $stepInfo[] = [
                        'action' => 'اتمام توسط تمام سرتیم ها و ارسال به واحد خشک کن',
                        'user_id' => Auth::id(),
                        'date' => Jalalian::now()->format('Y/m/d H:i:s')
                    ];
                    $RequestInfo->step = 9;
                }

                $RequestInfo->step_info = $stepInfo;
                $RequestInfo->save();

                WorkReq::where('user_requests.request_id', $reqid)
                    ->join('users', 'users.id', 'user_requests.user_id')
                    ->where('users.role', 'worker')
                    ->whereIn('users.id', $subusers)
                    ->update([
                        'info->vaziat' => 100
                    ]);

                return redirect()->route('chief.panel')->with('success', 'فرایند با موفقیت انجام شد.');
            }

            return redirect()->route('chief.current')->with('error', 'همه کارگران کار را تمام نکرده اند.');
        } else {
            return redirect()->route('chief.current')->with('error', 'کارگری اتمام کار را نزده است.');
        }
        }

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

    public function archive()
    {
        $perPage = 25;
        $page = request()->input('page', 1);

        $UserRequests = WorkReq::where('user_requests.user_id', Auth::id())
            ->join('requests', 'requests.id', 'user_requests.request_id')
            ->join('users', 'users.id', 'requests.user_id')
            ->where('requests.step', '>', 8)
            ->select('requests.*', 'users.first_name', 'users.last_name', 'user_requests.info', 'user_requests.id as urid')
            ->orderBy('requests.id', 'desc')
            ->paginate($perPage, ['*'], 'page', $page);

        return view('chiefWorker.index', compact('UserRequests'));
    }
}
