<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;
use Session;
use Auth;
use Hash;
use Str;
use Mail;

class WebController extends Controller
{
    public function index()
    {
        Session::put('page','home');

        $data['cats'] = DB::table('categories')->where('status', 0)->get();
        $data['npros'] = DB::table('products')->where('status', 1)->where('ptype', 1)->orderBy('created_at', 'desc')->take(18)->get();
        $data['pro_cats'] = DB::table('categories')->where('items', '>', 0)->where('status', 0)->inRandomOrder()->take(4)->get();
        $data['tpros'] = DB::table('products')->where('status', 1)->where('ptype', 1)->inRandomOrder()->take(8)->get();
        $data['posts'] = DB::table('contents')->where('status', 0)->orderBy('created_at', 'desc')->take(4)->get();

        return view('web.index', $data);
    }

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

    public function accountLogin(Request $request)
    {
        if ($request->isMethod('post')) {
            $data = $request->all();

            if (Auth::guard('member')->attempt(['username'=>$data['username'],'password'=>$data['password']])) {
            
                toastr()->success('Login Successful!');
                return redirect('dashboard');

            }else{
                toastr()->error('Invalid Username or Password!');
                return redirect()->back();
            }
        }
    }

    // Password Reset /////////////////
    public function passreset()
    {
        return view('web.passreset');
    }

