<?php

namespace App\Http\Controllers\Reciever;

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

class UserController extends Controller
{
    public function show()
    {
        $perPage = 25;
        $page = request()->input('page', 1);
        $mcode = request()->input('mcode');
        $phone = request()->input('phone');
        $fname = request()->input('fname');
        $lname = request()->input('lname');
        $query = AppRequest::where('requests.step', '>=', '4')
            ->where('requests.step', '<', '6')
            ->join('users', 'users.id', 'requests.user_id')
            ->join('farmer_profiles as farmer', 'farmer.user_id', 'users.id')
            ->select(
                'requests.*',
                'users.first_name',
                'users.last_name',
                'users.melli_code',
                'users.phone',
                'farmer.state',
                'farmer.city',
                'farmer.address',
                'farmer.farm_name'
            );

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

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

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

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

        $AllRequests = $query->get();

        $allweights = 0;

        foreach ($AllRequests as $Req) {
            $farmer_weight = $Req->weight['farmer'];
            $farmer_weight = explode(" ",$farmer_weight);
            $allweights = $allweights + $farmer_weight[0];
        }

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

        $justshow = false;

        return view('factoryReceiver.index', compact(['UserRequests', 'justshow','allweights']));
    }

    public function disagreementShow()
    {
        $perPage = 25;
        $page = request()->input('page', 1);
        $mcode = request()->input('mcode');
        $phone = request()->input('phone');
        $query = AppRequest::where('requests.step', '<', '0')
            ->where('requests.step', '>', '-100')
            ->join('users', 'users.id', 'requests.user_id')
            ->join('farmer_profiles as farmer', 'farmer.user_id', 'users.id')
            ->select(
                'requests.*',
                'users.first_name',
                'users.last_name',
                'users.melli_code',
                'users.phone',
                'farmer.state',
                'farmer.city',
                'farmer.address',
                'farmer.farm_name'
            );

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

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

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

        $justshow = true;

        return view('factoryReceiver.index', compact(['UserRequests', 'justshow']));
    }

    public function canceled()
    {
        $perPage = 25;
        $page = request()->input('page', 1);
        $mcode = request()->input('mcode');
        $phone = request()->input('phone');
        $query = AppRequest::where('requests.step', '<', '-100')
            ->join('users', 'users.id', 'requests.user_id')
            ->join('farmer_profiles as farmer', 'farmer.user_id', 'users.id')
            ->select(
                'requests.*',
                'users.first_name',
                'users.last_name',
                'users.melli_code',
                'users.phone',
                'farmer.state',
                'farmer.city',
                'farmer.address',
                'farmer.farm_name'
            );

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

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

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

        $justshow = true;

        return view('factoryReceiver.index', compact(['UserRequests', 'justshow']));
    }

