<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use \App\Rules\Count;

class ServerController extends Controller
{
	public function __construct()
    {
        $this->middleware(function ($request, $next) {
            if(auth()->check()){

                //SET PERMISSION WHO CAN VISIT THIS CONTROLLER
                $allow = ['admin', 'member', 'reseller', 'priority'];

                $level = auth()->user()->level;
                if(!in_array($level, $allow)){
                    abort(505);
                }
            }
            else{
                return redirect('/login');
            }
            return $next($request);
        });
    }

    public function validateAction($serverLink, $id){
        //define server list
        $serverList = ['voyager', 'envoyer', 'forge'];
        if(in_array($serverLink, $serverList)){
            //define server ON
            if($serverLink == 'voyager'){
                $serverOn = ['1'];
            } else if($serverLink == 'envoyer'){
                $serverOn = ['2'];
            } else if($serverLink == 'forge'){
                $serverOn = [''];
            }
            if(in_array($id, $serverOn)){
                return TRUE;
            }
        }

        return abort(505);
    }

    public function server($serverLink, $id = ''){
        if($this->validateAction($serverLink, $id)){
            switch($id) {
                case '1':
                    $max = 1000;
                    break;
                case '2':
                    $max = 1000;
                    break;
                default:
                    $max = 1000;
                    break;
            }
            
            return view('server.like', compact('serverLink', 'id', 'max'));
        }
        return abort(505);
    }

