<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use App\Models\Admin\User;
use App\Models\Project\Otp_log;
use App\Models\Project\UserDetail;
use App\Models\Project\BusinessDetail;
use App\Models\Admin\Countries;
use App\Models\Admin\Cities;
use App\Models\Project\Expense_type;
use App\Models\Project\Expenses;
use App\Models\Project\Budget;
use App\Models\Project\Package;
use App\Models\Project\Subscription;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Carbon\Carbon;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Validator;
use App\helpers\Malath_SMS;
use App\Models\Admin\SmsHost;
use App\Models\Admin\SmsTemplate;
use App\Traits\ApiLanguageTrait;

class RegisterController extends Controller
{
    use ApiLanguageTrait;
    /*registere user*/
    public function register(Request $request)
    {
        $data = array();
        //$otp = 1234;
        $mobile = $request->mobile;
        $code = substr($mobile, 1);
        //$mobile = "966".$code;	
        /*	if (User::where('username', $request->username)->where('user_type', $request->type)->exists()) {
            $data['msg_en'] = array('text' => $this->__transEn('username_not_available'), 'cls' => 'text-danger');
                $data['msg_ar'] = array('text' => $this->__transAr('username_not_available'), 'cls' => 'text-danger');
	
            $data['status'] = 0;
		}else{*/
        $otp = random_int(1000, 9999);
        $otp = 1234;
        $post = new Otp_log;
        if ($request->type == 2) {
            $post->username = $request->username;
        } else {
            $post->username = $request->username;
        }

        $post->country = $request->country;
        $post->locale = $request->language;
        $post->mobile_no = $mobile;
        $post->otp = Hash::make($otp);
        $post->user_type = $request->type; //1 = user/2 = vendor
        $post->password = Hash::make($request->password);
        $post->status = 1;
        $post->type = 1;


        $msg = $post->save();
        if ($request->language == "en") {
            $template = SmsTemplate::where('slug', 'otp_english')->first();
        } else {
            $template = SmsTemplate::where('slug', 'otp_arabic')->first();
        }
        $message = $template->text;
        $message = str_replace('{{otp}}', $otp, $message);
        /*mobile sms sending api*/
        $host = SmsHost::where('is_default', '1')->first();
        if ($host->slug == "malath_sms_api") {
            $DTT_SMS    = new Malath_SMS($host->username, $host->secret, 'UTF-8');
            $Credits    = $DTT_SMS->GetCredits();
            $SenderName = $DTT_SMS->GetSenders();
            $CheckUser  = $DTT_SMS->CheckUserPassword();
            $SmS_Msg    = $message;
            $Originator = $host->mask;
            // $Send = $DTT_SMS->Send_SMS($mobile, $Originator, $SmS_Msg, $CheckUser);
        }


        /*$post = new User;
            $post->username = $request->username;
            $post->country = $request->country;
            $post->mobile = $request->mobile;
            $post->otp = Hash::make($otp);
            $post->user_type = $request->type; //1 = user/2 = vendor
            $post->password = Hash::make($request->password);
            $msg = $post->save();*/
        if ($msg) {
            // Auth::login($post);
            $data['user_id'] = $post->id;
            $data['msg_en'] = array('text' => $this->__transEn('goto_Otp_screen'), 'cls' => 'text-success');
            $data['msg_ar'] = array('text' => $this->__transAr('goto_Otp_screen'), 'cls' => 'text-success');
            $data['status'] = 1;
        } else {
            $data['msg_en'] = array('text' => $this->__transEn('server_error'), 'cls' => 'text-danger');
            $data['msg_ar'] = array('text' => $this->__transAr('server_error'), 'cls' => 'text-danger');
            $data['status'] = 0;
        }

        return $data;
    }



