<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use Illuminate\Support\Facades\Auth;
use App\User;
use App\Models;
use Carbon\Carbon;
use App\ActivityLog;
use Illuminate\Support\Facades\Mail;
use App\Mail\ResetPassword;
use App\Models\Merchant;
use Session;
use Illuminate\Validation\Rule;


class LoginController extends Controller
{
    
    //Login page
    public function login_page(Request $request){
        // dd($request->headers->get('referer'));
        // session(['previous_page' => $request->headers->get('referer')]);
        // dd(session());
        return view('login.admin.index');
    }

    //Login user
    public function login_user(Request $request){

        $this->validate($request, ['email' => 'required', 'password' => 'required']);
        $email = $request->input('email');
        $password = $request->input('password');

        $login = auth()->attempt(['email' => $email, 'password' => $password]);

        if ($login) {
            $user = auth()->user();
            Auth::login($user, true);
            if (Auth::user()->deleted_at !== null) {
                return redirect()->back()->with('login-error', 'Account Suspended!');
            }

            $desc = [
                'title'=>'Login',
                'data'=>$user->name,
                'type'=>'login',
            ];
    
            $activity = new ActivityLog;
            $activity->user_id = Auth::user()->id;
            $activity->user_type = 'admin';
            $activity->description = json_encode($desc);
            $activity->save();

            return redirect(url('admin'));
        } 
        else {

            return redirect()->back()->with('login-error', 'Email/Password incorrect!');
        }
    }

    //Logout User
    public function logout(){

        auth()->logout();
        return redirect()->to('/login');

    }

    //Add user
    public function add_user(){

        $password = bcrypt('kweku20');

        $user = new User;
        $user->name = 'Kweku Debrah';
        // $user->lastname = 'Debrah';
        $user->email='kweku.debrah.emma@gmail.com';
        $user->password = $password;

        $save = $user->save();

    }
    public function show_merchant_register(){

        $data = [
            'page_title' => 'Merchant Registration',

        ];

        return view('login.merchant.register', $data);
    }
    public function merchant_register(Request $request){

        // $this->validate($request, [
        //     'fullname' => 'required',
        //     'phone'=> 'required|unique:merchants,phone',
        //     'language' => 'required'
        // ]);

        $request->validate([
            'fullname' => 'required',
            'phone'=> 'required|unique:merchants,phone',
            // 'language' => 'required',
            'country_iso' => 'required', Rule::in(['MW', 'ZM'])
        ], [
            'country_iso.exists' => 'Sorry, we do not currently support accounts from this country.',
        ]);
        $merchant_arr = $request->except('_token');
        /*
        $phone = $this->validatePhoneNumber($request->phone);
        if ($phone == false) {
            Session::flash('error_message', 'Invalid phone number format. Check and try again');
            return redirect()->back()->withInput();
        }
        */
        //todo : make the currency and country dynamic
        $country = ($request->country_iso == 'MW') ? "MALAWI" : 'ZAMBIA';  
        $currency = ($request->country_iso == 'MW') ? "MWK" : 'ZMW';        
        $phone = str_replace('+', '', $request->phone);
        $merchant_arr['phone'] = $phone;
        $merchant_arr['language'] = 'english';
        $merchant_arr['country'] = $country;
        $merchant_arr['currency'] = $currency;
        $result = Models\Merchant::create($merchant_arr);

        if ($result == null) {
            Session::flash('error_message', 'Your request could not be handled at this time. Try again later');
            return redirect()->back()->withInput();
        }
        return redirect('merchant/register-success');
    }
    public function register_success(){
        $data = ['page_title' => 'Merchant Sign Successful'];
        return view('login.merchant.register-success',$data);
    }
    public function register_page(Request $request){

        // $email = $request->input('email');

        // $user = User::where('email', $email)->first();

        // if ($user== null) {
           
        //     abort(404);
        // }

        $data = [
            // 'user'=>$user,
        ];
        return view('login.register', $data);
    }

    public function reset_password(Request $request){

        $validator = Validator::make($request->all(), [
            'user' => 'required',
            'password'=>'required',
            'cpassword'=>'required',            
        ]);

        if($validator->fails()){

            return redirect()->back()->with('login-error', 'Enter required data!');

        }

        if ($request->input('password') !== $request->input('cpassword')) {
            
            return redirect()->back()->with('login-error', 'Password dont Match!');

        }

        $user = $request->input('user');
        $password = $request->input('password');

        $user = User::where('id',$user)->update([
            'password'=>bcrypt($password),
        ]);

        return redirect()->to('/login')->with('login-success', 'Password Changed Successfully, Login to continue');



    }

    public function forgot_page(){

        return view('login.forgot');

    }

    public function sendResetMail(Request $request){
        
        // dd($request->all());

        $validator = Validator::make($request->all(), [

            'email' => 'required',
        
        ]);

        if($validator->fails()){

            return redirect()->back()->with('login-error', 'Enter required data!');

        }

        $email = $request->input('email');

        $user = User::where('email', $email)->first();

        if ($user == null ) {
            
            return redirect()->back()->with('login-error', 'Email Doesnt Exist!');


        }

        $newUser = [

            'name' => $user->name,
            'email' => $email,

        ];

        Mail::to($email)->send(new ResetPassword($newUser));

        return redirect()->to('/confirm-mail');

    }

    public function confirmMail()
    {
        return view('login.confirm');
    }

    /**
     * Merchant Login Section
     */

    public function merchant_login_page(){

        return view('login.merchant.index');

    }

    public function merchant_login(Request $request){
        $request->validate([
            'phone_number' => 'required|string',
            'pin' => 'required|string',
            'country_iso' => 'required', Rule::in(['MW', 'ZM'])
        ], [
            'country_iso.exists' => 'Sorry, we do not currently support accounts from this country.',
        ]);

        // if($validator->fails()){
        //     return redirect()->back()->with('login-error', 'Phone Number/PIN is required!');
        // }
        /*
        $phone_number = $this->validatePhoneNumber($request->phone_number);
        
        if($phone_number == false){
            return redirect()->back()->with('login-error', 'Phone Number/PIN is incorrect!');
        }
        */
        // $phone_number = $request->input('phone_number'); | use hashing
        $pin = md5($request->input('pin'));
        // dump($request->all());
        
        $phone_number = str_replace('+', '', $request->phone_number);

        $merchant = Merchant::where('phone', $phone_number)->where('pin', $pin)->first();
        // dd($merchant);
        if($merchant == null){
            return redirect()->back()->with('login-error', 'Phone Number/PIN incorrect!');
        }
        session(['merchant' => $merchant]);
        return redirect()->to('merchant/landing');
    }




    public function merchant_logout(){

        session(['merchant' => null]);

        // return redirect()->to('/merchant/login');
        return redirect()->to('/');
    }

    public function checkSupportedCountry(Request $request){
        $request->validate([
            'iso_code' => 'required|string|size:2'
        ]);

        $isoCode = strtoupper($request->iso_code);
        //todo retrieve this from the DB later
        // $isSupported = DB::table('supported_countries')->where('iso_code', $isoCode)->exists();

        $supported_arr = ['MW', 'ZM'];

        if (in_array($isoCode, $supported_arr)) {
            return response()->json(['supported' => true]);
        } else {
            return response()->json([
                'supported' => false,
                'message' => 'Sorry, we currently do not support accounts from this country.'
            ]);
        }
    }
    
    
  
    
    
  
   


    
}