    public function viewEdit($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', 'users.phone', 'users.melli_code', 'farmer_profiles.state', 'farmer_profiles.city', 'farmer_profiles.address', 'farmer_profiles.farm_name', 'farmer_profiles.father_name')
                ->first();
            $user_chief_worker = User::where('role', 'chief_worker')->get();

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

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

            if (isset($RequestInfo->transportation['user_id']) && ctype_digit($RequestInfo->transportation['user_id'])) {
                $Transporter = User::find($RequestInfo->transportation['user_id']);
                if ($RequestInfo->step >= 4 && $RequestInfo->step < 6) {
                    return view('factoryReceiver.edit', compact(['RequestInfo', 'Transporter', 'user_chief_worker','worker_salary','chiefworker_salary']));
                }
            }

            if ($RequestInfo->step >= 4 && $RequestInfo->step < 6) {
                return view('factoryReceiver.edit', compact(['RequestInfo', 'user_chief_worker','worker_salary','chiefworker_salary']));
            }
            

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

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

        if (count($chiefWorkers) > 0) {
            foreach ($chiefWorkers as $key => $chiefWorker) {
                $hasRow = WorkReq::where('user_id', $chiefWorker)
                    ->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],
                        'chiefprice' => $chiefprices[$key],
                        'workerprice' => $workerprices[$key],
                        'enddate' => $enddates[$key],
                        'ispast' => false,
                        'action' => 'در حال کار',
                        'vaziat' => 1
                    ];

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

            $RequestInfo->step = 6;

            $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('factory.reciever.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('factory.reciever.panel');
    }

    public function current()
    {
        $perPage = 25;
        $page = request()->input('page', 1);
        $mcode = request()->input('mcode');
        $phone = request()->input('phone');
        $fname = request()->input('fname');
        $lname = request()->input('lname');
        $query = WorkReq::join('requests', 'requests.id', 'user_requests.request_id')
            ->whereNotNull('user_requests.info')
            ->where('requests.step', '>=', 6)
            ->where('requests.step', '<', 9)
            ->join('users', 'users.id', 'user_requests.user_id')
            ->where('users.role', 'chief_worker')
            ->select(
                'user_requests.id as user_request_id',
                'user_requests.info',
                'requests.*',
                'users.first_name',
                'users.last_name',
                'users.melli_code',
                'users.phone'
            );

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

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

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

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

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



        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('factoryReceiver.current', 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', 'users.phone', 'users.melli_code', 'farmer_profiles.state', 'farmer_profiles.city', 'farmer_profiles.address', 'farmer_profiles.farm_name', 'farmer_profiles.father_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', 'chief_worker')
                ->select('user_requests.info', 'users.first_name', 'users.last_name', 'users.phone')
                ->get();

            $weightInfo = $RequestInfo->weight;

            if (isset($weightInfo['chief'])) {
                foreach ($weightInfo['chief'] as $key => $weightcw) {
                    $UserInfo = User::find($key);
                    $weightcw['name'] = $UserInfo->first_name . ' ' . $UserInfo->last_name;
                    $weightInfo['chief'][$key] = $weightcw;
                }
            }
            //dd($weightInfo);

            return view('factoryReceiver.request', compact(['RequestInfo', 'WorkerInfo', 'weightInfo']));
        }

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

    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 addnote(Request $request)
    {
        $req_id = $request->input('requestId');
        $note = $request->input('note');

        if (isset($req_id) && isset($note)) {
            $RequestInfo = AppRequest::where('id', $req_id)->first();

            if ($RequestInfo != null) {
                $stepInfo = $RequestInfo->step_info;

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

                $stepInfo[] = [
                    'action' => 'یاداشت توسط '.Auth::user()->first_name.' '.Auth::user()->last_name.' : '.$note,
                    'user_id' => Auth::id(),
                    'date' => Jalalian::now()->format('Y/m/d H:i:s')
                ];

                $RequestInfo->step_info =  $stepInfo;

                $RequestInfo->save();

                return redirect()->back()->with('success', 'یادداشت شما ثبت شد.');
            }
        }

        return redirect()->back()->with('error', 'سفارش معتبری پیدا نشد.');
    }

    public function printlist()
    {
        $fname = request()->input('fname');
        $lname = request()->input('lname');
        $phone = request()->input('phone');
        $melli_code = request()->input('mcode');

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


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

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

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

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


        $AllRequests = $query->get();

        $filename = "requests_" . date('Y-m-d_H-i-s') . ".csv";

        header("Content-Type: text/csv; charset=utf-8");
        header("Content-Disposition: attachment; filename=$filename");

        $output = fopen('php://output', 'w');

        fputcsv($output, [
            'کد سفارش',
            'نام',
            'نام خانوادگی',
            'شماره تماس',
            'کد ملی',
            'وزن گل',
            'وضعیت',
            'تاریخ اتمام'
        ]); 

        foreach ($AllRequests as $req) {

            $stepName = $req->step;

            switch ($stepName) {
                case 1:
                    $stepName = "درخواست جدید";
                    break;
                case 2:
                    $stepName = "در انتظار تایید کشاورز";
                    break;
                case 3:
                    $stepName = "قرارداد تایید شد";
                    break;
                case 4:
                    $stepName = " در انتظار تحویل";
                    break;
                case 5:
                    $stepName = "در انتظار تایید مرکز فراوری";
                    break;
                case 6:
                    $stepName = "دریافت توسط مرکز فراوری";
                    break;
                case 7:
                    $stepName = "توزیع به سرتیم ها";
                    break;
                case 8:
                    $stepName = "اعلام اتمام کار توسط کارگران";
                    break;
                case 9:
                    $stepName = "اتمام کار توسط همه سرتیم ها";
                    break;
                case 10:
                    $stepName = "دریافت توسط مرکز خشک کن";
                    break;
                case 11:
                    $stepName = "اتمام خشک کردن";
                    break;
                case 12:
                    $stepName = "دریافت توسط واحد بسته بندی";
                    break;
                case 13:
                    $stepName = "اتمام سفارش و ارسال";
                    break;
            }


            fputcsv($output, [
                $req->id,
                $req->first_name,
                $req->last_name,
                $req->phone,
                $req->melli_code,
                $req->info['weight'],
                $stepName,
                $req->info['enddate']
            ]); 
        }

        fclose($output);
        exit; 
    }
}
