<?php

namespace App\Http\Controllers\Reseller;

use Throwable;
use Carbon\Carbon;
use App\Models\Reseller;
use App\Services\SmsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;

class LoginController extends Controller
{
    public function register_reseller(Request $request)
    {
        $data = $request->validate([
            'name' => 'required',
            'company_name' => 'required',
            'email' => 'required|unique:resellers',
            'phone' => 'required|unique:resellers|digits:11',
            'address' => 'required',
            'refer_id' => 'nullable',
            'password' => 'required|min:8|confirmed',
        ]);
        //check refer id
        if (!empty($data['refer_id'])) {
            $is_exist = Reseller::where('username', $data['refer_id'])->first();
            if (empty($is_exist)) {
                return response()->json([
                    'status' => 'invalid_referred_id',
                    'message' => 'This refer id is not valid',
                ]);
            }
        }


        DB::beginTransaction();
        try {
            $r_id = Reseller::max('id') + 222;
            $data['username'] = 'dropshipping' . $r_id;
            $data['status'] = 0;
            $data['password'] = Hash::make($request->password);
            if ($request->hasFile('logo')) {
                $logo_image = $request->file('logo')->store('images/logo', 'public');
                $data['logo'] = $logo_image;
            }
            Reseller::query()->create($data);

            DB::commit();
            return response()->json([
                'status' => 'OK',
                'message' => 'successfully registered, our support team will contact with you soon',
            ]);
        } catch (Throwable $th) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => $th->getMessage(),
            ]);
        }
    }

    //function for login reseller
    public function check_login(Request $request)
    {
        $validateData = $request->validate([
            'phone' => 'required',
            'password' => 'required',
        ]);

        $credential = [
            'phone' => $request->phone,
            'password' => $request->password,
            'status' => '1',
        ];

        if (Auth::guard('reseller')->attempt($credential)) {
            Session::put('reseller', Auth::guard('reseller')->user());
            $reseller = Reseller::where('phone',$request->phone)->first();
            $reseller->last_login_date = Carbon::now();
            $reseller->save();
            return response()->json([
                'status' => true,
                'reseller' => Auth::guard('reseller')->user(),
                'reseller_token' => Hash::make($request->password),
                'message' => 'সফল ভাবে লগইন হয়েছে',
            ]);
        } else {
            $reseller = Reseller::where('phone',$request->phone)->first();
            if(!empty($reseller) && $reseller->status == 0){
                return response()->json([
                    'status' => 'inactive',
                    'message' => 'আপনার অ্যাকাউন্ট এখন ইনএক্টিভ আছে। খুব শীঘ্রই আমাদের প্রতিনিধি আপনার তথ্যাবলী ভ্যারিফাই করে এক্টিভ করে দিবে। এক্টিভ করার পর আপনি আপনার দেওয়া মোবাইল নাম্বার এবং পাসওয়ার্ড দিয়ে লগইন করে ব্যবসায়িক কার্যক্রম শুরু করতে পারবেন। আমাদের সাথে যুক্ত হওয়ার জন্য আপনাকে ধন্যবাদ।'
                ]);
            }else{
                return response()->json([
                    'status' => 'Fail',
                    'message' => 'আপনার দেওয়া মোবাইল নাম্বার এবং পাসওয়ার্ড আমাদের রেকর্ডের সাথে মিলেনি',
                ]);
            }
        }
    }

    public function current_reseller_password_update(Request $request)
    {
        $validatedData = $request->validate([
            'old_password' => 'required ',
            'new_password' => 'required',
        ]);

        $reseller = session()->get('reseller');
        $merchant_current_password = $reseller->password;

        if (Hash::check($request->old_password, $merchant_current_password)) {
            if ($request->new_password == $request->old_password) {
                return response()->json([
                    'message' => "current password and new password can't be same ",
                ]);
            } else {
                $reseller->password = Hash::make($request->new_password);
                if ($reseller->save()) {
                    return response()->json([
                        'success' => 'OK',
                        'message' => 'password changed successfully',
                    ]);
                }
            }
        } else {
            return response()->json([
                'message' => 'current password is incorrect! ',
            ]);
        }
    }

    public function Reseller()
    {
        $reseller = Session()->get('reseller');

        return response()->json([
            'success' => 'OK',
            'reseller' => $reseller,
        ]);
    }

    public function checkSession()
    {
        if (Session::has('reseller')) {
            return response()->json([
                'session' => 'running',
                'reseller' => session()->get('reseller'),
            ]);
        } else {
            return response()->json([
                'session' => 'expired',
            ]);
        }
    }

    public function logout()
    {
        Auth::guard('reseller')->logout();
        session()->forget('reseller');
        return response()->json([
            'status' => 'OK',
            'message' => 'Logout successfully',
        ]);
    }

    public function send_reset_code(Request $request)
    {
        $data = $request->validate([
            'phone' => 'required|digits:11',
        ]);

        $reseller = Reseller::where('phone', $request->phone)->first();
        if (empty($reseller)) {
            return response()->json([
                'status' => 'ERROR',
                'message' => 'The mobile number does not match with our records',
            ]);
        } else {
            $code = rand(000000, 999999);
            DB::table('password_resets')->insert([
                'mobile_no' => $request->phone,
                'token' => Hash::make($code),
            ]);
            if($reseller->otp_sms == 1){
                (new SmsService())->SendResellerPasswordResetCode($request->phone, $code);
            }
            return response()->json([
                'status' => 'SUCCESS',
                'message' => 'Sent verification code on your mobile',
            ]);
        }
    }

    public function reseller_reset_code_verified(Request $request, $phone)
    {
        $phone = DB::table('password_resets')
            ->where('mobile_no', $phone)
            ->orderBy('id', 'desc')
            ->first();

        if (Hash::check($request->code, $phone->token)) {
            return response()->json([
                'status' => 'SUCCESS',
                'message' => 'Code Match',
            ]);
        } else {
            return response()->json([
                'status' => 'ERROR',
                'message' => 'Code Matching Error',
            ]);
        }
    }



    public function reseller_set_new_password(Request $request, $phone)
    {
        $data = $request->validate([
            'password' => 'required',
        ]);

        $reseller = Reseller::where('phone', $phone)->firstOrFail();
        $reseller->password = Hash::make($request->password);
        $reseller->save();

        return response()->json([
            'status' => 'SUCCESS',
            'message' => 'Password updated successfully',
        ]);
    }
}
