<?php

namespace App\Http\Controllers\General;

use App\Http\Controllers\Controller;
use App\Models\AppRequest;
use App\Models\Messages;
use App\Models\User;
use App\Models\WorkReq;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Str;
use App\Services\IppanelService;

class UserController extends Controller
{

    protected $smsService;

    public function __construct(IppanelService $smsService)
    {
        $this->smsService = $smsService;
    }

    public function logout()
    {
        Auth::logout();
        return redirect()->route('login');
    }

    public function login(Request $request)
    {
        if (Auth::attempt(['username' => $request->input('username'), 'password' => $request->input('password')], true)) {
            if (Auth::check() && Auth::user()->role == 'farmer') {
                $RequestInfo = AppRequest::where('user_id', Auth::id())->orderBy('id', 'desc')->get()
                    ->map(function ($Inforequest) {
                        $Inforequest->token = base64_encode(json_encode([
                            'user_id' => Auth::id(),
                            'request_id' => $Inforequest->id
                        ]));
                        return $Inforequest;
                    });
                $AllRequests = $RequestInfo;
                $weightInfo = [
                    "قرارداد" => 0,
                    "گل" => 0,
                    "کلاله تر" => 0,
                    "زعفران" => 0,
                    "حمل" => 0,
                    "تعداد کل" => 0,
                    "خشک کن" => 0
                ];

                if ($AllRequests != null) {
                    $RequestCount = $AllRequests->count();


                    $weightInfo["تعداد کل"] = $RequestCount;

                    foreach ($AllRequests as $Req) {
                        $weightarr = $Req->weight;
                        //list($weight, $unit) = explode(' ', $weightarr['farmer']);
                        $weightInfo1 = explode(' ', $weightarr['farmer']);

                        $contract_req = $Req->contract;

                        if (count($weightInfo1) == 1) {
                            $weight = 0;
                            $unit = $weightInfo1[0];
                        } else {
                            $weight = (int) $weightInfo1[0];
                            $unit = $weightInfo1[1];
                        }


                        if (is_array($contract_req) && isset($contract_req['dryerpriceunit']) && isset($weightarr['dryer']['زعفران'])) {
                            $weightInfo["خشک کن"] = $weightInfo["خشک کن"] + ($contract_req['dryerpriceunit'] * $weightarr['dryer']['زعفران']);
                        }


                        if ($unit == 'گرم') {
                            $weight = $weight / 1000;
                        }

                        if (is_array($Req->transportation) && isset($Req->transportation['pricetotal'])) {
                            $weightInfo['حمل'] = $weightInfo['حمل'] + $Req->transportation['pricetotal'];
                        }

                        $weightInfo['گل'] = $weightInfo['گل'] + $weight;

                        $contract = $Req->contract;
                        if (isset($contract['pricetotal'])) {
                            $weightInfo['قرارداد'] = $weightInfo['قرارداد'] + $Req->contract['pricetotal'];
                        }

                        if (isset($weightarr['dryer']) && isset($weightarr['dryer']['زعفران'])) {
                            $weightInfo['کلاله تر'] = $weightInfo['کلاله تر'] + $weightarr['dryer']['کلاله'];
                            $weightInfo['زعفران'] = $weightInfo['زعفران'] + $weightarr['dryer']['زعفران'];
                        }
                    }
                }
                return redirect()->route('farmer.panel', compact(['RequestInfo', 'weightInfo']));
            }
        }

        return redirect()->route('login')->with('loginError', 'نام کاربری یا کلمه عبور صحیح نمی باشد');
    }

