<?php

namespace App\Http\Controllers\Transporter;

use App\Http\Controllers\Controller;
use App\Http\Requests\MelliCodeRequest;
use App\Models\AppRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Morilog\Jalali\Jalalian;

class UserController extends Controller
{
    public function delivery($id)
    {
        $RequestInfo = AppRequest::where('requests.id', $id)
            ->where('requests.step', 4)
            ->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();
        if ($RequestInfo !== null) {
            return view('transporter.delivery', compact('RequestInfo'));
        }
        return view('transporter.index');
    }

    public function accept(MelliCodeRequest $request)
    {
        $req_id = $request->input('requestId');
        $mellicode = $request->input('melli_code');
        $weight = $request->input('weight');
        $unit = $request->input('unit');

        $RequestInfo = AppRequest::where('requests.id', $req_id)
            ->join('users', 'users.id', 'requests.user_id')
            ->where('users.melli_code', $mellicode)
            ->select('requests.*')->first();
        if ($RequestInfo !== null) {
            if ($weight !== null) {
                $oldweight = $RequestInfo->weight;
                $oldweight['transporter'] = $weight . ' ' . $unit;
                $RequestInfo->weight = $oldweight;
            }
            $RequestInfo->step = 5;

            $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('transporter.panel')->with('success', 'تحویل با موفقیت ثبت گردید');
        }

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