<?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 ExtendController extends Controller
{
    public function autoExtendView() {

        return view('user.auto-extends');
      
    }
    
    public function autoExtendPrev() {
      if($addsaldo = session("auto_extend")) {
       
          $message = [
            'message' => 'Pembatalan berhasil'
          ];
          session()->flash('message', $message);
          session()->forget('auto_extend');
          return redirect()->action('ExtendController@autoExtendView');
       
      } else {
        return abort(404);
      }
    }
    
    public function autoExtend(Request $request) {
        $request->validate([
          'method' => 'required|in:bca',
          'durasi' => 'required|in:7,14,30'
        ]);
        $durasi = request('durasi');
        $method  = request('method');
        $u_name = request('username');
        
        $cekuser = \App\User::Where('username', $u_name)->first();
        
        if($cekuser == NULL){
            $message = ['Message' => 'Username Tidak Ditemukan !'];
            session()->flash('message', $message);
            return redirect()->back();
          }
          
        if($cekuser->level == 'priority'){
            if($durasi == 3){
            $keterangan = "Perpanjang akun 3 hari";
            $jumlah = 35000+rand(111,999);
            $price = 35000;
            $time = '3 days';
            } else if($durasi == 7){
                $keterangan = "Perpanjang akun 1 minggu";
                $jumlah = 40000+rand(111,999);
                $price = 40000;
                $time = '1 week';
            } else if($durasi == 14){
                $keterangan = "Perpanjang akun 2 minggu";
                $jumlah = 70000+rand(111,999);
                $price = 70000;
                $time = '2 weeks';
            } else if($durasi == 30){
                $keterangan = "Perpanjang akun 1 bulan";
                $jumlah = 120000+rand(111,999);
                $price = 120000;
                $time = '1 month';
            }
        }else{
            if($durasi == 3){
            $keterangan = "Perpanjang akun 3 hari";
            $jumlah = 35000+rand(111,999);
            $price = 35000;
            $time = '3 days';
            } else if($durasi == 7){
                $keterangan = "Perpanjang akun 1 minggu";
                $jumlah = 60000+rand(111,999);
                $price = 60000;
                $time = '1 week';
            } else if($durasi == 14){
                $keterangan = "Perpanjang akun 2 minggu";
                $jumlah = 100000+rand(111,999);
                $price = 100000;
                $time = '2 weeks';
            } else if($durasi == 30){
                $keterangan = "Perpanjang akun 1 bulan";
                $jumlah = 170000+rand(111,999);
                $price = 170000;
                $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' => $cekuser->id,
            'username' => $cekuser->username,
            'keterangan' => $keterangan,
            'bank' => $method,
            'durasi' => $durasi
          ];
          session(['auto_extend' => $data]);
          return redirect()->action('ExtendController@autoExtendView');
        } else if ($method == 'saldo') {
          if($cekuser->saldo < $price){
            $message = ['Message' => 'Saldo tidak mencukupi'];
            session()->flash('message', $message);
            return redirect()->back();
          }
          $username = $cekuser->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($cekuser->id,$price);
            Helper::saveUserBalanceHistory($cekuser->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('ExtendController@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();
        }
     
    }
    
    public function autoExtendNext() {
      if($addsaldo = session("auto_extend")) {
          
          $cekuser = \App\User::where('username', $addsaldo['jumlah'])->first();
        
        
          $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 = $cekuser->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($cekuser->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('ExtendController@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('ExtendController@autoExtendView');
              }
            } else {
              $message = [
                'Message' => 'Akun E-Bank admin bermasalah',
              ];
              session()->flash('message', $message);
              return redirect()->action('ExtendController@autoExtendView');
            }
          } else {
            return abort(505);
          }
        
      } else {
        return abort(404);
      }
    }
}