<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\PasswordReset;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use SoapClient;
use App\Facades\Sms\Sms;

class ForgotPasswordController extends Controller
{
    public function __construct()
    {
//        $this->middleware('throttle:3,1');
    }

    /*
     * Send Reset Code to Mobile methods
     */
    public function sendResetCodeMobile(Request $request)
    {
        $user = User::where('username', $request->username)->first();
        if ( !$user ) {
            return response()->json(['message' => 'کاربری با این نام کاربری وجود ندارد.'], 402);
        }

        if (PasswordReset::where('username', $request->username)->where('expired_at' ,'>=', Carbon::now())->first()) {
            return response()->json(['message' => 'دو دقیقه دیگر امتحان کنید.'], 402);
        }

        $create = PasswordReset::create([
            'username' => $request->username,
            'token' => Str::random(32),
            'code' => mt_rand(100000, 999999), //TODO: replace -> mt_rand(100000, 999999)
            'code_status' => 0,
            'expired_at' => Carbon::now()->addMinutes(2)
        ]);

        /// Send SMS
        $msg = 'کد اعتبار سنجی فراموشی رمز عبور: ' . $create->code . "\n سامانه جامع راهداری";
        Sms::sendSms($user->mobile, $msg);

        // $this->sms_sender($this->userMobile($request->username), $msg);

        return response()->json([
           'status' => 'success',
           'token' => $create->token,
        ]);
    }

    protected function userMobile($username)
    {
        $user = User::where('username', $username)->first();
        return $user->mobile;
    }


    /*
     * Get And Validate Code
     */

    public function getCodeMobile($token, Request $request)
    {
        $findWithToken = PasswordReset::where('token', $token)->get();

        foreach ($findWithToken as $item) {
            $validCode = $item->code;
        }

        if ($request->code == $validCode) {
            PasswordReset::where('token', $token)
                        ->where('expired_at', '>=' ,Carbon::now())
                        ->update(['code_status' => 1]);
            return response()->json([
               'message' => 'کد وارد شده درست میباشد',
               'token' => $token
            ]);
        }
        return response()->json([
            'message' => 'کد اشتباه میباشد.',
            'token' => $token
        ], 422);
    }


    /*
    *
    * Change Password Methods
    *
    */

    public function changePassword(Request $request, $token)
    {
        $this->validateCode($token);

        $request->validate($this->rules());

        $response = $this->resetPassword($this->getUser($token), $request->password);

        return $response
            ? $this->sendResetResponse($request, $response)
            : $this->sendResetFailedResponse($request, $response);
    }

    protected function resetPassword($userID, $password)
    {
        $user = User::find($userID);
        $user->password = Hash::make($password);
        return $user->save();
    }

    protected function rules()
    {
        return [
            'password' => 'required'
        ];
    }

    protected function getUser($token)
    {
        $getDataFromToken = PasswordReset::where('token', $token)->first();
        $user = User::where('username', $getDataFromToken->username)->first();
        return $user->id;
    }

    protected function validateCode($token)
    {
        if (PasswordReset::where('token', $token)->where('code_status', 0)->first()) {
            return response()->json(['message' => 'کد را وارد نکردید'], 402);
        } else {
            return PasswordReset::where('token', $token)
                ->where('code_status', 1)
                ->first();
        }
    }

    protected function sendResetResponse(Request $request, $response)
    {
        return response()->json([
            'success' => $response,
            'message' => 'پسورد با موفقیت تغییر یافت.'
        ], 200);
    }

    protected function sendResetFailedResponse(Request $request, $response)
    {
        return response()->json([
            'error' => $response
        ]);
    }

    // function sms_sender($mobile, $msg)
    // {
    //     $client=new SoapClient("http://sms1000.ir/webservice/smspro.asmx?WSDL");
    //     $result=$client->doSendSMS(
    //         array(
    //             'uUsername' => 'rmto',
    //             'uPassword' => 'Rahdari89',
    //             'uNumber' => '1000141',
    //             'uCellphones' => $mobile,
    //             'uMessage' => $msg,
    //             'uFarsi' => true,
    //             'uTopic' => false,
    //             'uFlash' => false
    //         )
    //     );
        
    //     //print_r($result);
    //     $x = $result->doSendSMSResult;
    //     return $x;
    // }
}