<?php

namespace App\Http\Controllers\Contractor;

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;
use App\Services\IppanelService;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Str;

class UserController extends Controller
{
    protected $smsService;

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

    // مشاهده جزئیات سفارش
    public function viewEdit($id = null)
    {
        if ($id != null && (int) $id > 0) {
            $allTransporter = User::where('role', 'transporter')->get();
            $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();

            $contractText = Settings::where('title', 'contract')->first();

            $contractText = $contractText->value;

            $contractText = str_replace('[FARMER]', $RequestInfo->first_name . ' ' . $RequestInfo->last_name, $contractText);

            $contractText = str_replace('[WEIGHT]', $RequestInfo->weight['farmer'], $contractText);

            $info = [
                'name' => $RequestInfo->first_name . ' ' . $RequestInfo->last_name,
                'weight' => $RequestInfo->weight['farmer']
            ];

            return view('contractor.edit', compact(['allTransporter', 'RequestInfo', 'info', 'contractText']));
        }
        return redirect()->route('contractor.panel');
    }

    // لغو درخواست
    public function cancel(Request $request)
    {
        if ($request->input('CancelId') !== null && ctype_digit($request->input('CancelId')) && (int) $request->input('CancelId') > 0) {
            $RequestInfo = AppRequest::find($request->input('CancelId'));
            $oldStep =  $RequestInfo->step;

            if ($oldStep > 0) {
                $oldStep *= -1;
            }
            $RequestInfo->step =  $oldStep - 100;
            $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('contractor.panel')->with('success', 'سفارش با موفقیت لغو شد.');
        }

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

    // قبول و ادامه مرحله بعد
    public function accept(Request $request)
    {
        $req_id = $request->input('RequestId');

        if ($req_id > 0) {
            $RequestInfo = AppRequest::where('requests.id', $req_id)
                ->join('users', 'users.id', '=', 'requests.user_id')
                ->select('requests.*', 'users.phone')
                ->first();

            if ($RequestInfo->step < 5) {
                $contract = $RequestInfo->contract;
                $sendsms = false;
                $oldstep = $RequestInfo->step;
                if ($RequestInfo->step < 0 && $RequestInfo->step > -100) {
                    $newstep = $RequestInfo->step * -1;
                    $oldstep = $oldstep * -1;
                } else {
                    $newstep = $RequestInfo->step + 1;
                    if ($RequestInfo->step == 4) {
                        $newstep = 4;
                    }
                }

                $priceperunit_new = str_replace('٬', '', $request->input('priceperunit'));
                $priceperunit_new = str_replace(',', '', $priceperunit_new);

                if ($contract != null && is_array($contract)) {
                    if ($contract['text'] != $request->input('contract')) {
                        $sendsms = true;
                        $contract = [
                            'text' => $request->input('contract'),
                            'user_id' => Auth::id(),
                            'date' => Jalalian::now()->format('Y/m/d H:i:s'),
                            'pricetotal' => $request->input('price'),
                            'priceperunit' => $priceperunit_new,
                            'isAccepted' => false,
                            'acceptedDate' => '',
                            'lastStep' => $oldstep
                        ];

                        $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;
                        $newstep = 2;
                    }
                } else if ($contract == null) {
                    $sendsms = true;
                    $contract = [
                        'text' => $request->input('contract'),
                        'user_id' => Auth::id(),
                        'date' => Jalalian::now()->format('Y/m/d H:i:s'),
                        'pricetotal' => $request->input('price'),
                        'priceperunit' => $priceperunit_new,
                        'isAccepted' => false,
                        'acceptedDate' => '',
                        'lastStep' => null
                    ];
                    $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->contract = $contract;

                if ($request->input('transportation') > 0) {
                    $transporterInfo = User::find($request->input('transportation'));
                    if ($RequestInfo->transportation == null) {
                        $userreq_data = [
                            'user_id' => $request->input('transportation'),
                            'request_id' => $req_id
                        ];
                        $userReq = WorkReq::create($userreq_data);

                        $transport = [
                            'user_id' => $request->input('transportation'),
                            'name' => $transporterInfo->first_name . ' ' . $transporterInfo->last_name,
                            'price' => str_replace(',', '', $request->input('transportprice')),
                            'pricetotal' => $request->input('priceTrans'),
                            'date' => Jalalian::now()->format('Y/m/d H:i:s')
                        ];

                        $RequestInfo->transportation = $transport;

                        $stepInfo = $RequestInfo->step_info;

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

                        $stepInfo[] = [
                            'action' => 'تعیین راننده: ' . $transporterInfo->first_name . ' ' . $transporterInfo->last_name,
                            'user_id' => Auth::id(),
                            'date' => Jalalian::now()->format('Y/m/d H:i:s')
                        ];

                        $RequestInfo->step_info =  $stepInfo;
                    } else if ($RequestInfo->transportation['user_id'] != $request->input('transportation')) {

                        WorkReq::where('user_id', $RequestInfo->transportation['user_id'])
                            ->where('request_id', $req_id)
                            ->take(1)->delete();

                        $userreq_data = [
                            'user_id' => $request->input('transportation'),
                            'request_id' => $req_id
                        ];
                        $userReq = WorkReq::create($userreq_data);

                        $transport = [
                            'user_id' => $request->input('transportation'),
                            'name' => $transporterInfo->first_name . ' ' . $transporterInfo->last_name,
                            'price' => str_replace(',', '', $request->input('transportprice')),
                            'pricetotal' => $request->input('priceTrans'),
                            'date' => Jalalian::now()->format('Y/m/d H:i:s')
                        ];

                        $RequestInfo->transportation = $transport;

                        $stepInfo = $RequestInfo->step_info;

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

                        $stepInfo[] = [
                            'action' => 'تعیین راننده: ' . $transporterInfo->first_name . ' ' . $transporterInfo->last_name,
                            'user_id' => Auth::id(),
                            'date' => Jalalian::now()->format('Y/m/d H:i:s')
                        ];

                        $RequestInfo->step_info =  $stepInfo;
                    }
                }

                $weight = $RequestInfo->weight;

                $weight['farmer'] = $request->input('weight') . ' ' . $request->input('weightUnit');

                $RequestInfo->weight = $weight;

                if ($request->input('steptype') == 1) {
                    $RequestInfo->step = $newstep;
                }

                $RequestInfo->save();

                if ($sendsms) {
                    $token = $this->generateToken($RequestInfo->user_id, $RequestInfo->id);
                    $link = route('farmer.contract', ['code' => $token]);
                    $link = str_replace("https://", "", $link);
                    $result = $this->smsService->sendPattern(
                        config('services.ippanel.default_from'),
                        '38qpvtms50c5x8b',
                        [$RequestInfo->phone],
                        [
                            'link' => $link,
                        ]
                    );
                }

                return redirect()->route('contractor.panel')->with('success', 'سفارش با موفقیت تغییر یافت.');
            }

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

    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 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;
        }
    }
}
