<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use \App\User;
use \App\Helper;
use \App\Bank;
use \App\Balance;
use \App\History;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Yajra\DataTables\DataTables;
use \App\Rules\Oldpassword;

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            if(auth()->check()){
                Helper::checkLevel(['admin', 'reseller', 'member', 'priority', 'junior']);
            } else {
                return redirect('/login');
            }
            return $next($request);
        });
    }

    public function addUser(){
      Helper::checkLevel(['admin', 'reseller']);
    	return view('user.register');
    }

    public function saveUser(Request $request){
        
      Helper::checkLevel(['admin', 'reseller']);
      if (auth()->user()->level == 'reseller') {
        $request->validate([
            'username' => 'unique:users,username|required',
            'password' => 'required|confirmed|min:8',
            'durasi' => 'in:1,3,7,14,30,custom',
            'level' => 'in:priority,member,reseller'
        ]);
      } else if (auth()->user()->level == 'admin') {
        $request->validate([
            'username' => 'unique:users,username|required',
            'password' => 'required|confirmed|min:8',
            'durasi' => 'in:1,3,7,14,30,custom',
            'level' => 'in:member,priority,reseller'
        ]);
      }

      $durasi = request()->durasi;

      if($request->level == 'priority'){
          if($durasi == 7){
              $price = 35000;
          } else if($durasi == 14){
              $price = 50000;
          } else if($durasi == 30){
              $price = 80000;
          }
      }else{
          if($durasi == 1){
              $price = 15000;
          } else if($durasi == 3){
              $price = 25000;
          } else if($durasi == 7){
              $price = 40000;
          } else if($durasi == 14){
              $price = 70000;
          } else if($durasi == 30){
              $price = 120000;
          }
      }

      $message = ['Alert' => 'Saldo tidak mencukupi'];
      if(auth()->user()->saldo < $price){
          session()->flash('message', $message);
          return redirect()->back();
      }

    	$date = date('Y-m-d h:i:s');
    	$user = new User;
    	$user->username = request()->username;
    	$user->password = bcrypt(request()->password);
    	$user->level = request()->level;
    	$user->register_date = $date;
    	$user->expired_date = date('Y-m-d h:i:s', strtotime($date.' + '.$durasi.' days'));
    	$user->register_by = auth()->user()->username;
    	$user->status = 'aktif';
    	$save = $user->save();
    	if($save){
        $delay = new \App\Delay;
        $delay->user_id = $user->id;
        $delay->save();
        
        $con = mysqli_connect('localhost', 'instagr9_panel', 'T;y^54SN@!Sa', 'instagr9_panel');
        $query = mysqli_query($con, "INSERT INTO users_panel VALUES(NULL, '".request()->username."', 'IGPanel')");

        Helper::subtractSaldo(auth()->user()->id, $price);
        Helper::saveUserBalanceHistory(auth()->user()->id, $price, 'debit', 'Pembuatan akun '.request()->level.' | "'.request()->username.'" dengan durasi '.$durasi.' hari', 'complete');
    		$data = request()->all();
        $expired = $user->expired_date;
        session()->flash('data', $data);
        session()->flash('expired', $expired);
        return redirect()->action('UserController@addUser')->with('userPassword', request()->password);
    	}
    }

    public function userListActive(){
      Helper::checkLevel(['admin','reseller']);
      if(auth()->user()->level == 'admin'){
        $users = User::where('expired_date', '>', date('Y-m-d h:i:s'))->get();
      } else if(auth()->user()->level == 'reseller') {
        $users = User::where('register_by', auth()->user()->username)->where('expired_date', '>', date('Y-m-d h:i:s'))->get();
      } else {
        return abort(505);
      }
      $button = '';
      $data = [];
      foreach($users as $key => $user){
        $class = '';
        if($user->status == 'aktif') {
          $suspend = '<button type="button" onclick="suspend('.$user->id.')" style="margin:0 2px;" class="btn btn-danger waves-effect waves-light"><i class="fa fa-close"></i></button>';
        } else {
          $suspend = '<button type="button" onclick="suspend('.$user->id.')" style="margin:0 2px;" class="btn btn-success waves-effect waves-light"><i class="fa fa-check"></i></button>';
        }
        if (auth()->user()->level == 'admin') {
          $button = $suspend;
          $button .= '<a href="'.url('admin/change_password/'.$user->id).'" target="_blank" style="margin:0 2px;" class="btn btn-primary change-pw waves-effect waves-light"><i class="fa fa-key"></i></a>';
        }
        $data[$key] = [
          'username' => $user->username,
        //   'sublike' => \App\History::where('submitted_by', $user->username)->where('type', 'Like Server 1')->whereDate('created_at', '=', date('Y-m-d'))->count() + \App\History::where('submitted_by', $user->username)->where('type', 'Like Server 2')->whereDate('created_at', '=', date('Y-m-d'))->count(),
          'level' => $user->level,
          'expired_date' => \Carbon\Carbon::parse($user->expired_date)->diffInDays(). ' hari lagi',
          'register_by' => $user->register_by,
          'status' => $user->status,
          'saldo' => 'Rp. '.$user->saldo,
          'created_at' => \Carbon\Carbon::parse($user->created_at)->diffForHumans(),
        ];

        if (auth()->user()->level == 'admin') {
          $data[$key]['action'] = $button;
        }
      }

      return DataTables::of($data)->make(true);
    }

    public function userListViewActive(){
      Helper::checkLevel(['admin','reseller']);
      return view('user.user-list');
    }

    public function userListExpired(){
      Helper::checkLevel(['admin','reseller']);
      if(auth()->user()->level == 'admin'){
        $users = User::where('expired_date', '<', date('Y-m-d h:i:s'))->get();
      } else if(auth()->user()->level == 'reseller') {
        $users = User::where('register_by', auth()->user()->username)->where('expired_date', '<', date('Y-m-d h:i:s'))->get();
      } else {
        return abort(505);
      }
      $button = '';
      $data = [];
      foreach($users as $key => $user){
        $class = '';
        if($user->status == 'aktif') {
          $suspend = '<button type="button" onclick="suspend('.$user->id.')" style="margin:0 2px;" class="btn btn-danger waves-effect waves-light"><i class="fa fa-close"></i></button>';
        } else {
          $suspend = '<button type="button" onclick="suspend('.$user->id.')" style="margin:0 2px;" class="btn btn-success waves-effect waves-light"><i class="fa fa-check"></i></button>';
        }
        if (auth()->user()->level == 'admin') {
          $button = $suspend;
          $button .= '<a href="'.url('admin/change_password/'.$user->id).'" target="_blank" style="margin:0 2px;" class="btn btn-primary change-pw waves-effect waves-light"><i class="fa fa-key"></i></a>';
        }
        $data[$key] = [
          'username' => $user->username,
          'level' => $user->level,
          'expired_date' => \Carbon\Carbon::parse($user->expired_date)->diffInDays(). ' hari yang lalu',
          'register_by' => $user->register_by,
          'status' => $user->status,
          'saldo' => 'Rp. '.$user->saldo,
          'created_at' => \Carbon\Carbon::parse($user->created_at)->diffForHumans(),
        ];

        if (auth()->user()->level == 'admin') {
          $data[$key]['action'] = $button;
        }
      }

      return DataTables::of($data)->make(true);
    }

    public function userListViewExpired(){
      Helper::checkLevel(['admin','reseller']);
      return view('user.user-list-expired');
    }

    public function historyBalanceList(){
      if(auth()->user()->level == 'admin'){
        $histories = Balance::all();
      }
      else{
        $histories = Balance::where('id_user', auth()->user()->id)->orderBy('id', 'DESC')->get();
      }
      $data = [];
      // dd($histories);
      foreach($histories as $balance){
        $type = $balance->type;
        if($type == 'debit'){
          $class = 'danger';
        }
        else{
          $class = 'primary';
        }
        $data[] = [
          'code' => '<span class="label label-primary">'.strtoupper($balance->code).'</span>',
          'username' => (count(array($balance->user))) ? $balance['user']['username'] : 'USER_DELETED',
          'value' => 'Rp. '.number_format($balance->value,0),
          'type' => '<span class="label label-'.$class.'">'.strtoupper($balance->type).'</span>',
          'note' => $balance->note,
          'status' => '<span class="label label-success">'.strtoupper($balance->status).'</span>',
          'created_at' => \Carbon\Carbon::parse($balance->created_at)->diffForHumans(),
        ];
      }
      return DataTables::of($data)->escapeColumns([])->make(true);
    }

    public function historyBalanceView(){
      return view('user.balance');
    }

    public function extend(Request $request){
        $delay = 1;
        \App\Delay::where('user_id', auth()->user()->id)->update(['like_9' => date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . $delay . ' minute'))]);
          Helper::checkLevel(['admin', 'reseller']);
      $username = auth()->user()->username;
      if (auth()->user()->level == 'reseller') {
        $user = User::where('register_by', '=' , auth()->user()->username)->get();
        $usernames = '';
        $no = 1;
        foreach($user as $u) {
          $koma = ',';
          if ($no == 1){
            $koma = '';
          }
          $usernames .= $koma.$u->username;
          $no++;
        }
        $request->validate([
            'durasi' => 'required|in:1,3,7,14,30',
            'user' => "required|not_in:{$username}"
        ]);
      } else if (auth()->user()->level == 'admin') {
        $request->validate([
            'durasi' => 'in:1,3,7,14,30',
            'user' => "required|not_in:{$username}"
        ]);
      }

      $durasi = request()->durasi;

      if($durasi == 1){
          $time = '1 days';
          $price = 12000;
      } else if($durasi == 3){  
          $time = '3 days';
          $price = 25000;
      } else if($durasi == 7){
          $time = '1 week';
          $price = 40000;
      } else if($durasi == 14){
          $time = '2 weeks';
          $price = 70000;
      } else if($durasi == 30){
          $time = '1 month';
          $price = 120000;
      }
      $message = ['Alert' => 'Saldo tidak mencukupi'];
      if(auth()->user()->saldo < $price){
          session()->flash('message', $message);
          return redirect()->back();
      }
      $username = request('user');
      $user = User::where('username', '=', $username)->first();
      if (time() <= strtotime($user->expired_date)) {
        $newexp = date('Y-m-d', strtotime('+'.$time, strtotime($user->expired_date)));
        $user->expired_date = $newexp;
        $save = $user->save();
      } else {
        $newexp = date('Y-m-d', strtotime('+'.$time));
        $user->expired_date = $newexp;
        $save = $user->save();
      }
      if($save){
        Helper::subtractSaldo(auth()->user()->id,$price);
        Helper::saveUserBalanceHistory(auth()->user()->id, $price, 'debit', 'Perpanjangan durasi akun '.$user->level.' | "'.request()->user.'" dengan durasi '.$time, 'complete');
        $data = $user;
        $data['durasi'] = $durasi;
        session()->flash('data', $data);
        return redirect()->action('UserController@extendView');
      } else {
        $message = ['Error' => 'Terjadi kesalahan pada sistem silahkan coba lagi dengan melakukan refresh pada halaman'];
        session()->flash('message', $message);
        return redirect()->back();
      }
    }

    public function extendView(){
      Helper::checkLevel(['admin', 'reseller']);
      if(auth()->user()->level  == 'admin') {
        $user = User::where('id', '!=' , auth()->user()->id)->get();
      } else if (auth()->user()->level  == 'reseller') {
        $user = User::where('register_by', '=' , auth()->user()->username)->get();
      }
      return view('user.extend', compact('user'));
    }

    public function historySubmitView(){
      return view('user.submit-history');
    }

    public function historySubmitList(){
      if(auth()->user()->level == 'admin'){
        $histories = History::orderBy('created_at', 'desc')->take(5000)->get();
      }
      else{
        $histories = History::where('submitted_by', auth()->user()->username)->get();
      }
      $data = [];
      foreach($histories as $submit){
        $type = $submit->type;
        
        if($type == 'Comment'){
          $class = 'primary';
        }
        else{
          $class = 'success';
        }
        
        if($submit->status == 1){
            $status = 'Pending';
            $ws = 'warning';
        }else if($submit->status == 'Success'){
            $status = $submit->status;
            $ws = 'success';
        }elseif($submit->status == 'Canceled'){
            $status = $submit->status;
            $ws = 'danger';
        }else{
            $status = $submit->status;
            $ws = 'primary';
        }
        $data[] = [
          'submitted_by' => $submit->submitted_by,
          'target' => '<a href="'.$submit->target.'" target="_blank">'.$submit->target.'</a>',
          'total_submit' => $submit->total_submit,
          'start' => $submit->start,
          'status' => '<span class="label label-'.$ws.'">'.$status.'</span>',
          'ip' => $submit->ip,
          'created_at' => \Carbon\Carbon::parse($submit->created_at)->diffForHumans(),
          'updated_at' => \Carbon\Carbon::parse($submit->updated_at)->diffForHumans(),
          'type' => '<span class="label label-'.$class.'">'.strtoupper($submit->type).'</span>',
        ];
      }
      return DataTables::of($data)->escapeColumns([])->make(true);
    }


    public function change(Request $request) {
      $request->validate([
        'old_password' => ['required', new Oldpassword],
        'password' => 'required|confirmed|min:8',
      ]);
      $user = User::where('id', '=', auth()->user()->id)->first();
      $user->password = Hash::make(request('password'));
      $save = $user->save();
      if ($save) {
        session()->flash('login_alert', 'Harap login kembali setelah melakukan penggantian password');
        auth()->logout();
        return redirect('/login');
      }
    }

    public function changeView() {
      return view('user.change');
    }

    public function changeUser(Request $request) {
      $request->validate([
        'password' => 'required|confirmed|min:8',
      ]);
      $user = User::where('id', '=', request('id'))->first();
      $user->password = Hash::make(request('password'));
      $save = $user->save();
      if ($save) {
        return 'Sukses ganti password member';
      }
    }

    public function changeUserView($id) {
      Helper::checkLevel(['admin']);
      return view('admin.change', compact('id'));
    }

    public function autoSaldo(Request $request) {
      Helper::checkLevel(['reseller', 'member', 'priority','admin']);
      $request->validate([
        'bank' => 'required|in:bca',
        'jumlah' => 'required|numeric|min:10000'
      ]);
      $bank = request('bank');
      
      $jumlah  = intval(request('jumlah')) + rand(111,999);;
      if ($bank == 'bca') {
        $tujuan = "5505164251 a/n Syarif H (BCA)";
      } else if ($bank == 'bni') {
        $tujuan = "0489641119 A/n Syarif H (BNI)";
      }
      
      $id = rand(1111,9999);
      $data = [
        'tujuan' => $tujuan,
        'jumlah' => $jumlah,
        'tanggal' => date('Y-m-d'),
        'id' => $id,
        'id_user' => auth()->user()->id,
        'username' => auth()->user()->username,
        'keterangan' => 'Tambah Saldo Otomatis',
        'bank' => $bank
      ];
      if(session()->has('auto_saldo')) {
        $message = [
          'Message' => 'Anda sudah memiliki sesi add saldo otomatis, bersihkan cache browser anda terlebih dahulu',
        ];
        session()->flash('message', $message);
        return redirect()->action('UserController@autoSaldoView');
      } else {
        session(['auto_saldo' => $data]);
      }
      return redirect()->action('UserController@autoSaldoView');
    }

    public function autoSaldoNext(Request $request) {
      if($addsaldo = session("auto_saldo")) {
        Helper::checkLevel(['reseller', 'member', 'priority', 'admin']);
        $tgl        = date("j-n-Y");
        $addsaldo   = session("auto_saldo");
        $bank       = $addsaldo['bank'];
        
        $jumlah     = $addsaldo['jumlah'];
        // if($jumlah >= 10000){
        //     $bonus      = ceil($addsaldo['jumlah'] * 10 / 100);
        // }else{
        //     $bonus = 0;
        // }
        $bonus = 0;
        // $bonus = 0;
        $username      = $addsaldo['username'];
        $id_user      = $addsaldo['id_user'];
        $keterangan = $addsaldo['keterangan'];
        $tglTrx     = $addsaldo['tanggal'];
        
        if($bank == 'bca') {
          $source   = Bank::grab_bca('sarifhid0302', '010206', $tgl);
          $exp      = explode('<b>Saldo</b></font></div></td>', $source);
          $jkt_time = time() + (3600 * 1);
          $tahun    = date('Y', $jkt_time);
          if (isset($exp[1])) {
            $sukses = 0;
            $table = explode("</table>", $exp[1]);
            $tr    = explode("<tr>", $table[0]);
            for ($i = 1; $i < count($tr); $i++) {
              $str = str_ireplace('</font>', '#~#~#</font>', $tr[$i]);
              $str = str_ireplace('<br>', '<br> ', $str);
              $str = preg_replace('!\s+!', ' ', trim(strip_tags($str)));

              $arr    = array_map('trim', explode("#~#~#", $str));
              $dbpend = $arr[4];

              $arr[0]     = date('d/m', $jkt_time);
              $tgl        = $arr[0] . '/' . $tahun;
              $keterangan = $arr[1]; //keterangan ini adalah keterangan di mutasi
              $kredit     = Bank::fix_angka_bca($arr[3]); //kredit ini adalah nominal mutasi
              if ($kredit == $jumlah) { // nah ini proses kalau nominal yang kita cari di jumlah ada berarti artinya sukses
                $sukses = 1;
              }
            }
            if ($sukses) {
                $ttln = $jumlah + $bonus;
              Helper::addSaldo($id_user, $ttln);
              Helper::saveUserBalanceHistory($id_user, $ttln, 'deposit', 'Transfer Saldo Otomatis melalui Bank '.strtoupper($bank).' untuk akun sendiri', 'complete');
              $message = [
                'Message' => 'Tambah saldo otomatis berhasil!',
                'username' => $username,
                'Bank' => $bank,
                'Jumlah' => $ttln,
                'Tgl Transaksi' => $tglTrx,
                'status' => 'Berhasil'
              ];
              session()->flash('message', $message);
              session()->forget('auto_saldo');
              return redirect()->action('UserController@autoSaldoView');
            } else {
              $message = [
                'Message' => 'Anda belum melakukan pembayaran',
              ];
              session()->flash('message', $message);
              return redirect()->action('UserController@autoSaldoView');
            }
          } else {
            $message = [
              'Message' => 'Akun E-Bank admin bermasalah',
            ];
            session()->flash('message', $message);
            return redirect()->action('UserController@autoSaldoView');
          }
        } else {
          return abort(505);
        }
      } else {
        return abort(404);
      }
    }

    public function autoSaldoPrev() {
      if($addsaldo = session("auto_saldo")) {
        Helper::checkLevel(['reseller', 'member', 'priority', 'admin']);
        $message = [
          'message' => 'Pembatalan berhasil'
        ];
        session()->flash('message', $message);
        session()->forget('auto_saldo');
        return redirect()->action('UserController@autoSaldoView');
      } else {
        return abort(404);
      }
    }
    public function autoSaldoView() {
      Helper::checkLevel(['reseller', 'member', 'priority', 'admin']);
      return view('user.auto-saldo');
    }

    public function autoExtend(Request $request) {
      Helper::checkLevel(['member', 'reseller', 'priority', 'admin']);
      if (Helper::isUserRegisteredByAdmin()) {
        $request->validate([
          'method' => 'required|in:bca',
          'durasi' => 'required|in:3,7,14,30'
        ]);
        $durasi = request('durasi');
        $method  = request('method');
        if($durasi == 3){
            $keterangan = "Perpanjang akun 3 hari";
            $jumlah = 40000+rand(111,999);
            $price = 40000;
            $time = '3 days';
        } else if($durasi == 7){
            $keterangan = "Perpanjang akun 1 minggu";
            $jumlah = 65000+rand(111,999);
            $price = 65000;
            $time = '1 week';
        } else if($durasi == 14){
            $keterangan = "Perpanjang akun 2 minggu";
            $jumlah = 110000+rand(111,999);
            $price = 110000;
            $time = '2 weeks';
        } else if($durasi == 30){
            $keterangan = "Perpanjang akun 1 bulan";
            $jumlah = 180000+rand(111,999);
            $price = 180000;
            $time = '1 month';
        }
        if($method == 'bca') {
          $tujuan = "5505164251 a/n Syarif H (BCA)";
          $id = rand(1111,9999);
          $data = [
            'tujuan' => $tujuan,
            'jumlah' => $jumlah,
            'tanggal' => date('Y-m-d'),
            'id' => $id,
            'id_user' => auth()->user()->id,
            'username' => auth()->user()->username,
            'keterangan' => $keterangan,
            'bank' => $method,
            'durasi' => $durasi
          ];
          session(['auto_extend' => $data]);
          return redirect()->action('UserController@autoExtendView');
        } else if ($method == 'saldo') {
          if(auth()->user()->saldo < $price){
            $message = ['Message' => 'Saldo tidak mencukupi'];
            session()->flash('message', $message);
            return redirect()->back();
          }
          $username = auth()->user()->username;
          $user = User::where('username', '=', $username)->first();
          if (time() <= strtotime($user->expired_date)) {
            $newexp = date('Y-m-d', strtotime('+'.$time, strtotime($user->expired_date)));
            $user->expired_date = $newexp;
            $save = $user->save();
          } else {
            $newexp = date('Y-m-d', strtotime('+'.$time));
            $user->expired_date = $newexp;
            $save = $user->save();
          }
          if($save){
            Helper::subtractSaldo(auth()->user()->id,$price);
            Helper::saveUserBalanceHistory(auth()->user()->id, $price, 'debit', 'Perpanjangan durasi akun sendiri dengan durasi '.$time, 'complete');
            $message = ['Message' => 'Perpanjangan Durasi akun anda telah berhasil'];
            session()->flash('message', $message);
            return redirect()->action('UserController@autoExtendView');
          } else {
            $message = ['Error' => 'Terjadi kesalahan pada sistem silahkan coba lagi dengan melakukan refresh pada halaman'];
            session()->flash('message', $message);
            return redirect()->back();
          }
        } else {
          $message = ['Error' => 'Error, harap logout dan bersihkan cache browser'];
          session()->flash('message', $message);
          return redirect()->back();
        }
      } else {
        return abort(404);
      }
    }

    public function autoExtendNext() {
      if($addsaldo = session("auto_extend")) {
        Helper::checkLevel(['member', 'reseller', 'priority', 'admin']);
        if (Helper::isUserRegisteredByAdmin()) {
          $tgl    = date("j-n-Y");
          $addsal = session("auto_extend");
          $bank   = $addsaldo['bank'];
          $jumlah = $addsaldo['jumlah'];
          $username  = $addsaldo['username'];
          $id_user  = $addsaldo['id_user'];
          $durasi = $addsaldo['durasi'];
          $tglTrx     = $addsaldo['tanggal'];
          if($durasi == 3){
              $ket = "Perpanjang akun 3 hari";
              $time = '3 days';
          } else if($durasi == 7){
              $ket = "Perpanjang akun 1 minggu";
              $time = '1 week';
          } else if($durasi == 14){
              $ket = "Perpanjang akun 2 minggu";
              $time = '2 weeks';
          } else if($durasi == 30){
              $ket = "Perpanjang akun 1 bulan";
              $time = '1 month';
          }
          if($bank == 'bca') {
            $source   = Bank::grab_bca('sarifhid0302', '010206', $tgl);
            $exp      = explode('<b>Saldo</b></font></div></td>', $source);
            $jkt_time = time() + (3600 * 1);
            $tahun    = date('Y', $jkt_time);
            if (isset($exp[1])) {
              $sukses = 0;
              $table = explode("</table>", $exp[1]);
              $tr    = explode("<tr>", $table[0]);
              for ($i = 1; $i < count($tr); $i++) {
                $str = str_ireplace('</font>', '#~#~#</font>', $tr[$i]);
                $str = str_ireplace('<br>', '<br> ', $str);
                $str = preg_replace('!\s+!', ' ', trim(strip_tags($str)));

                $arr    = array_map('trim', explode("#~#~#", $str));
                $dbpend = $arr[4];

                $arr[0]     = date('d/m', $jkt_time);
                $tgl        = $arr[0] . '/' . $tahun;
                $keterangan = $arr[1]; //keterangan ini adalah keterangan di mutasi
                $kredit     = Bank::fix_angka_bca($arr[3]); //kredit ini adalah nominal mutasi
                if ($kredit == $jumlah) { // nah ini proses kalau nominal yang kita cari di jumlah ada berarti artinya sukses
                  $sukses = 1;
                }
              }
              if ($sukses) {
                $username = auth()->user()->username;
                $user = User::where('username', '=', $username)->first();
                if (time() <= strtotime($user->expired_date)) {
                  $newexp = date('Y-m-d', strtotime('+'.$time, strtotime($user->expired_date)));
                  $user->expired_date = $newexp;
                  $save = $user->save();
                } else {
                  $newexp = date('Y-m-d', strtotime('+'.$time));
                  $user->expired_date = $newexp;
                  $save = $user->save();
                }
                if($save){
                  Helper::saveUserBalanceHistory(auth()->user()->id, $jumlah, 'debit', 'Transfer Untuk Perpanjang Durasi Otomatis akun sendiri dengan durasi '.$time, 'complete');
                  $message = [
                    'Message' => 'Tambah saldo otomatis berhasil!',
                    'username' => $username,
                    'Bank' => $bank,
                    'Keterangan' => $ket,
                    'Keterangan Mutasi' => $keterangan,
                    'Jumlah' => $jumlah,
                    'Tgl Transaksi' => $tglTrx,
                    'status' => 'Berhasil'
                  ];
                  session()->flash('message', $message);
                  session()->forget('auto_extend');
                  return redirect()->action('UserController@autoExtendView');
                } else {
                  $message = ['Error' => 'Terjadi kesalahan pada sistem silahkan coba lagi dengan melakukan refresh pada halaman'];
                  session()->flash('message', $message);
                  return redirect()->back();
                }
              } else {
                $message = [
                  'Message' => 'Anda belum melakukan pembayaran',
                ];
                session()->flash('message', $message);
                return redirect()->action('UserController@autoExtendView');
              }
            } else {
              $message = [
                'Message' => 'Akun E-Bank admin bermasalah',
              ];
              session()->flash('message', $message);
              return redirect()->action('UserController@autoExtendView');
            }
          } else {
            return abort(505);
          }
        } else {
          return abort(505);
        }
      } else {
        return abort(404);
      }
    }

    public function autoExtendPrev() {
      if($addsaldo = session("auto_extend")) {
        Helper::checkLevel(['member', 'reseller', 'priority', 'admin']);
        if (Helper::isUserRegisteredByAdmin()) {
          $message = [
            'message' => 'Pembatalan berhasil'
          ];
          session()->flash('message', $message);
          session()->forget('auto_extend');
          return redirect()->action('UserController@autoExtendView');
        } else {
          return abort(505);
        }
      } else {
        return abort(404);
      }
    }

    public function autoExtendView() {
      Helper::checkLevel(['member', 'reseller', 'priority']);
      if (Helper::isUserRegisteredByAdmin()) {
        return view('user.auto-extend');
      } else {
        return abort(404);
      }
    }
    
    

    public function suspend($id){
      $user = User::find($id);
      if($user->status == 'suspend'){
        $user->status = 'aktif';
      }
      else{
        $user->status = 'suspend';
      }
      if($user->save()){
        return 'success';
      }
    }
    public function error(){
      return abort(404);
    }
    
    public function panelname(){
        Helper::checkLevel(['reseller']);
        return view('user.panelname');
    }
    
    public function mypanel(){
        
        $con = mysqli_connect('localhost', 'instagr9_panel', 'T;y^54SN@!Sa', 'instagr9_panel');
        $query = mysqli_query($con, "UPDATE users_panel SET panelname='".$_POST['panelname']."' WHERE register_by='".$_POST['register_by']."' ");
        
        
        return redirect('/reseller/panelname');
        
    }
    
    public function subserver(){
        if(auth()->user()->level == 'admin'){
        $users = User::where('expired_date', '>', date('Y-m-d h:i:s'))->paginate(10);
      } else if(auth()->user()->level == 'reseller') {
        $users = User::where('register_by', auth()->user()->username)->where('expired_date', '>', date('Y-m-d h:i:s'))->paginate(10);
      } else {
        return abort(505);
      }
      
        // $datasubsatu = \App\History::where('submitted_by', $user->username)->where('type', 'Like Server 1')->whereDate('created_at', '=', date('Y-m-d'))->paginate(20);
        // $datasubdua = \App\History::where('submitted_by', $user->username)->where('type', 'Like Server 2')->whereDate('created_at', '=', date('Y-m-d'))->paginate(20);
        return view('user.subserver', compact('users'));
        
        
    }
    
    public function subserverjs(){
        Helper::checkLevel(['admin']);
          
        // $users = User::where('expired_date', '<', date('Y-m-d h:i:s'))->get();
        // SELECT submitted_by FROM `users_history` WHERE DATE('created_at') = NOW() GROUP_BY submitted_by
        $users = \DB::table('users_history')->whereDate('created_at', '=', date('Y-m-d'))->select('submitted_by', \DB::raw('count(*) as total'))->groupBy('submitted_by')->get();
        
        
        // $users = User::where('expired_date', '<', date('Y-m-d h:i:s'))->join('users_history', 'users.username', 'users_history.submitted_by')->get();
        
          
          $button = '';
          $data = [];
          foreach($users as $key => $user){
            $class = '';
            
            
            
            $data[$key] = [
              'username' => $user->submitted_by,
              'subserver' =>  $user->total
            ];
    
          }
          
    
          return DataTables::of($data)->make(true);
    }
    
    public function subserverlist(){
        Helper::checkLevel(['admin']);
          
        $users = \DB::table('subserver')
                    ->join('users', 'subserver.user_id', '=', 'users.id')
                    ->where('date', date('Y-m-d'))
                    ->get();
        
          
          $data = [];
          foreach($users as $key => $user){
            
            $data[$key] = [
              'username' => $user->username,
              'server1' =>  $user->server1,
              'server2' =>  $user->server2,
              'server3' =>  $user->server3,
              'total'   =>  $user->server1 + $user->server2,
              'date'    =>  $user->date
            ];
    
          }
          
    
          return DataTables::of($data)->make(true);
        
    }
    
    public function sublist(){
        
    	return view('user.total-sub');
    
    }

}
