<?php

namespace App\Http\Controllers\Api\v1;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use App\EmailTemplate;
use App\EmailQueue;
use App\Manager;
use App\UserGroup;
use App\GroupPermission;
use App\Permission;
use App\Organization;
use App\SubscriptionPlans;
use App\ManagerPlan;


use App\Employee;

/**
 * User
 */
class UserController extends Controller
{

    /**
     *
     * @author     Ketan Patel <ketan.patel@brainvire.com>
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login', 'resetPassword', 'forgotPassword']]);
    }

    /**
     *
     * @author     Ketan Patel <ketan.patel@brainvire.com>
     * @return userobject
     */
    public function login(Request $request)
    {
        $this->validate($request, [
            'email' => 'required',
            'password' => 'required'
        ]);

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

        $user_delete_email = $request->input('email') . '_deleted';

        $user_delete = User::withTrashed()->where(['email' => $user_delete_email])->where('role', '!=', 'ROLE_EMPLOYEE')->first();

        if ($user_delete) {
            return response()->json(['status' => 'fail', 'message' => MANAGER_DELETE]);
        }
        if ($user) {
            if ($user->role == 'ROLE_EMPLOYEE') {
                $user = User::where('email', $request->input('email'))->where('role', 'ROLE_MANAGER')->first();
                if (!$user) {
                    return response()->json(['status' => 'fail', 'message' => LOGIN_NOT_ALLOWED]);
                }
            }
            if ($user->role != 'ROLE_ADMIN' && $user->role != 'ROLE_SUPER_ADMIN' && $user->role != 'ROLE_MANAGER') {
                return response()->json(['status' => 'fail', 'message' => LOGIN_NOT_ALLOWED]);
            }
            if (($user->role != 'ROLE_ADMIN' && $user->role != 'ROLE_SUPER_ADMIN') && ($user->status === 2 || $user->status === 0)) {
                return response()->json(['status' => 'fail', 'message' => ACC_BLOCKED]);
            }
            // if ($user->role == 'ROLE_MANAGER' && $user->plan == null) {
            //     return response()->json(['status' => 'fail', 'message' => PURCHASE_PLAN]);
            // }


            if (Hash::check($request->input('password'), $user->password)) {
                
                $baseUrl = url();
                $tokenData = array();
                $clientId = CLIENT_ID;
                $clientSecret = CLIENT_SECRET;
                $grantType = GRANT_TYPE;
                $sitePath = $baseUrl;
                $callURL = $sitePath . '/oauth/token';
                $params = array(
                    'client_id' => $clientId,
                    'username' => $user->email,
                    'password' => $request->input('password'),
                    'client_secret' => $clientSecret,
                    'grant_type' => $grantType
                );

                /* cURL call for getting the access token */
                $helperobj = new \App\CommonHelper();
                $curlResponse = $helperobj->callCurl($callURL, $params);
                $httpCode = $curlResponse['code'];
                $curlOutput = $curlResponse['output'];
                if ($httpCode == 200) {
                    $tokenData = json_decode($curlOutput, true);
                } else {
                    return response()->json(['status' => 'fail', 'message' => SOMETHING_WENT_WRONG]);
                }
                $user->fail_attempt = 0;
                $user->save();
                $userId = $user->id;
                $userEmail = $user->email;
                $userName = $user->name;
                $role = $user->role;
                $orgId = 0;
                $stripeCustId = 0;
                $fbInfo = 'No';
                $achBankVerified = '';
                $org = Manager::where('user_id', $userId)->first();

                if (!empty($org)) {
                    $orgId = $org->organization_id;
                    $stripeCustId = $org->stripe_cust_id;
                    $achBankVerified = $org->ach_bank_verified;
                    if ($org->facebook_token != null) {
                        $fbInfo = 'Yes';
                    }
                }
                $permissionArr = $this->getPermission($user);
                if ($user->role == "ROLE_MANAGER") {
                    if ($user->first_login == 0) {
                        $user->first_login = 1;
                    } elseif ($user->first_login == 1) {
                        $user->first_login = 2;
                    }
                    $user->save();
                }

                $plan = ManagerPlan::where('manager_id', $user->id)->first();


                if ($plan) {
                    $status_plan = '1';
                    $planId = '';
                } else {
                    $status_plan = '0';
                    $planId = $user->plan_id;
                }
                $returnArray = array(
                    'id' => $userId,
                    'organization_id' => $orgId,
                    'name' => $userName,
                    'email' => $userEmail,
                    'role' => $role,
                    'passcode' => $user->passcode,
                    'first_login' => $user->first_login,
                    'fbInfo' => $fbInfo,
                    'permissionArr' => $permissionArr,
                    'stripe_cust_id' => $stripeCustId,
                    'ach_bank_verified' => $achBankVerified,
                    'tokenData' => $tokenData,
                    'status_plan' => $status_plan,
                    'plan_id' => $planId,
                    'is_sycle_profile' => $user->is_sycle_profile
                );
                return response()->json(['status' => 'success', 'data' => $returnArray]);
            } else {
                $failAttempt = $user->fail_attempt;
                if ($failAttempt >= 2) {
                    $user->status = 2;
                }
                $user->fail_attempt = $failAttempt + 1;
                $user->save();
                return response()->json(['status' => 'fail', 'message' => INVALID_CREDENTIALS]);
            }
        } else {
            return response()->json(['status' => 'fail', 'message' => INVALID_CREDENTIALS]);
        }
    }

