<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Customers;
use App\CustomerToken;
use Illuminate\Support\Str;
use Carbon\Carbon;
use DB;
use Mail;
use App\Helpers\Functions;
use App\EmailsResponders;

class ForgotPasswordController extends Controller {

    public function __construct() {
        //$this->middleware('auth:customers');
    }

    public function index() {

        if (!empty(auth('customers')->user())) {
            return redirect("/");
        }
        return view('front/forget_password');
    }

    public function change(Request $request) {


        $rules = [
            'email' => 'required|string|email',
        ];
        $input = $request->all();

        $message = [];
        $validator = Validator::make($input, $rules, $message);

        if ($validator->fails()) {

            return redirect()->back()->withErrors($validator->errors())->withInput();
        } else {

            $rand_token = Str::random(12);
            $customers = Customers::where("email", "=", $input['email'])->first();

            if (!empty($customers)) {

                $mytime = Carbon::now();

                if (empty($tokens)) {
                    DB::beginTransaction();
                    try {
                        $token = new CustomerToken();
                        $token->customer_id = $customers->id;
                        $token->token = $rand_token;
                        $token->created_at = $mytime->toDateTimeString();
                        $token->save();

                        DB::commit();
                        // all good
                    } catch (\Exception $e) {
                        DB::rollback();
                        // something went wrong
                    }
                } else {
                    DB::beginTransaction();
                    try {
                        $token_val = CustomerToken::find($tokens->customer_id);
                        $token_val->token = $rand_token;
                        $token_val->created_at = $mytime->toDateTimeString();
                        $token_val->save();

                        DB::commit();
                        // all good
                    } catch (\Exception $e) {
                        DB::rollback();
                        // something went wrong
                    }
                }




                $emailsResponders = EmailsResponders::where('Title', 'Forget Password')->first();

                $data["body"] = $emailsResponders->Content;
                $data["title"] = $emailsResponders->Title;
                $data["subject"] = $emailsResponders->Subject; // "Reset Your " . $replaces["Website_Name"] . " Account Password"


                $replaces["Email_Address"] = $customers->email;
                $replaces["First_Name"] = $customers->firstName;
                $replaces["rand_token"] = $customers->rand_token;
                $replaces["Website_Name"] = \URL::to('/');
                $replaces["URL"] = url('reset_password/' . $rand_token);

                $template = Functions::replaces($data, $replaces);

                $subject = $template['subject'];

                try {

                    Mail::send('front.emails.template', ['content' => $template["body"]], function ($m) use ($subject, $customers) {
                        $m->from(env("MAIL_FROM_ADDRESS"), env("MAIL_FROM_NAME"));
                        $m->to($customers->email, $customers->firstName);
                        $m->subject($subject);
                    });
                } catch (\Throwable $th) {
                    // throw $th;
                }

                return redirect("login")->with('reset_message', 'We have sent you an email to your registered email address that will allow you to change your password.');
            } else {
                return redirect()->back()->withErrors('Your email has not been found on our system. Please enter the email you used to register your account on our system.')->withInput();
            }
        }
    }

    public function resetPassword($key) {
        $tokenInfo = CustomerToken::where('token', $key)->first();
        if (!empty($tokenInfo)) {
            $data["customers"] = Customers::where("id", "=", $tokenInfo->customer_id)->first();
        } else {
            $data["customers"] = array();
        }

        return view('front/reset_password', $data);
    }

    public function reset(Request $request) {


        $rules = [
            'password' => 'required|min:6|confirmed',
                // 'confrim_password' => 'required|same:password',
        ];
        $input = $request->all();

        $message = [];
        $validator = Validator::make($input, $rules, $message);

        if ($validator->fails()) {

            return redirect()->back()->withErrors($validator->errors())->withInput();
        } else {

            unset($input['_token']);
            unset($input['confrim_password']);
            unset($input['password_confirmation']);

            $input["password"] = bcrypt($input["password"]);


            $customer = Customers::where('email', $input["email"])->update($input);


            return redirect("login");
        }
    }

}
