<?php

namespace App\Http\Controllers\Farmer;

use App\Http\Controllers\Controller;
use App\Http\Requests\RegisterRequest;
use App\Models\AppRequest;
use App\Models\User;
use App\Models\Farmer;
use App\Models\SMS;
use App\Services\IppanelService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Morilog\Jalali\Jalalian;

class UserController extends Controller
{
    protected $smsService;

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

    public function show()
    {
        return view('layouts.auth.auth');
    }

    public function register(RegisterRequest $request)
    {
        $user_inputs = [
            'username' => $request->input('melli_code'),
            'first_name' => $request->input('first_name'),
            'last_name' => $request->input('last_name'),
            'melli_code' => $request->input('melli_code'),
            'phone' => $request->input('phone'),
            'password' => $request->input('phone')
        ];
        $returned_user = User::create($user_inputs);

        $farmer_inputs = [
            'user_id' => $returned_user->id,
            'state' => $request->input('state'),
            'city' => $request->input('city'),
            'address' => $request->input('address'),
            'farm_name' => $request->input('farm_name'),
            'father_name' => $request->input('father_name')
        ];

        $returned_farmer = Farmer::updateOrCreate(
            ['user_id' => $returned_user->id],
            [
                'state' => $request->input('state'),
                'city' => $request->input('city'),
                'address' => $request->input('address'),
                'farm_name' => $request->input('farm_name'),
                'father_name' => $request->input('father_name')
            ]
        );
        if (Auth::attempt(['username' => $request->input('melli_code'), 'password' => $request->input('phone')], true)) {

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

            if ($request->has('isorder')) {
                $weight = [
                    'farmer' => $request->input('weight') . ' ' . $request->input('unit')
                ];

                if ($request->has('wantTransport')) {

                    $stepinfo = [];

                    $stepinfo[] = [
                        'action' => 'نیاز به راننده دارم',
                        'user_id' => Auth::id(),
                        'date' => Jalalian::now()->format('Y/m/d H:i:s')
                    ];

                    //wantTransport
                    $req_inputs = [
                        'user_id' => $returned_user->id,
                        'type' => 1,
                        'weight' => $weight,
                        'step' => 1,
                        'step_info' => $stepinfo
                    ];
                }
                else
                {
                    $req_inputs = [
                        'user_id' => $returned_user->id,
                        'type' => 1,
                        'weight' => $weight,
                        'step' => 1
                    ];
                }
                
                $row_request = AppRequest::create($req_inputs);

                if ($row_request instanceof AppRequest) {
                    return redirect()->route('farmer.panel');
                }
            } else {
                return redirect()->route('farmer.panel');
            }
        } else {
            return redirect()->route('login');
        }
    }

    public function sendsms(RegisterRequest $request)
    {
        try {
            $random_code = rand(10000, 99999);

            $verfication = SMS::firstOrNew(['phone' => $request->input('phone')]);
            $verfication->smscode = $random_code;
            $verfication->save();

            $result = $this->smsService->sendPattern(
                config('services.ippanel.default_from'),
                'nkijq9sdcwqwc02',
                [$request->input('phone')],
                [
                    'code' => $random_code,
                ]
            );

            if ($result['success']) {
                return response()->json([
                    'status' => true,
                    'message' => 'پیامک با موفقیت ارسال شد',
                    'data' => $result
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'error' => 'خطا در ارسال پیامک. لطفا دوباره تلاش کنید',
                    'details' => $result
                ], 500);
            }
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'error' => 'خطا در ارسال پیامک. لطفا دوباره تلاش کنید',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function checksms(RegisterRequest $request)
    {
        $verfication = SMS::firstwhere('phone', $request->input('phone'));

        if ($verfication->smscode == $request->input('smscode')) {
            return response()->json([
                'success' => true
            ]);
        } else {
            return response()->json([
                'error' => true
            ]);
        }
    }
}