    /*businsess Registration in Detail to business detail table*/
    public function vendor_detail(Request $request)
    {
        $data = array();
        if ($request->apptype == "app") {
            $id = $request->user_id;
        } else {
            $id = Auth::id();
        }
        $new_name = "";
        $uniqid = Str::random(5);
        $id2 = "2";
        if ($request->has('logo') && !empty($request->input('logo'))) {
            $folderPath = "project/vendors/";
            $image_name = $id . '_' . $request->name . '_' . date('Y-m-d_H_i_s') . '.png';
            $file = $folderPath . $image_name;
            $image = base64_decode($request->logo);
        } else {
            $image_name = "no.png";
        }
        // if ($validation->passes()) {
        /* $photo = $request->file('logo');
            if ($photo) {
                $new_name = rand() . '.' . $photo->getClientOriginalExtension();
                $photo->move(base_path('images/vendors'), $new_name);
            }*/
        $post = new BusinessDetail;
        $post->name = $request->name;
        $post->type = $request->type;
        $post->lisence_no = $request->lisence;
        $post->ref_no = $request->ref_no;
        $post->insta_link = $request->insta;
        $post->twitter_link = $request->twitter;
        $post->website = $request->website;
        $post->whatsapp = $request->whatsapp;
        $post->location = $request->location;
        $post->location_lat = $request->location_lat;
        $post->location_lng = $request->location_lng;
        $post->vendor_status = 1;
        $post->logo = $image_name;
        $post->uid = $id;
        $post->qrcode =  $id . $uniqid . $id2;
        $post->business_type = $request->business_type;
        $msg = $post->save();
        if ($msg) {
            if ($request->has('logo') && !empty($request->input('logo'))) {
                file_put_contents($file, $image);
            }
            $data['status'] = 1;
            $data['msg_en'] = $this->__transEn('register_success');
            $data['msg_ar'] = $this->__transAr('register_success');
            $data['data'] = User::find($id);
        } else {

            $data['status'] = 0;
            $data['msg_en'] = $this->__transEn('register_fails');
            $data['msg_ar'] = $this->__transAr('register_fails');
        }
        return $data;
        /* } else {
            throw ValidationException::withMessages([
                'logo' =>[$validation->errors()->all()]
            ]);
        }*/
    }

    /*send user detail to user detail table*/
    public function user_detail(Request $request)
    {
        $data = array();
        if ($request->apptype == "app") {
            $id = $request->uid;
        } else {
            $id = Auth::id();
        }
        $request->validate([
            'name' => ['required'],
            'gender' => ['required'],
        ]);
        $uniqid = Str::random(5);
        $id2 = "1";
        $post = new UserDetail;
        $post->name = $request->name;
        $post->gender = $request->gender;
        $post->age = $request->age;
        $post->uid = $id;
        $post->qrcode =  $id . $uniqid . $id2;
        $msg = $post->save();
        if ($msg) {
            DB::table('budgets')->where('user_id', $id)->where('budget_type', 1)->update(array('budget_amount' => $request->salary_amount));
            $data['msg_en'] = array('text' => $this->__transEn('register_success'), 'cls' => 'text-success');
            $data['msg_ar'] = array('text' => $this->__transAr('register_success'), 'cls' => 'text-success');
            $data['status'] = 1;
        } else {

            $data['msg_en'] = array('text' => $this->__transEn('register_fails'), 'cls' => 'text-danger');
            $data['msg_ar'] = array('text' => $this->__transAr('register_fails'), 'cls' => 'text-danger');
            $data['status'] = 0;
        }
        return $data;
    }

