<?php

namespace App\Http\Controllers\Vendor;

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

class VendorController extends Controller
{
    public function dashboard()
    {
        $data['vendor_data'] = DB::table('vendors')->where('id', Auth::guard('vendor')->user()->id)->first();
        $data['agents'] = DB::table('agents')->where('vendor_id', $data['vendor_data']->id)->count();
        $data['psales'] = DB::table('reports')->where('user_id', $data['vendor_data']->id)->where('type', 'vendor')->where('wallet', 'point')->where('action', 'Transfer')->sum('bal_out');
        $data['tsales'] = DB::table('orders')->where('vend_id', $data['vendor_data']->id)->where('status', 1)->sum('sub_total');
        $data['pend_sales'] = DB::table('orders')->where('vend_id', $data['vendor_data']->id)->where('status', 0)->sum('sub_total');
        $data['payout'] = DB::table('payments')->where('user_id', $data['vendor_data']->id)->where('user_type', 'Vendor')->where('type', 'Payout')->sum('amount');

        return view('vendor.dashboard', $data);
    }

    public function logout()
    {
        Auth::guard('vendor')->logout();
        return redirect('/');
    }

    public function settings()
    {
        $data['vendor_data'] = DB::table('vendors')->where('id', Auth::guard('vendor')->user()->id)->first();
        $data['country'] = DB::table('countries')->get();
        return view('vendor.settings', $data);
    }

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

            $rules = [
                'name' => 'required',
                'email' => 'required|email',
                'mobile' => 'required',
            ];
                
            $customMessages = [
                'name.required' => 'Name is Required',
                'email.required' => 'Email is Required',
                'email.email' => 'Valid Email is Required',
                'mobile.required' => 'Mobile is Required', 
            ];

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

            $vendor = DB::table('vendors')->where('id', Auth::guard('vendor')->user()->id)->first();

