<?php

namespace App\Http\Controllers\Web;

use App\City;
use App\District;
use App\Http\Requests\UserProfileRequest;
use App\User;
use App\Verification;
use Illuminate\Support\Facades\Route;
use Illuminate\View\View;
use App\Helpers\ImageHelper;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\LoginRequest;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use App\Http\Requests\RegisterRequest;
use Illuminate\Contracts\View\Factory;
use App\Providers\RouteServiceProvider;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Illuminate\Validation\ValidationException;


class UserController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your Admin screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    // use AuthenticatesUsers;

    public $view = 'web.users.';

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::USER;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        // $this->middleware('guest')->except('logout');
    }

    /**
     * Show the login form.
     * @return Factory|View
     */
    public function login() :View
    {
        return view('web.login');
    }

    /**
     * Check login value in database and check verify code
     * @param LoginRequest $request
     * @return Factory|RedirectResponse|View
     */
    public function doLogin(LoginRequest $request)
    {
        $user = User::where('role', 'user')
            ->where('email', $request->email)
            ->orWhere('phone', $request->email)->withTrashed()->first();
        $status= true;
        $message= '';

        if (!$user){
            $status= false;
            $message= 'auth.failed';
        }

        if ($user && $user->deleted_at){
            $status= false;
            $message= 'users.user_disabled';
        }

        if ($status) {
            $status= Hash::check($request->password, $user->password) ? true : false;
            $message= 'auth.failed';
        }

        if (!$status) {
            return back()->withInput()->with('error', $message);
        }

        return $this->checkVerification($request);
    }


    /**
     * Show register form
     * @return View
     */
    public function register() :View
    {
        $regions = DB::table('regions')->cursor();

        session()->forget('agree');
        if (session()->has('agree') || request()->has('agree')){
            session()->put('agree', true);
            return view('web.register', compact('regions'));
        } else {
            $terms = DB::table('pages')
                ->where('pages.id', 1)
                ->join('page_descriptions', 'pages.id', 'page_descriptions.page_id')
                ->where('page_descriptions.language_id', currentLanguage()->id)->cursor()->first();

            return view('web.terms_and_conditions', compact('terms'));
        }
    }


    /**
     * Check Register values  for user and check verify code
     * @param RegisterRequest $request
     * @return View
     */
    public function doRegister(RegisterRequest $request)
    {
        // upload photo, bank_account_statement files
        $id_photo = ImageHelper::upload($request->id_photo);
        $bank = ImageHelper::upload($request->bank_account_statement);

        $meta = [
                'id_number' => $request->id_number,
                'general_info_score' => [
                    'first_name_en' => $request->first_name_en,
                    'second_name_en' => $request->second_name_en,
                    'third_name_en' => $request->third_name_en,
                    'last_name_en' => $request->last_name_en,
                    'first_name_ar' => $request->first_name_ar,
                    'second_name_ar' => $request->second_name_ar,
                    'third_name_ar' => $request->third_name_ar,
                    'last_name_ar' => $request->last_name_ar,
                ],
                'work_status_score' => [
                    'iban_number' => $request->iban_number,
                    'absher_phone' => $request->absher_phone,
                ],
                'monthly_income_score' => [
                    'work_status' => $request->work_status,
                    'work_status_other' => $request->work_status_other,
                    'monthly_income' => $request->monthly_income,
                    'monthly_income_other' => $request->monthly_income_other,
                    'age_period' => $request->age_period,
                    'education' => $request->education,
                ],
                'personal_info_score' => [
                    'current_liabilities' => $request->current_liabilities,
                    'current_liabilities_other' => $request->current_liabilities_other,
                    'social_status' => $request->social_status,
                    'health_status' => $request->health_status,
                    'health_status_other' => $request->health_status_other,
                ],
                'location_info_score' => [
                    'country' => $request->country,
                    'city' => $request->city,
                    'region' => $request->region,
                    'district' => $request->district,
                    'latitude' => $request->latitude,
                    'longitude' => $request->longitude,
                ],
                'address_info_score' => [
                    'street' => $request->street,
                    'postal_code' => $request->postal_code,
                    'building_info' => $request->building_info,
                ],
                'attachments_score' => [
                    'id_photo' => '/uploads/images/'.$id_photo,
                    'bank_account_statement' => '/uploads/images/'.$bank,
                ],
                'social_media_score' => [
                    'facebook_url' => $request->facebook_url,
                    'twitter_url' => $request->twitter_url,
                    'instagram_url' => $request->instagram_url,
                    'linkedin_url' => $request->linkedin_url,
                ],
        ];


        // Create new user
        $data= [
            'name' => $request->user_name,
            'email' => $request->email,
            // 'id_number' => $request->id_number,
            'phone' => $request->phone,
            'meta' => $meta,
            'register_steps' => implode(',', $request->register_steps),
            'password' => bcrypt($request->password),
        ];

        // dd($data);

        User::create($data);

        // check verify code
        return $this->checkVerification($request);

    }

    public function getLocationInfo(Request $request)
    {

        // $results = DB::table($request->table)->where($request->foreign_id, $request->id)->cursor();
        if ($request->table == 'cities'){
            $results = City::where($request->foreign_id, $request->id)->get();
        } elseif($request->table == 'districts'){
            $results = District::where($request->foreign_id, $request->id)->get();
        }
        $table_id = $request->table_id;
        return view($this->view.'get_location_info', compact('results', 'table_id'));
    }


    /**
     * Show forget password form
     * @return Factory|View
     */
    public function forgetPasswordForm() :View
    {
        return view($this->view.'forget_password_form');
    }

    /**
     * Generate forget password code
     * @param Request $request
     * @return RedirectResponse
     * @throws ValidationException
     */
    public function generateForgetPasswordCode(Request $request)
    {

        if (preg_match('/@/', $request->email)){
            $rules =  ['email' => 'required|email|exists:users,email'];
            $messages = ['email' => __('users.email')];
        } else {
            $rules =  ['email' => 'required|numeric|exists:users,phone'];
            $messages = ['email' => __('users.phone')];
        }


        $this->validate($request, $rules, [], $messages);

        // Check verify code
        $verification = VerificationController::verificationOperation($request);

        if ($verification){
            session()->put('email', $request->email);
            return redirect()->route('user.typeVerificationCodeForm');
        }

        return back()->withInput()->with('error', __('auth.failed'));
    }

    /**
     * Show code form
     * @return View
     */
    public function typeVerificationCodeForm() :View
    {
        $email = session('email') ?? '';
        return view($this->view.'forget_password_code_form', compact('email'));
    }


    /**
     * Show type new password form
     * @return Factory|View
     */
    public function newPasswordForm() :View
    {
        $code = session('code') ?? '';
        return view($this->view.'new_password_form', compact('code'));
    }

    /**
     * Type new password and reset it
     * @param Request $request
     * @return RedirectResponse
     * @throws ValidationException
     */
    public function typeNewPassword(Request $request)
    {
        $this->validate($request, [
            'password' => 'required|confirmed',
        ], [], ['password' => __('users.password')]);

        $code = Verification::where('code', $request->code)->first();
        $password = bcrypt($request->password);
        $code->user->update(['password' => $password]);
        $code->delete();
        session()->forget(['email', 'code']);
        return redirect()->route('user.login')->with('success', __('users.password_reset_success'));
    }


    /**
     * Resend code
     * @param Request $request
     * @return Factory|RedirectResponse|View
     */
    public function resendCode(Request $request)
    {
        $verification = VerificationController::verificationOperation($request);

        if ($verification){
            return response()->json(['message' => 'We send code, check your E-mail box']);
        }

    }


    /**
     * Check verification operation
     * @param $request
     * @return Factory|RedirectResponse|View
     */
    public static function checkVerification($request)
    {
        // dd($request->loop_id, $request->type, $request->phone, $request->email);
        $verification = VerificationController::verificationOperation($request);

        if ($verification){
            if ($request->ajax()){
                return response()->json(['message' => 'Register Successfully', 'url' => route('users.verification', $request->phone), 'status' => 1]);
            }
            return  view('web.verification.index', ['email' => $request->phone ?? $request->email]);

        }

        return back()->withInput()->with('error', __('auth.failed'));
    }

    public function verification($phone)
    {
        return  view('web.verification.index', ['email' => $phone]);
    }

    public function profile()
    {

        $user = Auth::user();
        $f_name = $user->meta['general_info_score']['first_name_'.getCurrentLocale()];
        $l_name = $user->meta['general_info_score']['last_name_'.getCurrentLocale()];
        // $name = $f_name.' '.$l_name;
        $name = $user->name;
        $city_id = $user->meta['location_info_score']['city'];

        // $loops= $user->loop_group_users()->with->get();
        $loops= $user->loop_groups()->groupby('loop_id')->with('loop')->get();

        $loops= $loops ? $loops->toArray() : [];
        // dd( $loops );

        $loopGroupUser= $user->loop_group_users()
        ->whereRaw("DATE_FORMAT(encashment_month,'%Y-%m-01') >= DATE_FORMAT(CURDATE(),'%Y-%m-01')")
        ->where('get_paid', 0)->first();
        $nearestEncashmentMonth= $loopGroupUser->encashment_month ?? '';

        $city = City::find($city_id);
        $city= $city? $city->{'name_'.getCurrentLocale()} : '';

        $address = $user->meta['address_info_score']['street'];
        $facebook = $user->meta['social_media_score']['facebook_url'];
        $twitter = $user->meta['social_media_score']['twitter_url'];
        $instagram = $user->meta['social_media_score']['instagram_url'];
        $phone = $user->phone;
        $photo = $user->photo ?? false;
        $about_me = $user->about_me ?? false;
        // dd( $facebook, parse_url($facebook));
        return view($this->view.'profile', compact( 'loops', 'nearestEncashmentMonth', 'name','city', 'address', 'facebook', 'twitter', 'instagram', 'phone', 'photo', 'about_me'));

    }

    public function editProfile()
    {
        $user = Auth::user();
        $f_name = $user->meta['general_info_score']['first_name_'.getCurrentLocale()];
        $l_name = $user->meta['general_info_score']['last_name_'.getCurrentLocale()];
        $name = $f_name.' '.$l_name;
        $city_id = $user->meta['location_info_score']['city'];
        $city = City::find($city_id);
        $city= $city? $city->{'name_'.getCurrentLocale()} : '';

        $address = $user->meta['address_info_score']['street'];
        $facebook = $user->meta['social_media_score']['facebook_url'];
        $twitter = $user->meta['social_media_score']['twitter_url'];
        $instagram = $user->meta['social_media_score']['instagram_url'];
        $phone = $user->phone;
        $photo = $user->photo ?? false;
        $about_me = $user->about_me ?? false;
        $regions = DB::table('regions')->cursor();
        return view($this->view.'profile_form', compact('regions','f_name', 'l_name', 'city', 'city_id', 'address', 'facebook', 'twitter', 'instagram', 'phone', 'photo', 'about_me'));
    }

    public function updateProfile(UserProfileRequest $userProfileRequest)
    {

    }



    /**
     * User logout
     * @return RedirectResponse|Redirector
     */
    public function logout() :RedirectResponse
    {
        Session::flush();
        Auth::logout();
        return redirect('/');
    }
}