    /**
     *
     * @author     Ketan Patel <ketan.patel@brainvire.com>
     * @return userobject
     */
    public function resetPassword(Request $request)
    {
        $this->validate($request, [
            'token' => 'required',
            'password' => 'required',
        ]);

        $user = User::where('password_token', $request->input('token'))->first();
        if ($user) {
            $expiryDate = 0;
            $dateTime = new \DateTime();
            $currentDateTime = strtotime($dateTime->format('Y-m-d H:i:s'));
            $username = $user->name;

            if ($user->expire_on != '') {
                $expiryDate = strtotime($user->expire_on);
            }

            if ($expiryDate < $currentDateTime) {
                return response()->json(['status' => 'fail', 'message' => TOKEN_EXPIRED]);
            } else {
                $newPass = Hash::make($request->input('password'));
                $user->password = $newPass;
                $user->password_token = null;
                $user->save();
                $link = ANGULARURL . 'forgot-password';
                $body = EmailTemplate::where('slug', 'PASSWORD_CHANGED')->first();
                if (!empty($body)) {
                    $organization = Organization::where('user_id', $user->id)->first();
                    if ($organization) {
                        $helperobj = new \App\CommonHelper();
                        $docUrl = $helperobj->publicPath();

                        if ($organization->organization_pic != "") {
                            $image = $docUrl . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
                            if (!file_exists($image)) {
                                $image = ANGULARURL . 'assets/img/PU-logo.png';
                            } else {
                                $image = url() . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
                            }
                        } else {
                            $image = ANGULARURL . 'assets/img/PU-logo.png';
                        }
                    } else {
                        $image = ANGULARURL . 'assets/img/PU-logo.png';
                    }
                    $date = new \DateTime();
                    $mailDate = $date->format('F d, Y');
                    $userEmail = $user->email;
                    $tmp = str_replace("##USER_NAME##", $username, $body['description']);
                    $tmp1 = str_replace("##SUPPORT_MAIL##", SUPPORT_MAIL, $tmp);
                    $tmp2 = str_replace("##MAIL_DATE##", $mailDate, $tmp1);
                    $tmp3 = str_replace("##LOGO##", $image, $tmp2);
                    $tmp4 = str_replace("##YEAR##", date('Y'), $tmp3);
                    $data['html'] = str_replace("##RESET_PASSWORD_LINK##", $link, $tmp4);
                    $subject = str_replace("##USER_NAME##", $organization->name, $body['subject']);

                    $emailQueue = new EmailQueue();
                    $emailQueue->type = TYPE_RESET;
                    $emailQueue->mail_subject = $subject;
                    $emailQueue->mail_to = $userEmail;
                    $emailQueue->mail_from = FROM_IN_MAIL;
                    $emailQueue->mail_body = $data['html'];
                    $emailQueue->is_send = 0;
                    $ddf = $date->format('Y-m-d H:i:s');
                    $emailQueue->created = $ddf;
                    $emailQueue->save();
                }

                return response()->json(['status' => 'success', 'message' => PASS_RESET]);
            }
        } else {
            return response()->json(['status' => 'fail', 'message' => INVALID_TOKEN]);
        }
    }