    public function newpass(Request $request)
    {
        $username = $request->input('username');
        if (!empty($username)) {
            $user_info = User::where('username', $username)->first();

            if ($user_info !== null) {
                $phone = $user_info->phone;
                $randomCode = rand(1000000, 9999999);
                $user_info->password = $randomCode;
                $user_info->save();

                $result = $this->smsService->sendPattern(
                    config('services.ippanel.default_from'),
                    'c5pcbvtqkb60a0v',
                    [$phone],
                    [
                        'username' => $username,
                        'password' => $randomCode
                    ]
                );

                if ($result['success']) {

                    return redirect()->back()->with('success', 'پیامک حاوی اطلاعات ورود به شما پیامک شد');
                } else {
                    return redirect()->back()->with('error', 'مشکلی در ارسال پیامک رخ داد دوباره تلاش کنید.');
                }
            }

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

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

    public function panel()
    {
        if (Auth::check() && Auth::user()->role == 'farmer') {
            $NotifMessages = Messages::where('messages.user_id',Auth::id())
                            ->where('messages.status', 0)
                            ->get();

            $RequestInfo = AppRequest::where('user_id', Auth::id())->orderBy('id', 'desc')->get()
                ->map(function ($Inforequest) {
                    $Inforequest->token = base64_encode(
                        Auth::id() . '-' . $Inforequest->id
                    );
                    return $Inforequest;
                });
            $AllRequests = $RequestInfo;
                $weightInfo = [
                    "قرارداد" => 0,
                    "گل" => 0,
                    "کلاله تر" => 0,
                    "زعفران" => 0,
                    "حمل" => 0,
                    "تعداد کل" => 0,
                    "خشک کن" => 0
                ];

                if ($AllRequests != null) {
                    $RequestCount = $AllRequests->count();


                    $weightInfo["تعداد کل"] = $RequestCount;

                    foreach ($AllRequests as $Req) {
                        $weightarr = $Req->weight;
                        //list($weight, $unit) = explode(' ', $weightarr['farmer']);
                        $weightInfo1 = explode(' ', $weightarr['farmer']);

                        $contract_req = $Req->contract;

                        if (count($weightInfo1) == 1) {
                            $weight = 0;
                            $unit = $weightInfo1[0];
                        } else {
                            $weight = (float) $weightInfo1[0];
                            $unit = $weightInfo1[1];
                        }


                        if (is_array($contract_req) && isset($contract_req['dryerpriceunit']) && isset($weightarr['dryer']['زعفران'])) {
                            $weightInfo["خشک کن"] = $weightInfo["خشک کن"] + ($contract_req['dryerpriceunit'] * $weightarr['dryer']['زعفران']);
                        }


                        if ($unit == 'گرم') {
                            $weight = $weight / 1000;
                        }

                        if (is_array($Req->transportation) && isset($Req->transportation['pricetotal'])) {
                            $weightInfo['حمل'] = $weightInfo['حمل'] + $Req->transportation['pricetotal'];
                        }

                        $weightInfo['گل'] = $weightInfo['گل'] + $weight;

                        $contract = $Req->contract;
                        if (isset($contract['pricetotal'])) {
                            $weightInfo['قرارداد'] = $weightInfo['قرارداد'] + $Req->contract['pricetotal'];
                        }

                        if (isset($weightarr['dryer']) && isset($weightarr['dryer']['زعفران'])) {
                            $weightInfo['کلاله تر'] = $weightInfo['کلاله تر'] + $weightarr['dryer']['کلاله'];
                            $weightInfo['زعفران'] = $weightInfo['زعفران'] + $weightarr['dryer']['زعفران'];
                        }
                    }
                }
            return view('farmer.index', compact(['RequestInfo', 'NotifMessages','weightInfo']));
        } else if (Auth::check() && Auth::user()->role == 'contractor') {
            return redirect()->route('contractor.panel');
        }

        return redirect()->route('login');
    }

    public function contractor()
    {
        if (Auth::check() && Auth::user()->role == 'contractor') {
            $perPage = 25;
            $step = request()->input('step');
            $mcode = request()->input('mcode');
            $fname = request()->input('fname');
            $lname = request()->input('lname');
            $page = request()->input('page', 1);

            $query = AppRequest::where('requests.step', '>', 0)
                ->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');

            if ($step && $step <= 4) {
                $query->where('requests.step', $step);
            }

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

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

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

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

            return view('contractor.index', compact('RequestInfo'));
        }

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

    public function contract($code)
    {

        $data = $this->validateToken($code);
        list($usid, $reqid) = explode("-", $data);
        $RequestInfo = AppRequest::where('id', $reqid)
            ->where('user_id', $usid)->first();
        $user_info = User::find($usid);
        return view('farmer.contract', compact(['RequestInfo', 'user_info']));
    }

    public function generateToken($userId, $req_id)
    {
        $data = $userId . "-" . $req_id;

        return base64_encode($data);
    }


    public function validateToken($token)
    {
        try {
            $data = base64_decode($token);
            return $data;
        } catch (\Exception $e) {
            return false;
        }
    }

    public function transporter()
    {
        $perPage = 25;
        $page = request()->input('page', 1);
        $mcode = request()->input('mcode');
        $phone = request()->input('phone');
        $query = WorkReq::where('user_requests.user_id', Auth::id())
            ->join('requests', 'requests.id', 'user_requests.request_id')
            ->join('users', 'users.id', 'requests.user_id')
            ->join('farmer_profiles as farmer', 'farmer.user_id', 'users.id')
            ->select(
                'user_requests.id as usreqId',
                '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('user_requests.id', 'desc')
            ->paginate($perPage, ['*'], 'page', $page);
        return view('transporter.index', compact('UserRequests'));
    }

    public function messageSeen(Request $request)
    {
        $userId = $request->input('id');

        if (isset($userId)) {
            $messageInfo = Messages::where('user_id', $userId)
                ->where('status', 0)
                ->update([
                    'status' => 1
                ]);

            if ($messageInfo > 0) {
                return response()->json([
                    'success' => true
                ]);
            }

            return response()->json([
                'success' => false
            ]);
        }

        return response()->json([
            'success' => false
        ]);
    }
}