    public function submitLike($serverLink, $id = ''){
        // $like = 'like_'.$id;
        $like = 'like_1';

        switch($id) {
            case '1':
                $max = 1000;
                break;
            case '2':
                $max = 1000;
                break;
            default:
                $max = 1000;
                break;
        }
        

        request()->validate([
            
            'url' => 'required',
            'jumlah' => 'required|numeric|max:'.$max
        ]);

        if(\Carbon\Carbon::now() < auth()->user()->delay->$like){
            return abort(505);
        }


        
        if(auth()->check()){
                

                $level = auth()->user()->level;
                if($level == 'admin'){
                    $delay = 2;
                }else{
                    $delay = 10;
                }
            }


        // \App\Delay::where('user_id', auth()->user()->id)->update(['like_global' => date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . $delay . ' minute'))]);
       //\App\Delay::where('user_id', auth()->user()->id)->update(['like_'.$id => date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . $delay . ' minute'))]);
       
       \App\Delay::where('user_id', auth()->user()->id)->update(['like_1' => date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . $delay . ' minute'))]);

        if($this->validateAction($serverLink, $id)){
            $server = $id;
            $result = '';
            $subdomain = '';

            set_time_limit(0);
            $c = curl_init('https://api.instagram.com/oembed/?url='.trim(request()->url));
            curl_setopt($c,CURLOPT_RETURNTRANSFER,1);
            curl_setopt($c,CURLOPT_SSL_VERIFYPEER,0);
            curl_setopt($c,CURLOPT_USERAGENT,"SEBASTIANW-PC 11/23.01.78.64 Recognized as Mozilla(AppleWebKit SPA)");
            $x = curl_exec($c);
            $xinfo = curl_getinfo($c);
            curl_close($c);
            


            if ($xinfo['http_code'] !== 200) {
                $mediaid = null;
            } else {
                $mediaid = json_decode($x);
                $mediaid = $mediaid->media_id;
                $mediaid = explode("_", $mediaid);
                $mediaid = $mediaid[0];
            }
            
            
            
            
            $jumlah = request()->jumlah;

    	   	$kataUnik = md5("f6cd3459f9a39c9784b3e328f05be0f7");
    	   	$idHash = hash("md4", $mediaid);
    	   	$jmLHash = hash("sha256", $jumlah);
    	   	$kesimpulan = md5(sha1(hash("md4", $kataUnik.".".$idHash.".".$jmLHash)));
      
            $data['id'] = $mediaid;
            $data['jumlah'] = $jumlah;
            $data['kesimpulan'] = $kesimpulan;
            
            switch($server) {
                case '1':
                    $urlServer = "http://instagram.vip-member.net/free/liker/hackplease-2.php";
                    $result = $this->curlLike($urlServer, $data, $server);
                break;
                case '2':
                    $urlServer = "http://instagram.vip-member.net/free/liker/hackplease-2.php";
                    $result = $this->curlLike($urlServer, $data, $server);
                break;
                
                default:
                break;
            }
            
            
            //save to user history
            $history = new \App\History;
            $history->submitted_by = auth()->user()->username;
            $history->target = request()->url;
            $history->type = 'Like Server '.$server;
            $history->total_submit = request()->jumlah;
            
            $history->ip = $_SERVER['REMOTE_ADDR'];
            $history->save();

            //add delay based on server id

            session()->flash('result', $result);
            if($id == ''){
                $id = 1;
            }
            return redirect('server/'.$serverLink.'/'.$id);
            
        }
        return abort(505);
    }
    
    public function story(){
        return view('server.story');
    }

    public function comment(){
        // return abort(505);
        return view('server.comment');
    }

    public function submitComment(){
        // return abort(505);
        request()->validate([
            'g-recaptcha-response' => 'required|captcha',
            'url' => 'required',
            'comment' => ['required', new Count]
        ]);
				$result = '';
        if(auth()->check()){
                

                $level = auth()->user()->level;
                if($level == 'admin'){
                    $delay = 2;
                }else{
                    $delay = 10;
                }
            }
            else{
                $delay = 10;
            }

        \App\Delay::where('user_id', auth()->user()->id)->update(['comment' => date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . $delay . ' minute'))]);
        
        
        //   $login = $this->curl('http://ifun.masoek.in/masuk/userlogin.php', 'username=Ivan&password=91akerhPaQ');
        // if($login){
        //     $result = $this->curl('http://ifun.masoek.in/tambahcommentz.php','urlnyax='.request()->url.'&commentar='.request()->comment);
        // }
        
        set_time_limit(0);
            $c = curl_init('https://api.instagram.com/oembed/?url='.trim(request()->url));
            curl_setopt($c,CURLOPT_RETURNTRANSFER,1);
            curl_setopt($c,CURLOPT_SSL_VERIFYPEER,0);
            curl_setopt($c,CURLOPT_USERAGENT,"SEBASTIANW-PC 11/23.01.78.64 Recognized as Mozilla(AppleWebKit SPA)");
            $x = curl_exec($c);
            $xinfo = curl_getinfo($c);
            curl_close($c);
            

            if ($xinfo['http_code'] !== 200) {
                $mediaid = null;
            } else {
                $mediaid = json_decode($x);
                $mediaid = $mediaid->media_id;
                $mediaid = explode("_", $mediaid);
                $mediaid = $mediaid[0];
            }
        
        $count = count(explode("\n", request()->comment));
        
        $kataUnik = md5("u1ppTrgs342312ndhabsd!er@#"); 
        $idHash = hash("md4", $mediaid);
    	$jmLHash = hash("sha256", $count);
    	
    	$kesimpulan = md5(sha1(hash("md4", $kataUnik.".".$idHash.".".$jmLHash)));
    	
    	$result = $this->curl('http://instagram.vip-member.net/free/Ty5456/123iuyt.php', 'id_autolike='.$mediaid.'&jml_autolike='.request()->comment.'&hash_autolike='. $kesimpulan);

        //save to user history
        $history = new \App\History;
        $history->submitted_by = auth()->user()->username;
        $history->target = request()->url;
        $history->type = 'comment';
        $history->total_submit = count(explode(PHP_EOL, request()->comment));
        $history->save();

        //add delay based on server id
        $flash_msg = "<div class=\"alert alert-success\"><b>BERHASIL:</b> Permintaan Anda sedang diproses.<br />Layanan: Instagram Comment Indonesia<br />Post Target: ". request()->url ."<br />Jumlah: ".number_format($count, 0,',','.')."<br>Mohon gunakan dengan bijak.</div>";
        session()->flash('result', $flash_msg);
        return redirect('server/comment');
    }
    

    public function curl($url, $postdata = ''){
    	$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        if($postdata !== ''){
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        }
        curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
        curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT,5);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public function curlLike($urlServer, $data, $server)
    {
        $ca = curl_init();
        curl_setopt($ca, CURLOPT_URL, $urlServer);
        curl_setopt($ca, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ca, CURLOPT_POST, true);
        $data = array(
                    'id_autolike'  => $data['id'],
                    'jml_autolike' => $data['jumlah'],
                    'hash_autolike'=> $data['kesimpulan'],
                    'server'       => $server,
                 );
        curl_setopt($ca,CURLOPT_TIMEOUT, 10);
        curl_setopt($ca, CURLOPT_POSTFIELDS, $data);
        $za = curl_exec($ca);
        curl_close($ca);

        return $za;
    }
    
    
}