    /**
     *
     * @author     Ketan Patel <ketan.patel@brainvire.com>
     * @return userobject
     */
    public function forgotPassword(Request $request)
    {
        $this->validate($request, [
            'email' => 'required',
        ]);

        $user = User::where('email', $request->input('email'))->first();
        if ($user) {
            if ($user->status === 2) {
                return response()->json(['status' => 'fail', 'message' => ACC_BLOCKED]);
            }

            $username = $user->name;
            $email = $user->email;
            $user->password_token = str_random(60);
            $date = new \DateTime();
            $oneDay = $date->modify('+1 day');
            $expiryDate = $oneDay->format('Y-m-d H:i:s');
            $user->expire_on = $expiryDate;

            if ($user->save()) {
                $link = ANGULARURL . 'reset-password?token=' . $user->password_token;
                $body = EmailTemplate::where('slug', 'RESET_PASSWORD')->first();

                if (!empty($body)) {
                    $organization = Organization::where('user_id', $user->id)->first();
                    if ($organization) {
                        $helperobj = new \App\CommonHelper();
                        $docUrl = $helperobj->publicPath();

                        if ($organization->organization_pic != "") {
                            $image = $docUrl . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
                            if (!file_exists($image)) {
                                $image = ANGULARURL . 'assets/img/PU-logo.png';
                            } else {
                                $image = url() . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
                            }
                        } else {
                            $image = ANGULARURL . 'assets/img/PU-logo.png';
                        }
                    } else {
                        $image = ANGULARURL . 'assets/img/PU-logo.png';
                    }
                    $tmp = str_replace("##USER_NAME##", $username, $body['description']);
                    $tmp1 = str_replace("##SUPPORT_MAIL##", SUPPORT_MAIL, $tmp);
                    $tmp2 = str_replace("##LOGO##", $image, $tmp1);
                    $tmp3 = str_replace("##YEAR##", date('Y'), $tmp2);
                    $data['html'] = str_replace("##RESET_PASSWORD_LINK##", $link, $tmp3);
                    $subject = str_replace("##USER_NAME##", $organization ? $organization->name : '', $body['subject']);

                    $emailQueue = new EmailQueue();
                    $emailQueue->type = TYPE_FORGOT;
                    $emailQueue->mail_subject = $subject;
                    $emailQueue->mail_to = $email;
                    $emailQueue->mail_from = FROM_IN_MAIL;
                    $emailQueue->mail_body = $data['html'];
                    $emailQueue->is_send = 0;
                    $date = new \DateTime();
                    $ddf = $date->format('Y-m-d H:i:s');
                    $emailQueue->created = $ddf;
                    $emailQueue->save();
                }

                return response()->json(['status' => 'success', 'message' => RESET_LINK_SEND]);
            } else {
                return response()->json(['status' => 'fail', 'message' => SOMETHING_WENT_WRONG]);
            }
        } else {
            return response()->json(['status' => 'fail', 'message' => EMAIL_NOT_FOUND]);
        }
    }