            if (Hash::check($data['pin'], $vendor->pin)) {
                $data1['name'] = $data['name'];
                $data1['email'] = $data['email'];
                $data1['mobile'] = $data['mobile'];
                $data1['country'] = $data['country'];
                $data1['address'] = $data['address'];

                DB::table('vendors')->where('id', $vendor->id)->update($data1);

                toastr()->success('Profile Updated Successfully!');
                return redirect()->back();
            }else{
                toastr()->error('Invalid Security PIN!');
                return redirect()->back();
            } 
        }
    }

    public function updatePass(Request $request)
    {
        if ($request->isMethod('post')) {
            $data = $request->all();
            if(Hash::check($data['current_pass'], Auth::guard('vendor')->user()->password)){
                if ($data['password']==$data['conf_password']){
                    DB::table('vendors')->where('id', Auth::guard('vendor')->user()->id)->update(['password'=>bcrypt($data['password'])]);
                    
                    toastr()->success('Password updated successfully!');

                }else{

                   toastr()->error('New password and Confirm password not match');
                }
            }else{
  
                toastr()->error('Your current password is incorrect');
            }
            return redirect()->back();
        }
    }

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

            $vend_data = DB::table('vendors')->where('id', Auth::guard('vendor')->user()->id)->first();

            if ($data['pin'] == $data['conf_pin']) {
                $data1['pin'] = Hash::make($data['pin']);
                DB::table('vendors')->where('id', $vend_data->id)->update($data1);

                toastr()->success('PIN Generated Successfully!');
                return redirect()->back();
            }else{
                toastr()->error('Confirm PIN Not Matched!');
                return redirect()->back();
            }
                
        }
    }


    public function updatePin(Request $request)
    {
        if ($request->isMethod('post')) {
            $data = $request->all();
            if(Hash::check($data['current_pin'], Auth::guard('vendor')->user()->pin)){ 
                if ($data['pin']==$data['conf_pin']) {
                    DB::table('vendors')->where('id', Auth::guard('vendor')->user()->id)->update(['pin'=>bcrypt($data['pin'])]);
                 
                    toastr()->success('PIN updated successfully!');

                }else{
                    
                    toastr()->error('New PIN and Confirm PIN not match');
                }   
            }else{
              
                toastr()->error('Your current PIN is incorrect');
            }

            return redirect()->back();
        }
    }

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

            $vendor_data = DB::table('vendors')->where('id', Auth::guard('vendor')->user()->id)->first();

            $spass = Str::random(4);
            $data1['pin'] = Hash::make($spass);
            DB::table('vendors')->where('id', $vendor_data->id)->update($data1);

            //SMS Alert
            $mob = $vendor_data->mobile;
            $url = "http://66.45.237.70/api.php";
            $number= "$mob";
            $text='Dear '.$vendor_data->username.'! Your New Security PIN: < '.$spass.' > Keep Secrect your PIN. Hotline: 01940243031';
            $dataxx= array(
            'username'=>"01304098181",
            'password'=>"NKDTFPYZ",
            'number'=>"$number",
            'message'=>"$text"
            );

            $ch = curl_init(); // Initialize cURL
            curl_setopt($ch, CURLOPT_URL,$url);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($dataxx));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $smsresult = curl_exec($ch);
            $p = explode("|",$smsresult);
            $sendstatus = $p[0];

            toastr()->success('PIN Reset Successful!');
            return redirect()->back();
        }
    }

    public function agents()
    {
        $data['agents'] = DB::table('agents')->where('vendor_id', Auth::guard('vendor')->user()->id)->orderBy('created_at', 'desc')->get();
        return view('vendor.agents', $data);
    }

    public function addAgent()
    {
        return view('vendor.addagent');
    }

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

    public function agentRegi(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('agents')->where('username', $data['username'])->first();
                if (empty($new_user)) {
                    if (!empty($data['password']) && $data['password'] == $data['confirm_pass']) {

                        $vendor = DB::table('vendors')->where('id', Auth::guard('vendor')->user()->id)->first();

                        $data1['name'] = $data['name'];
                        $data1['shop_name'] = $data['shop_name'];
                        $data1['username'] = $data['username'];
                        $data1['email'] = $data['email'];
                        $data1['mobile'] = $data['mobile'];
                        $data1['password'] = Hash::make($data['password']);
                        $data1['address'] = $data['address'];
                        $data1['min_ratio'] = $data['percent'];
                        $data1['vendor_id'] = $vendor->id;
                        $data1['status'] = 1;
                        DB::table('agents')->insert($data1);

                        $data2['agents'] = $vendor->agents+1;
                        DB::table('vendors')->where('id', $vendor->id)->update($data2);

                        //SMS Alert
                        $mob = $data['mobile'];
                        $url = "http://66.45.237.70/api.php";
                        $number= "$mob";
                        $text='Welcome to osbbl.shop! Your Agent Account Register Successful. Login ID: '.$data['username'].' & Password: '.$data['password'].' Hotline: 01940243031';
                        $dataxx= array(
                        'username'=>"01304098181",
                        'password'=>"NKDTFPYZ",
                        'number'=>"$number",
                        'message'=>"$text"
                        );

                        $ch = curl_init(); // Initialize cURL
                        curl_setopt($ch, CURLOPT_URL,$url);
                        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($dataxx));
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        $smsresult = curl_exec($ch);
                        $p = explode("|",$smsresult);
                        $sendstatus = $p[0];

                        toastr()->success('Agent Added Successful! Wait until Active.');
                        return redirect()->back();

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

        }
    }

    public function pointsend()
    {
        $data['vendor_data'] = DB::table('vendors')->where('id', Auth::guard('vendor')->user()->id)->first();
        $data['agents'] = DB::table('agents')->where('vendor_id', Auth::guard('vendor')->user()->id)->where('status', 0)->get();
        return view('vendor.pointsend', $data);
    }

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

            if (!empty($data['username'])) {
                $user_data = DB::table('vendors')->where('id', Auth::guard('vendor')->user()->id)->first();
                $receiv_user = DB::table('agents')->where('username', $data['username'])->first();

                if (!empty($data['amount']) && $data['amount'] >= 1) {
                    if ($user_data->point_bal >= $data['amount']) {
                        if (Hash::check($data['pin'], $user_data->pin)) {
                            $data1['point_bal'] = $receiv_user->point_bal+$data['amount'];
                            $pay = DB::table('agents')->where('id', $receiv_user->id)->update($data1);

                            if ($pay) {
                                $data2['point_bal'] = $user_data->point_bal-$data['amount'];
                                DB::table('vendors')->where('id', $user_data->id)->update($data2);

                                $repo1['type'] = 'agent';
                                $repo1['bal_type'] = 'Receive';
                                $repo1['wallet'] = 'point';
                                $repo1['action'] = 'Receive';
                                $repo1['details'] = 'Receive Point from ';
                                $repo1['bal_in'] = $data['amount'];
                                $repo1['bal'] = $receiv_user->point_bal+$data['amount'];
                                $repo1['user_id'] = $receiv_user->id;
                                $repo1['from_user'] = $user_data->username;
                                DB::table('reports')->insert($repo1);

                                $repo2['type'] = 'vendor';
                                $repo2['bal_type'] = 'Transfer';
                                $repo2['wallet'] = 'point';
                                $repo2['action'] = 'Transfer';
                                $repo2['details'] = 'Transfer Point to ';
                                $repo2['bal_out'] = $data['amount'];
                                $repo2['bal'] = $user_data->point_bal-$data['amount'];
                                $repo2['user_id'] = $user_data->id;
                                $repo2['from_user'] = $receiv_user->username;
                                DB::table('reports')->insert($repo2);
                                
                                toastr()->success('Point Send Successful!');
                                return redirect()->back();
                            }else{
                                toastr()->error('Somethin is Worng! Try Again.');
                                return redirect()->back();
                            }
                        }else{
                            toastr()->error('Invalid Security PIN!');
                            return redirect()->back();
                        }
                    }else{
                        toastr()->error('Insufficient Point Balance!');
                        return redirect()->back();
                    }

                        
                }else{
                    toastr()->error('Enter Amount Currectly!');
                    return redirect()->back();
                }
                
            }else{
                toastr()->error('Select an Agent!');
                return redirect()->back();
            }
        }
    }

    public function balsend()
    {
        $data['vendor_data'] = DB::table('vendors')->where('id', Auth::guard('vendor')->user()->id)->first();
        $data['agents'] = DB::table('agents')->where('vendor_id', Auth::guard('vendor')->user()->id)->where('status', 0)->get();

        return view('vendor.balsend', $data);
    }

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

            if (!empty($data['username'])) {
                $user_data = DB::table('agents')->where('username', $data['username'])->first();
                
                if (!empty($data['amount']) && $data['amount'] >= 1) {
                    $vendor_data = DB::table('vendors')->where('id', Auth::guard('vendor')->user()->id)->first();
                    if (Hash::check($data['pin'], $vendor_data->pin)) {
                        $data1['cash_bal'] = $user_data->cash_bal+$data['amount'];
                        $pay = DB::table('agents')->where('id', $user_data->id)->update($data1);

                        if ($pay) {
                            $repo1['type'] = 'agent';
                            $repo1['bal_type'] = 'Receive';
                            $repo1['wallet'] = 'cash';
                            $repo1['action'] = 'Receive';
                            $repo1['details'] = 'Receive Cash from ';
                            $repo1['bal_in'] = $data['amount'];
                            $repo1['bal'] = $user_data->cash_bal+$data['amount'];
                            $repo1['user_id'] = $user_data->id;
                            $repo1['from_user'] = $vendor_data->username;
                            DB::table('reports')->insert($repo1);

                            $data2['cash_bal'] = $vendor_data->cash_bal-$data['amount'];
                            DB::table('vendors')->where('id', $vendor_data->id)->update($data2);

                            $repo3['type'] = 'vendor';
                            $repo3['bal_type'] = 'Transfer';
                            $repo3['wallet'] = 'cash';
                            $repo3['action'] = 'Transfer';
                            $repo3['details'] = 'Transfer Cash to ';
                            $repo3['bal_out'] = $data['amount'];
                            $repo3['bal'] = $vendor_data->cash_bal-$data['amount'];
                            $repo3['user_id'] = $vendor_data->id;
                            $repo3['from_user'] = $user_data->username;
                            DB::table('reports')->insert($repo3);

                            toastr()->success('Cash Send Successful!');
                            return redirect()->back();
                        }else{
                            toastr()->error('Somethin is Worng! Try Again.');
                            return redirect()->back();
                        }
                    }else{
                        toastr()->error('Invalid Security PIN!');
                        return redirect()->back();
                    }
                }else{
                    toastr()->error('Enter Amount Currectly!');
                    return redirect()->back();
                }
                
            }else{
                toastr()->error('Select an Agent!');
                return redirect()->back();
            }
        }
    }

    public function payout()
    {
        $data['vendor_data'] = DB::table('vendors')->where('id', Auth::guard('vendor')->user()->id)->first();
        return view('vendor.payout', $data);
    }

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

            $vend_data = DB::table('vendors')->where('id', Auth::guard('vendor')->user()->id)->first();

            if (!empty($data['amount']) && $data['amount'] >= 500) {
                if ($vend_data->cash_bal >= $data['amount']) {
                    if (!empty($data['gateway']) && !empty($data['account'])) {
                        if (Hash::check($data['pin'], $vend_data->pin)) {  
                            $charge = $data['amount']*10/100;
                            $net_amount = $data['amount']-$charge;

                            $data1['user_id'] = $vend_data->id;
                            $data1['username'] = $vend_data->username;
                            $data1['user_type'] = 'Vendor';
                            $data1['type'] = 'Payout';
                            $data1['user_name'] = $vend_data->name;
                            $data1['user_mobile'] = $vend_data->mobile;
                            $data1['payment_method'] = $data['gateway'];
                            $data1['account'] = $data['account'];
                            $data1['amount'] = $net_amount;
                            $data1['charge'] = $charge;
                            $data1['status'] = 0;
                            $payout = DB::table('payments')->insert($data1);
                              
                            if ($payout) {
                                $data2['cash_bal'] = $vend_data->cash_bal-$data['amount'];
                                DB::table('vendors')->where('id', $vend_data->id)->update($data2);

                                $repo1['type']            = 'vendor';
                                $repo1['bal_type']        = 'Transfer';
                                $repo1['wallet']          = 'cash';
                                $repo1['action']          = 'Payout';
                                $repo1['details']         = 'Transfer Amount for Payout';
                                $repo1['bal_out']         = $data['amount'];
                                $repo1['bal']             = $vend_data->cash_bal-$data['amount'];   
                                $repo1['user_id']         = $vend_data->id;
                                DB::table('reports')->insert($repo1);

                                $wallet = DB::table('wallet_manages')->where('id', 1)->first();
                                $data3['tax'] = $wallet->tax+$charge;
                                DB::table('wallet_manages')->where('id', $wallet->id)->update($data3);

                                $repo2['type']            = 'admin';
                                $repo2['bal_type']        = 'Receive';
                                $repo2['wallet']          = 'charge';
                                $repo2['action']          = 'Payout';
                                $repo2['details']         = 'Receive Payout Charge from ';
                                $repo2['bal_in']          = $charge;  
                                $repo2['bal']             = $wallet->tax+$charge; 
                                $repo2['user_id']         = 1;
                                $repo2['from_user']       = $vend_data->username;
                                DB::table('reports')->insert($repo2);
                                
                                toastr()->success('Payout Completed Successfully!');
                                return redirect()->back(); 
                            } 
                        }else{
                            toastr()->error('Invalid Security PIN! Reset or Generate Under Settings Section.');
                            return redirect()->back();
                        }
                    }else{
                        toastr()->error('Please, Select Payment Method & Enter Account Number Currectly!');
                        return redirect()->back();
                    }
                }else{
                    toastr()->error('Insufficient Balance!');
                    return redirect()->back();
                }
            }else{
                toastr()->error('Please, Enter amount! (Minimum 500)');
                return redirect()->back();
            }
        }
    }

    public function prepo()
    {
        $data['reports'] = DB::table('reports')->where('type', 'vendor')->where('user_id', Auth::guard('vendor')->user()->id)->where('wallet', 'point')->orderBy('created_at', 'desc')->get();
        return view('vendor.prepo', $data);
    }

    public function crepo()
    {
        $data['reports'] = DB::table('reports')->where('type', 'vendor')->where('user_id', Auth::guard('vendor')->user()->id)->where('wallet', 'cash')->orderBy('created_at', 'desc')->get();
        return view('vendor.crepo', $data);
    }


    public function paystatus()
    {
        $data['payments'] = DB::table('payments')->where('user_id', Auth::guard('vendor')->user()->id)->where('user_type', 'Vendor')->where('type', 'Payout')->get();
        
        return view('vendor.paystatus', $data);
    }
}
