<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Models\Contact;
use App\Models\Bank;
use App\User;
use App\Trading;
use Session;
use Auth;

class WelcomeController extends Controller
{
    public function register_save(Request $request)
    {
        // true spawn vast sadness tiny board plunge arctic maximum begin area gravity
        $this->validate($request, [
            'username' => 'required|string',
            'email' => 'required|email|string',
            'password' => 'required|string',
            'phone' => 'required',
        ]);

        $data = $request->all();

        $checkReferal = User::where('username',$request->referal)->first();
        if(!$checkReferal)
        {
            $data['err'] = 'Invalid Referal ID';
            return view('auth.register', compact('data'));
            //return back()->with('flash_error','Invalid Referal ID');
        }

        $checkUsername = User::where('username',$request->username)->first();
        if($checkUsername)
        {
            $data['err'] = 'Username already exists';
            return view('auth.register', compact('data'));
        }

        $checkEmail = User::where('email',$request->email)->first();
        if($checkEmail)
        {
            $data['err'] = 'Email ID already exists';
            return view('auth.register', compact('data'));
        }

        $checkPhone = User::where('phone',$request->phone)->first();
        if($checkPhone)
        {
            $data['err'] = 'Phone Number already exists';
            return view('auth.register', compact('data'));
        }

        $user = new User;
        $user->role_id = 2;
        $user->username = $request->username;
        $user->email = $request->email;
        $user->phone = $request->phone;
        $user->parent = $request->referal;
        $user->level = 0;
        $user->password = Hash::make($request->password);
        $user->save();

        $bank = new Bank;
        $bank->user_id = $user->id;
        $bank->save();

        $level = new Trading;
        $level->user_id = $user->id;
        $level->order_id = 0;
        $level->amount = 0;
        $level->total = 0;
        $level->type = 'LEVEL';
        $level->credit = 1;
        $level->save();

        Auth::login($user);
        return redirect('/');
    }

    public function login_check(Request $request)
    {
        $credentials = [
            'username' => $request['username'],
            'password' => $request['password'],
        ];

        if (Auth::attempt($credentials)) {
            if (Auth::user()->role_id == 2)
                return redirect('/');
            else{
                Auth::logout();
                return back()->with('flash_error','Invalid Email or Password');
            }
        }
        else{
            return back()->with('flash_error','Invalid Email or Password');
        }
    }

    public function forgot_password_otp(Request $request)
    {
        $request->validate([
            'email' => 'required',
        ]);

        $data = User::where('email',$request->email)->first();
        if(!$data)
            return back()->with('flash_error', 'Invalid Email ID');

        $otp = rand(1000,9999);

$to = $request->email;
$subject = "Forgot Password";

$message = "
<html>
<head>
<title>Forgot Password</title>
</head>
<body>
<p>Dear User<br>Your OTP for password reset is ".$otp."</p>
</body>
</html>
";

// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// More headers
$headers .= 'From: Nexprism <nexprism@gmail.com>' . "\r\n";

//mail($to,$subject,$message,$headers);

        $data->remember_token = $otp;
        $data->save();

        return view('auth.passwords.reset', compact('to'));
    }

    public function forgot_password_otp_check(Request $req)
    {
        $data = User::where('email',$req->email)->first();
        
        if($req->otp == $data->remember_token)
        {
            $to = $req->email;
            return view('auth.passwords.confirm', compact('to'));
        }
        else
        {
            return back()->with('flash_error', 'Invalid OTP');
        }    
    }

    public function reset_password(Request $req)
    {
        
        
        if($req->new == $req->confirm)
        {
            $data = User::where('email',$req->email)->first();
            $data->password = Hash::make($req->new);
            $data->save();
            Auth::login($data);
            return redirect('/');
        }
        else
        {
            return back()->with('flash_error', 'Password and Confirm Password not Match');
        }
        
    }

    public function saveContact(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string',
            'email' => 'required|email|string',
            'message' => 'required|string',
            'phone' => 'required',
        ]);

        $contact = new Contact;
        $contact->name = $request->name;
        $contact->email = $request->email;
        $contact->message = $request->message;
        $contact->phone = $request->phone;
        $contact->save();

        $site_details = SiteDetail::find(1);

  $name=$request->name;
  $email=$request->email;
  $phone=$request->phone;
  $message=$request->message;

  $to = $site_details->email;
  $subject = "Contact Us";
  