    /*username checking*/
    public function username_check(Request $request)
    {
        $data = array();
        if (is_numeric($request->username)) {
            $data['msg_en'] = array('text' => $this->__transEn('only_digit_username'), 'cls' => 'text-danger');
            $data['msg_ar'] = array('text' => $this->__transAr('only_digit_username'), 'cls' => 'text-danger');
            $data['status'] = 0;
        } else {
            if (User::where('username', $request->username)->exists()) {
                $data['msg_en'] = array('text' => $this->__transEn('username_taken'), 'cls' => 'text-danger');
                $data['msg_ar'] = array('text' => $this->__transAr('username_taken'), 'cls' => 'text-danger');
                $data['status'] = 0;
            } else {
                $data['msg_en'] = array('text' => $this->__transEn('username_available'), 'cls' => 'text-success');
                $data['msg_ar'] = array('text' => $this->__transAr('username_available'), 'cls' => 'text-success');
                $data['status'] = 1;
            }
        }
        return $data;
    }
    /*Mobile checking*/
    public function mobile_check(Request $request)
    {
        $mobile = $request->mobile;
        // $code = substr($mobile, 1);
        //$mobile = "966".$code;	
        $data = array();
        if (User::where('mobile', $mobile)->where('user_type', $request->type)->exists()) {
            $data['msg_en'] = array('text' => $this->__transEn('mob_number_taken'), 'cls' => 'text-danger');
            $data['msg_ar'] = array('text' => $this->__transAr('mob_number_taken'), 'cls' => 'text-danger');
            $data['status'] = 0;
        } else {
            $data['msg_en'] = array('text' => $this->__transEn('mob_number_correct'), 'cls' => 'text-success');
            $data['msg_ar'] = array('text' => $this->__transAr('mob_number_correct'), 'cls' => 'text-success');
            $data['status'] = 1;
        }
        return $data;
    }

    public function otp_verify(Request $request)
    {
        $data = array();

        $user = Otp_log::where('id', $request->user_id)->where('status', 1)->where('type', 1)->orderBy('created_at', 'desc')->first();
        // = Otp_log::find($request->user_id);

        if (Hash::check($request->otp, $user->otp)) {
            $data['msg_en'] = array('text' => $this->__transEn('otp_verified'), 'cls' => 'text-success');
            $data['msg_ar'] = array('text' => $this->__transAr('otp_verified'), 'cls' => 'text-success');
            $post = new User;

            $post->username = $user->username;

            $post->email = $user->username . $user->user_type . Str::random(10) . '@sarfapp.com';

            $post->country = $user->country;
            $post->mobile = $user->mobile_no;
            $post->locale = $user->locale;
            //$post->otp = Hash::make($otp);
            $post->user_type = $user->user_type; //1 = user/2 = vendor
            $post->type = $user->user_type;
            $post->password = $user->password;
            if ($request->ios_device_id) {
                $post->ios_device_id =  $request->ios_device_id;
            } else {
                $post->android_device_id =  $request->android_device_id;
            }
            $msg = $post->save();

            $data['user_id'] = $post->id;
            $data['user_type'] = $post->user_type;
            if ($request->ios_device_id) {
                DB::table('users')->where('id', $request->user_id)->update(array('ios_device_id' => $request->ios_device_id));
            } else {
                DB::table('users')->where('id', $request->user_id)->update(array('android_device_id' => $request->android_device_id));
            }
            $data['status'] = 1;

            if ($user->user_type == 1) {
                $post1 = new Budget;
                $post1->budget_name = 'Salary';
                $post1->user_id = $post->id;
                $post1->budget_amount = 0;
                $post1->dated = Date('Y-m-d');
                $msg = $post1->save();
                $memberAry = Expense_type::where('type', 1)->where('status', 1)->pluck('id');
                $memberIds = str_replace('[', "", $memberAry);
                $members = str_replace(']', "", $memberIds);
                $memberAry2 = explode(',', $members);
                foreach ($memberAry2 as $key => $value) {
                    $post2 = new Expenses;
                    $post2->expense_type_id = $value;
                    $post2->user_id = $post->id;
                    $post2->budget_id = $post1->id;
                    $msg = $post2->save();
                }
                $day =  (string)DB::table('package')->where('type', 2)->where('status', 1)->first()->duration;
                $date2 = Date('Y-m-d');
                $newdate = date('Y-m-d', strtotime($date2 . ' + ' . $day . ' days'));
                $post3 = new Subscription;
                $post3->pkg_id = 1;
                $post3->user_id = $post->id;
                $post3->amount_paid = 0;
                $post3->start_date = Date('Y-m-d');
                $post3->end_date = $newdate;
                $msg = $post3->save();
            } else {
                $post1 = new Budget;
                $post1->budget_name = 'expenses';
                $post1->user_id = $post->id;
                $post1->budget_amount = 0;
                $post1->dated = Date('Y-m-d');
                $msg = $post1->save();
                $day =  (string)DB::table('package')->where('type', 2)->where('status', 1)->first()->duration;
                $date2 = Date('Y-m-d');
                $newdate = date('Y-m-d', strtotime($date2 . ' + ' . $day . ' days'));
                $post3 = new Subscription;
                $post3->pkg_id = 1;
                $post3->user_id = $post->id;
                $post3->amount_paid = 0;
                $post3->type = 3;
                $post3->start_date = Date('Y-m-d');
                $post3->end_date = $newdate;
                $msg = $post3->save();
            }
        } else {
            $data['msg_en'] = array('text' => $this->__transEn('otp_not_verified'), 'cls' => 'text-danger');
            $data['msg_ar'] = array('text' => $this->__transAr('otp_not_verified'), 'cls' => 'text-danger');
            $data['status'] = 0;
        }
        return ($data);
    }