    /**
     *
     * @author     Ketan Patel <ketan.patel@brainvire.com>
     * @return userobject
     */
    public function index()
    {
        $users = DB::table('users as u')
                ->select('u.id', 'u.name', 'u.email', 'u.passcode', 'u.mobile', 'u.created_at', 'sp.name as plan', 'u.status', 'u.deleted_at', 'og.id as org_id', 'og.name as org_name', 'u.is_sycle_profile', DB::raw('COUNT(fb.id)as total_send_link'), DB::raw('IFNULL(SUM(fbsl.is_clicked_count),0)as total_link_click_count'))
                ->Where('u.role', '=', 'ROLE_MANAGER')
                ->Where('u.deleted_at', '=', null)
                ->leftJoin('subscription_plans as sp', 'sp.id', '=', 'u.plan')
                ->leftJoin('organizations as og', 'og.user_id', '=', 'u.id')
                ->leftJoin('feedback as fb', 'fb.organization_id', '=', 'og.id')
                ->leftJoin('feedback_send_link_log as fbsl', 'fbsl.feedback_id', '=', 'fb.id')
                ->groupBy('og.id')
                ->orderBy('u.id', 'desc')
                ->get();
        return response()->json($users);
    }

    /**
     * Return the path to public dir
     * @param null $path
     * @return string
     */
    public function publicPath($path = null)
    {
        return rtrim(app()->basePath('public/' . $path), '/');
    }

    public function destroy($rid)
    {
        $user = User::find($rid);

        if (!$user) {
            return response()->json(['status' => 'fail', 'message' => RECORD_NOT_FOUND]);
        }

        $user_email = $user->email . '_deleted';

        $update_data = User::where('id', $user->id)->update(array('email' => $user_email));

        $organization = Organization::select('id', 'name')->where('user_id', $rid)->first();

        $sub_plan = ManagerPlan::where('manager_id', $rid)->where('status', 'current')->first();

//         if($sub_plan)
//        {
//            $update_plan = ManagerPlan::where('manager_id',$rid)->where('status','current')->update(array('status' =>'deleted'));
//        }

        if ($organization) {
            $org_name = $organization->name . '_deleted';

            $update_org = Organization::where('user_id', $rid)->update(array('name' => $org_name));

            $employee = Employee::where('organization_id', $organization->id)->select('user_id')->get();

            if (count($employee) > 0) {
                foreach ($employee as $key => $value) {
                    $emp_user = User::select('id', 'email')->where('id', $value->user_id)->first();

                    $emp_email = $emp_user->email . '_deleted';

                    $emp_update = User::where('id', $value->user_id)->update(array('email' => $emp_email, 'status' => 2, 'deleted_at' => date('Y-m-d h:i:s')));

                    $emp_update_data = DB::table('employees')->where('user_id', $value->user_id)->update(array('status' => 'deleted'));

                    $login_data = DB::table('oauth_access_tokens')->where('user_id', $value->user_id)->first();

                    if ($login_data) {
                        DB::table('oauth_access_tokens')
                                ->where('user_id', $value->user_id)
                                ->update([
                                    'revoked' => '1',
                                    'expires_at' => Carbon::now()->subDays(400),
                                ]);
                    }
                }
            }
        }

        $user->status = 2;
        $user->delete();

        $plan = ManagerPlan::where('manager_id', $rid)->get()->where('status', 'current')->first();

        if ($plan && $user->is_sycle_profile == 0) {
            $subscriptionId = $plan->subscription_id;
            $subscription = \Stripe\Subscription::retrieve($subscriptionId);
            $subscription->cancel();

            $plan->status = 'canceled';
            $date = new \DateTime();
            $plan->expire_on = $date->format('Y-m-d');
            $plan->save();
        }


        //Revoke users

        return response()->json(['status' => 'success', 'message' => USER_DELETED]);
    }

    public function getPermission($user)
    {

        $userGroup = UserGroup::where('user_id', $user->id)->first();
        $permCode = array();
        if ($userGroup) {
            $groupPermission = GroupPermission::where('group_id', $userGroup->group_id)->get();
            foreach ($groupPermission as $group) {
                $permission = Permission::find($group->permission_id);
                array_push($permCode, $permission->code);
            }
        }
        return $permCode;
    }
}