    public function resetpass(Request $request)
    {
        if ($request->isMethod('post')) {
            $data = $request->all();

            if (!empty($data['username'])) {
                $user_data = DB::table('members')->where('username', $data['username'])->first();
                if (!empty($user_data)) {
                    $pass = Str::random(6);
                    $data1['password'] = Hash::make($pass);
                    DB::table('members')->where('id', $user_data->id)->update($data1);

                    //SMS Alert                                            
                    $mob = $user_data->mobile;
                    $url = "http://bulksmsbd.net/api/smsapi";
                    $api_key = "F7isYmkCiQF14G4C6uM6";
                    $senderid = "8809617613059";
                    $number= "$mob";
                    $message = 'Dear '.$user_data->name.'! Your New Password: < '.$pass.' > Keep Secrect your Password.';
                 
                    $datax = [
                        "api_key" => $api_key,
                        "senderid" => $senderid,
                        "number" => $number,
                        "message" => $message
                    ];
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_POST, 1);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $datax);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    $smsresult = curl_exec($ch);
                    $p = explode("|",$smsresult);
                    $sendstatus = $p[0];

                    toastr()->success('Password Reset Successful!');
                    return redirect('/');
                }else{
                    toastr()->error('Invalid Username! Try Again.');
                    return redirect()->back();
                }
            }else{
                toastr()->error('Enter Username!');
                return redirect()->back();
            }
        }
    }

    public function admin()
    {
        return view('web.admin');
    }

    public function adminLogin(Request $request)
    {
        if ($request->isMethod('post')) {
            $data = $request->all();

            if (Auth::guard('admin')->attempt(['email'=>$data['email'],'password'=>$data['password']])) {
            
                toastr()->success('Login Successful!');
                return redirect('admin/dashboard');

            }else{
                toastr()->error('Invalid Email or Password!');
                return redirect()->back();
            }
        }
    }

    // Pages //////////////////////////
    public function about()
    {
        Session::put('page','about');

        return view('web.about');
    }

    public function gallery()
    {
        Session::put('page','gallery');

        return view('web.gallery');
    }

    public function news()
    {
        Session::put('page','news');

        $data['posts'] = DB::table('contents')->where('status', 0)->orderBy('created_at', 'desc')->paginate(12);

        return view('web.news', $data);
    }

    public function postdetails($id)
    {
        $data['post_data'] = DB::table('contents')->where('id',$id)->first();
        $data['popular'] = DB::table('contents')->inRandomOrder()->take(4)->get();

        return view('web.postdetails', $data);
    }

    public function contact()
    {
        Session::put('page','contact');

        return view('web.contact');
    }

    public function contactus(Request $request)
    {
        if ($request->isMethod('post')) {
            $data = $request->all();

            $data1['name'] = $data['name'];
            $data1['username'] = $data['username'];
            $data1['email'] = $data['email'];
            $data1['message'] = $data['message'];
            $data1['status'] = 0;
            DB::table('messages')->insert($data1);

            $subs  = DB::table('subscribers')->where('email', $data['email'])->count();
            if ($subs == 0) {
                $data2['email'] = $data['email'];
                DB::table('subscribers')->insert($data2);
            }                

            toastr()->success('Message Send Successfully!');
            return redirect()->back();
        }
    }

    public function subscribe(Request $request)
    {
        if ($request->isMethod('post')) {
            $data = $request->all();

            $subs  = DB::table('subscribers')->where('email', $data['email'])->count();
            if ($subs == 0) {
                $data1['email'] = $data['email'];
                DB::table('subscribers')->insert($data1);

                toastr()->success('You Added into Our Subscriber List Successfully!');
                return redirect()->back();
            }else{
                toastr()->info('You Already Subscribed!');
                return redirect()->back();
            }                

            
        }
    }

    public function faqs()
    {
        Session::put('page','faqs');

        return view('web.faqs');
    }

    public function privacy()
    {

        return view('web.privacy');
    }

    public function terms()
    {

        return view('web.terms');
    }

    // Register ///////////////////////
    public function register()
    {
       
        return view('member.regi');
    }

    public function registration($id)
    {
        $data['ref']   = $id;
       
        return view('web.register', $data);
    }

    public function referAbility(Request $request)
    {
        $refer       = $request->refer;
        if (!empty($refer)) {
            $refer_result   = DB::table('members')->where('username', $refer)->first();
            
            if(empty($refer_result)){
                echo 'unique';
            }else {
                echo 'not_unique';
            }
        }else{
            echo 'invalid';
        }      
              
    }

    public function UserAbility(Request $request)
    {
        $username       = $request->username;
        if (!empty($username)) {
            $username_result   = DB::table('members')->where('username', $username)->first();
            
            if(empty($username_result)){
                echo 'unique';
            }else {
                echo 'not_unique';
            }
        }else{
            echo 'invalid';
        }      
              
    }

    public function newRegister(Request $request)
    {
        if ($request->isMethod('post')) {
            $data = $request->all();

            $rules = [
                'username' => 'max:20|regex:/^[a-zA-Z0-9]*$/',
            ];
                
            $customMessages = [
                'username.regex' => 'Username: Only letters and numbers allow! No Space or Symbol.',
            ];

            $this->validate($request,$rules,$customMessages);

            if (!empty($data['username'])) {
                $new_user = DB::table('members')->where('username', $data['username'])->first();
                if (empty($new_user)) {
                    if (!empty($data['password']) && $data['password'] == $data['confirm_pass']) {
                        if (!empty($data['refer'])) {
                            $refer_data = DB::table('members')->where('username', $data['refer'])->first();
                            if (!empty($refer_data)) {
                                $data1['name'] = $data['name'];
                                $data1['username'] = $data['username'];
                                $data1['email'] = $data['email'];
                                $data1['mobile'] = $data['mobile'];
                                $data1['country'] = 'Bangladesh';
                                $data1['sponsor'] = $refer_data->username;
                                $data1['password'] = Hash::make($data['password']);
                                $data1['password_plain'] = $data['password'];
                                $data1['address'] = $data['address'];
                                $data1['status'] = 0;
                                DB::table('members')->insert($data1);

                                $data2['sponsor_count'] = $refer_data->sponsor_count+1;
                                DB::table('members')->where('id', $refer_data->id)->update($data2);

                                $this->team_count($refer_data->id);

                                //Welcome Email
                                Session::put('email', $data['email']);
                                Session::put('username', $data['username']); 
                                Session::put('password', $data['password']); 

                                $this->regi_wel_email($data['email'], $data['username']);

                                toastr()->success('Registration Completed Successfully!');
                                
                                if ($data['regtyp'] == 1) {
                                    return redirect('login');
                                }else{
                                    return redirect()->back();
                                }
                                
                            }else{
                                toastr()->error('Invalid Refer ID!');
                                return redirect()->back();
                            }                                

                        }else{
                            toastr()->error('Enter Refer ID!');
                            return redirect()->back();
                        }                            

                    }else{
                        toastr()->error('Please, Enter Password Currectly!');
                        return redirect()->back();
                    }
                    
                }else{
                    toastr()->error('User Exist! Try Another.');
                    return redirect()->back();
                }
            }else{
                toastr()->error('Enter Username!');
                return redirect()->back();
            }
        }
    }

    private function team_count($muser)
    {        
        $team_data = DB::table('members')->where('id', $muser)->first();
        
        if(!empty($team_data)) {
            $data200['tcount']   = $team_data->tcount + 1;
            DB::table('members')->where('id', $team_data->id)->update($data200);                 
        }

        if(!empty($team_data)){
            return $this->team_count($team_data->sponsor);
        }
    }

    public function regi_wel_email($mailid, $username){      
       $subject = 'Welcome to Earning BD Shop';
       $data520 = array('email' => $mailid, 'subject' => $subject);
        Mail::send(['html'=>'emails.regi_wel'], $data520, function ($message) use ($data520) {
           $message->from('info@earningbdshop.com', 'Welcome to Earning BD Shop');
           $message->to($data520['email']);
           $message->subject($data520['subject']); 
        });   
    }

    // Product ////////////////////
    public function catPro($id)
    {
        $data['products'] = DB::table('products')->where('cat_id', $id)->where('status', 1)->where('ptype', 1)->orderBy('created_at', 'desc')->paginate(18);
        $data['pro_count'] = DB::table('products')->where('cat_id', $id)->where('status', 1)->where('ptype', 1)->count();
        $data['cat_data'] = DB::table('categories')->where('id',$id)->first();

        return view('web.catpro', $data);
    }

    public function prodetails($id)
    {
        $data['pro_data'] = DB::table('products')->where('id', $id)->first();
        $data['cat_data'] = DB::table('categories')->where('id', $data['pro_data']->cat_id)->first();
        $data['mpros'] = DB::table('products')->where('status', 1)->where('ptype', 1)->inRandomOrder()->take(3)->get();
        $data['rpros'] = DB::table('products')->where('status', 1)->where('ptype', 1)->where('cat_id', $data['pro_data']->cat_id)->inRandomOrder()->take(6)->get();

        return view('web.prodetails', $data);
    }
}