    public function resend_opt(Request $request)
    {
        $data = array();
        // $otp = '1234';
        $otp = random_int(1000, 9999);
        $user = Otp_log::where('id', $request->user_id)->where('status', 1)->where('type', 1)->orderBy('created_at', 'desc')->first();
        // $user->otp = Hash::make($otp);
        //$msg = $user->save();
        if ($user) {
            $post = new Otp_log;
            $post->mobile_no = $user->mobile;
            $post->otp = Hash::make($otp);
            $post->status = 1;
            $post->user_id = $user->id;
            $post->type = 1;
            $msg = $post->save();

            $template = SmsTemplate::where('slug', 'otp_english')->first();
            $message = $template->text;
            $message = str_replace('{{otp}}', $otp, $message);

            $host = SmsHost::where('is_default', '1')->first();
            if ($host->slug == "malath_sms_api") {
                $DTT_SMS    = new Malath_SMS($host->username, $host->secret, 'UTF-8');
                $Credits    = $DTT_SMS->GetCredits();
                $SenderName = $DTT_SMS->GetSenders();
                $CheckUser  = $DTT_SMS->CheckUserPassword();
                $SmS_Msg    = $message;
                $Originator = $host->mask;
                $Send = $DTT_SMS->Send_SMS($user->mobile, $Originator, $SmS_Msg, $CheckUser);
            }

            $data['msg_en'] = $this->__transEn('otp_send');
            $data['msg_ar'] = $this->__transAr('otp_send');
            $data['status'] = 1;
        } else {
            $data['msg_en'] = $this->__transEn('otp_sending_fail');
            $data['msg_ar'] = $this->__transAr('otp_sending_fail');
            $data['status'] = 0;
        }
        return ($data);
    }