$message_ = '
<html> 
<head>
<title>Contact us</title>
</head>
<body>
<h2>Contact Us Entry</h2>
<ul>
  <h3><li>Name: '.$name.'</li></h3>
  <h3><li>Email: '.$email.'</li></h3>
  <h3><li>Phone: '.$phone.'</li></h3>
  <h3><li>Message: '.$message.'</li></h3> 
</ul>
<h4>Thank you<br>'.$site_details->name.' Team</h4>
</body> 
</html>
';

// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// More headers
$headers .= 'From: '.$site_details->name.' <'.$site_details->email.'>' . "\r\n";
   
    @mail($to,$subject,$message_,$headers);
    return back()->with('flash_success_contact', 'Thank You We will get back to you shortly');
    }
    public function intent(Request $request)
    {
        return redirect($request->link);
    }

    public function blogs(Request $request)
    {
        $site_details = SiteDetail::find(1);
        $title = "Blogs | ".$site_details->name;
        $og_image = $site_details->image;
        if($request->name)
        $blogs = blogs::where('title', 'LIKE', "%{$request->name}%")->where('status', 'Active')->orderBy('id','DESC')->paginate(100);
        else
        $blogs = blogs::where('status', 'Active')->orderBy('id','DESC')->paginate(10);
        $recent_blogs = blogs::where('status', 'Active')->orderBy('id','DESC')->limit(4)->get();
        return view('blog',compact('site_details','title','og_image','blogs','recent_blogs'));
    }

    public function blogs_details($slug, $id)
    {
        $site_details = SiteDetail::find(1);
        $blogs = blogs::find($id);
        $title = $blogs->title." | ".$site_details->name;
        $og_image = $blogs->image;
        $recent_blogs = blogs::where('status', 'Active')->orderBy('id','DESC')->limit(4)->get();
        return view('blog-details',compact('site_details','title','og_image','blogs','recent_blogs'));
    }

    public function welcome()
    {
        $site_details = SiteDetail::find(1);
        $banners = Banner::where('status', 'Active')->orderBy('id', 'DESC')->get();
        $products = Product::where('status', 'Active')->orderBy('id','DESC')->get();
        $reviews = Review::where('status', 'Active')->orderBy('id','DESC')->get();
        $blogs = blogs::where('status', 'Active')->orderBy('id','DESC')->limit(3)->get();
        $title = "Home | ".$site_details->name;
        $og_image = $site_details->image;
        return view('welcome',compact('site_details','banners','products','reviews','title','blogs','og_image'));
    }

    public function videos()
    {
        $videos = Video::where('status','Active')->orderBy('id','DESC')->paginate(6);
        return view('videos',compact('videos'));
    }

    public function comment_delete($session_id, $id)
    {
        $comment = Comment::find($id);
        if($comment->session_id == $session_id)
        {
            $comment->delete();
            return back()->with('flash_success_contact', 'Comment Deleted');
        }
        return back()->with('flash_error', 'Try again');
    }

    public function post_comment(Request $request)
    {
        $comment_add = new Comment;
        $comment_add->blog_id = $request->blog_id;
        $comment_add->session_id = Session::getId();
        $comment_add->name = $request->name ? $request->name : 'User';
        $comment_add->comment = $request->comment;
        $comment_add->save();
        $commentno = Comment::where('blog_id', $request->blog_id)->count();
        $commentno .= ' comments';
        $comment = '<div class="comments-details">
                            <div class="comments-list-img">
                              <img src="../../public/front/assets/img/blog/b02.jpg">
                            </div>
                            <div class="comments-content-wrap">
                              <span>
                                <b>'.$comment_add->name.'</b>
                                
                                <span class="post-time">'.date("d-m-Y h:i a",strtotime($comment_add->created_at)).'</span>
                                <a href="../../comment_delete/'.$comment_add->session_id.'/'.$comment_add->id.'"><i style="color: red;" class="fa fa-trash"></i></a>
                              </span>
                              <p>'.$comment_add->comment.'</p>
                            </div>
                          </div>';
        return response()->json(['commentno' => $commentno, 'comment' => $comment]);
    }  
}