    public function country_list()
    {
        $data = array();
        $data['country_list_status'] = 1;
        $data['country_list'] = Countries::where('status', '1')->get();
        return ($data);
    }
    public function city_list()
    {
        $data = array();
        $data['city_list_status'] = 1;
        $data['city_list'] = Cities::where('city_status', '1')->get();
        return ($data);
    }
    public function forgot_pass(Request $request)
    {
        $data = array();
        // $otp = random_int(1000, 9999);
        $otp = 1234;
        $template = SmsTemplate::where('slug', 'otp_forgot_english')->first();
        $message = $template->text;
        $message = str_replace('{{otp}}', $otp, $message);
        $host = SmsHost::where('is_default', '1')->first();
        if ($request->mobile) {
            //$code = substr($request->mobile, 1);
            $mobile = $request->mobile;
            $user = User::where('mobile', $mobile)->where('status', 1)->first();
            if ($user) {
                $data['user_id'] = $user->id;
                $data['msg_en'] = $this->__transEn('otp_send');
                $data['msg_ar'] = $this->__transAr('otp_send');
                $data['status'] = 1;
                $post = new Otp_log;
                $post->mobile_no = $mobile;
                $post->otp = Hash::make($otp);
                $post->status = 1;
                $post->user_id = $user->id;
                $post->type = 2;
                $msg = $post->save();
                /*mobile sms sending api*/

                if ($host->slug == "malath_sms_api") {
                    $DTT_SMS    = new Malath_SMS($host->username, $host->secret, 'UTF-8');
                    $Credits    = $DTT_SMS->GetCredits();
                    $SenderName = $DTT_SMS->GetSenders();
                    $CheckUser  = $DTT_SMS->CheckUserPassword();
                    $SmS_Msg    = $message;
                    $Originator = $host->mask;
                    $Send = $DTT_SMS->Send_SMS($mobile, $Originator, $SmS_Msg, $CheckUser);
                }
            } else {
                $data['status'] = 0;
                $data['msg_en'] = $this->__transEn('mob_no_not_found');
                $data['msg_ar'] = $this->__transAr('mob_no_not_found');
            }
        } else {
            $user = User::where('username', $request->username)->where('status', 1)->first();
            if ($user) {
                $data['user_id'] = $user->id;
                $data['msg_en'] = $this->__transEn('otp_send');
                $data['msg_ar'] = $this->__transAr('otp_send');
                $data['status'] = 1;
                $post = new Otp_log;
                $post->mobile_no = $user->mobile;
                $post->otp = Hash::make($otp);
                $post->status = 1;
                $post->user_id = $user->id;
                $post->type = 2;
                $msg = $post->save();
                /*mobile sms sending api*/

                if ($host->slug == "malath_sms_api") {
                    $DTT_SMS    = new Malath_SMS($host->username, $host->secret, 'UTF-8');
                    $Credits    = $DTT_SMS->GetCredits();
                    $SenderName = $DTT_SMS->GetSenders();
                    $CheckUser  = $DTT_SMS->CheckUserPassword();
                    $SmS_Msg    = $message;
                    $Originator = $host->mask;
                    $Send = $DTT_SMS->Send_SMS($user->mobile, $Originator, $SmS_Msg, $CheckUser);
                }
            } else {
                $data['status'] = 0;
                $data['msg_en'] = $this->__transEn('username_not_found');
                $data['msg_ar'] = $this->__transAr('username_not_found');
            }
        }
        return ($data);
    }

    public function change_pass_forgot(Request $request)
    {
        $data = array();
        if ($request->apptype == "app") {
            $id = $request->user_id;
        } else {
            $id = Auth::id();
        }
        $otp = Otp_log::where('user_id', $id)->where('status', 1)->where('type', 2)->orderBy('created_at', 'desc')->first();
        if (Hash::check($request->otp, $otp->otp)) {
            $post = User::find($id);
            $post->password = Hash::make($request->password);
            $msg = $post->save();
            if ($msg) {
                $data['msg_en'] = array('text' => $this->__transEn('password_changed_successfully'), 'cls' => 'success');
                $data['msg_ar'] = array('text' => $this->__transAr('password_changed_successfully'), 'cls' => 'success');
                $data['status'] = 1;
            } else {
                $data['msg_en'] = array('text' => $this->__transEn('not_change'), 'cls' => 'error');
                $data['msg_ar'] = array('text' => $this->__transEn('not_change'), 'cls' => 'error');
                $data['status'] = 0;
            }
        } else {
            $data['msg_en'] = array('text' => $this->__transEn('otp_not_verified'), 'cls' => 'text-danger');
            $data['msg_ar'] = array('text' => $this->__transAr('otp_not_verified'), 'cls' => 'text-danger');
            $data['status'] = 0;
        }
        return $data;
    }



    public function change_language(Request $request)
    {
        $data = array();
        if ($request->apptype == "app") {
            $id = $request->user_id;
        } else {
            $id = Auth::id();
        }

        $post = User::find($id);
        $post->locale = $request->language;
        $msg = $post->save();
        if ($msg) {
            $data['msg_en'] = array('text' => $this->__transEn('language_changed_successfully'), 'cls' => 'success');
            $data['msg_ar'] = array('text' => $this->__transAr('language_changed_successfully'), 'cls' => 'success');
            $data['status'] = 1;
        } else {
            $data['msg_en'] = array('text' => $this->__transEn('not_change'), 'cls' => 'error');
            $data['msg_ar'] = array('text' => $this->__transEn('not_change'), 'cls' => 'error');
            $data['status'] = 0;
        }

        return $data;
    }
}
