<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Yajra\Datatables\Datatables;
use DB;

class OrderSocmedController extends Controller
{

    public function index(){
    	$category 	= DB::table('service_categories')->where('code', 'SOCMED')->get();
    	$service 	= DB::table('services')->get();

    	return view('server.order.index', compact('service', 'category'));
    }

    public function inc_service(Request $request){
		$service = DB::table('services')->where('category', $request->category)
								->where('status', 'active')
								->orderBy('sid')
								->get();
		
    	return view('inc.order_service', compact('service'));
    }

    public function inc_note(Request $request){
    	
    	$note = DB::table('services')->where('sid', $request->service)
    						->where('status', 'active')
    						->get();

    	return view('inc.order_note', compact('note'));
    }

    public function inc_rate(Request $request){

		$service = DB::table('services')->where('sid', $request->service)->where('status', 'active')->get();
		foreach($service as $data){
			$result = $data->price / 1000;
			echo $result;
		}

    }

    public function orders(Request $request){

    	$auth = \Auth::User();
    	$post_service = $request->service;
		$post_quantity = $request->quantity;
		$post_link = trim($request->link);
		$post_category = $request->category;
		$kos = "https://kamkos.me/module.php?authId=137e5fddf13dc82ee786bd9ad69157edb1154084cc99a4b2a484d700ab8fb3ec&modulePath=superflow&moduleId=push&";
		$prov1 = "JAP";
		$prov2 = "REGRAM";
		$prov3 = "SMMLITE";
		$prov4 = "KAMKOS";
		$prov5 = "RM";
		$prov6 = "VIQHRIL";
		$prov7 = "UBAI1";
		$prov8 = "SUPARDI1";
		$prov9 = "SUPARDI2";
		$prov10 = "UBAI2";
		$prov11 = "VMP";
		$prov12 = "RMFOLLOWERS";
		$prov13 = "RMLIKES";
		$prov14 = "MENTALIS";

		if (!empty($post_service) || !empty($post_link)){
			
			$data_service = DB::table('services')->where('sid', $post_service)->where('status', 'active')
				->first();

	        $data_orders = DB::table('orders')->where('link', $post_link)->whereIn('status', ['pending', 'processing'])->first();
	        
	        if($data_service == NULL){
	            $request->session()->flash("status", "Gagal: Pastikan mengisi form dengan benar !");
	            return redirect()->back();
	        }

			$rate = $data_service->price / 1000;
			$price = $rate*$post_quantity;
			$oid = 'NO-'.$this->generate(6);
			$service = $data_service->service;
			$provider = $data_service->provider;
			$pid = $data_service->pid;

			$data_provider = DB::table('providers')->where('code', $provider)->first();
		}

		if (empty($post_service) || empty($post_link) || empty($post_quantity)) {
			$msg_type = "status";
			$msg_content = "Gagal: Mohon mengisi input.";
		}else if ($data_service == NULL) {
			$msg_type = "status";
			$msg_content = "Gagal: Layanan tidak ditemukan.";
		} else if ($data_provider == NULL) {
			$msg_type = "status";
			$msg_content = "Gagal: Server Maintenance.";
		} else if ($post_quantity < $data_service->min) {
			$msg_type = "status";
			$msg_content = "Gagal: Jumlah minimal adalah ".$data_service->min.".";
		} else if ($post_quantity > $data_service->max) {
			$msg_type = "status";
			$msg_content = "Gagal: Jumlah maksimal adalah ".$data_service->max.".";
		} else if ($auth->saldo < $price) {
			$msg_type = "status";
			$msg_content = "Gagal: Saldo Anda tidak mencukupi untuk melakukan pembelian ini.";
		} else {

			$api_link = $data_provider->link;
			$api_key  = $data_provider->api_key;

			if($provider == $prov1){
				$order_postdata = "key=$api_key&action=add&service=$pid&link=$post_link&quantity=$post_quantity";	
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $api_link);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $order_postdata);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $chresult = curl_exec($ch);
                curl_close($ch);
                $order_data = json_decode($chresult, true);
                $poid = $order_data['order'];
			}else if ($provider == $prov2) {
                $order_postdata = "api_key=$api_key&product=$pid&data=$post_link&quantity=$post_quantity";	
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $api_link);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $order_postdata);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $chresult = curl_exec($ch);
                curl_close($ch);
                $order_data = json_decode($chresult, true);
                
                
                if($order_data['status'] == false){
                    echo 'yee';
                }else{
                    $poid = $order_data['data']['code'];
                }
               
                
            }else if ($provider == $prov3) {
			    $order_postdata = "key=$api_key&action=add&service=$pid&link=$post_link&quantity=$post_quantity";	
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $api_link);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $order_postdata);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $chresult = curl_exec($ch);
                curl_close($ch);
                $order_data = json_decode($chresult, true);
                $poid = $order_data['order'];
            } else if ($provider == $prov4) {
			    $order_postdata = "";	
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $kos.'productId='.$pid.'&usernameLink='.$post_link.'&orderAmount='.$post_quantity);
                curl_setopt($ch, CURLOPT_POST, 1);
                
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $chresult = curl_exec($ch);
                curl_close($ch);
                $order_data = json_decode($chresult, true);
                $poid = $order_data['order'];
            }else if($provider == $prov5){
                
            	$order_postdata = "api=$api_key&action=add&type=$pid&link=$post_link&quantity=$post_quantity";	
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $api_link);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $order_postdata);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $chresult = curl_exec($ch);
                curl_close($ch);
                $order_data = json_decode($chresult, true);
                $poid = $order_data['info']['order']['order_id'];;
                    
            	
            }else if($provider == $prov6){
                $postdata = 'urlxx='.$post_link.'&jumlahlahx='.$post_quantity;
                
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $api_link);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT,10);
                $result = curl_exec($ch);
                curl_close($ch);
                
                $poid = 'ok';
            }else if($provider == $prov7){
                
                $postdata = $api_link.'?link='.$post_link.'&quantity='.$post_quantity.'&types=120';
        
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $postdata);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                
        
                curl_setopt($ch,CURLOPT_TIMEOUT, 5);
                
                $za = curl_exec($ch);
                
                
            			
                curl_close($ch);
                
                $order = json_encode($za);
                
                $ambil=	json_decode($za,true);
                
                $poid = 'ok';
       
            
            }else if($provider == $prov8){
                $postdata = 'url='.$post_link.'&jumlah='.$post_quantity.'&server=like1';
                
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $api_link);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT,10);
                $result = curl_exec($ch);
                curl_close($ch);
                
                $poid = 'ok';
            }else if($provider == $prov9){
                $postdata = 'url='.$post_link.'&jumlah='.$post_quantity.'&server=like2';
                
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $api_link);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT,10);
                $result = curl_exec($ch);
                curl_close($ch);
                
                $poid = 'ok';
            
            }else if($provider == $prov10){
                $postdata = $api_link.'?link='.$post_link.'&quantity='.$post_quantity.'&types=112';
        
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $postdata);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                
        
                curl_setopt($ch,CURLOPT_TIMEOUT, 5);
                
                $za = curl_exec($ch);
                
                
            			
                curl_close($ch);
                
                $order = json_encode($za);
                
                $ambil=	json_decode($za,true);
                
                $poid = 'ok';
            }else if($provider == $prov11){
            
                $postdata = "api_key=$api_key&action=order&service=$pid&data=$post_link&quantity=$post_quantity";

                  $ch = curl_init('https://vip-member.id/api/json');
                
                  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                  curl_setopt($ch, CURLOPT_POST, 1);
                  curl_setopt($ch, CURLOPT_HEADER, 0);
                  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                
                  curl_setopt($ch, CURLOPT_POST, true);
                  curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
                
                  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
                  $results = curl_exec($ch);
                  if (curl_errno($ch)) {
                      $results = curl_error($ch);
                  }
                
                  curl_close($ch);
                
                  $order  = json_encode($results);
                  $ambil  = json_decode($results,true);
                
                  $poid = $ambil['data']['order_id'];
            }else if($provider == $prov12){
                
            	$order_postdata = "api=$api_key&action=add&type=$pid&link=$post_link&quantity=$post_quantity";	
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $api_link);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $order_postdata);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $chresult = curl_exec($ch);
                curl_close($ch);
                $order_data = json_decode($chresult, true);
                
                if(isset($order_data['info']['order']['order_id'])){
                 $poid = $order_data['info']['order']['order_id'];
               }
                    
            	
            }else if($provider == $prov13){
                
            	$order_postdata = "api=$api_key&action=add&type=$pid&link=$post_link&quantity=$post_quantity";	
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $api_link);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $order_postdata);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $chresult = curl_exec($ch);
                curl_close($ch);
                $order_data = json_decode($chresult, true);
                
                if(isset($order_data['info']['order']['order_id'])){
                 $poid = $order_data['info']['order']['order_id'];
               }
                    
            	
            }else if($provider == $prov14){
                $api = 'https://mentalispanel.id/api/json.php';
               
                $postdata = "api_key=$api_key&action=order&data=$post_link&service=$pid&quantity=$post_quantity";
            	
                 $ch = curl_init('https://mentalispanel.id/api/json.php');
           
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                   
                   
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
           
               
                curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
                $results = curl_exec($ch);
                if (curl_errno($ch)) {
                    $results = curl_error($ch);
                }
                       
                curl_close($ch);
               
                $order = json_encode($results);
                $ambil= json_decode($results,true);
                
                
                if(isset($ambil['data']['id'])){
                    $poid = $ambil['data']['id'];
                }
            }else{
		        die("System Error");
			}


			if(empty($poid)){
				$msg_type = "status";
			    $msg_content = "Server Segera Kembali";
			}else{
				$saldo_awal 	= $auth->saldo;
				$saldo_akhir 	= $auth->saldo - $price; 

				$update_user = \App\User::where('username', $auth->username)->first();

				$update_user->saldo = $saldo_akhir;
				$update_user->save();


				if($update_user == TRUE){
					
					$insert_order = DB::table('SaldoHistory')->insert([
					   'username' => $auth->username,
					   'action' => 'Cut Balance',
					   'quantity' => $price,
					   'balance_now' => $saldo_akhir,
					   'msg' => 'Saldo dipotong untuk pembelian '.$post_quantity. ' ' . $service .', '. $oid,
					   'date' => date('Y-m-d'),
					]);

					
					if($provider == 'VIQHRIL' || $provider == 'UBAI1' || $provider == 'SUPARDI1' || $provider == 'SUPARDI2'  || $provider == 'UBAI2' ){
					    $statusinsert = 'Success';
					}else{
					    $statusinsert = 'Pending';
					}
					
					$insert_order = DB::table('orders')->insert([
					    'oid' => $oid,
					    'poid' => $poid,
					    'user' => $auth->username,
					    'service' => $service,
					    'link' => $post_link,
					    'quantity' => $post_quantity,
					    'price' => $price,
					    'start_count' => 0,
					    'remains' => 0,
					    'status' => $statusinsert,
					    'provider' => $provider,
					    'date' => date('Y-m-d'),
					    'place_form' => 'WEB',
					    'refund' => '0',
					]);

					if ($insert_order == TRUE) {
						$msg_type = "status";
						$msg_content = "Pesanan telah diterima. 
						Layanan: $service 
						Jumlah: ".number_format($post_quantity,0,',','.')."
						Biaya: Rp ".number_format($price,0,',','.');
					} else {
						$msg_type = "error";
						$msg_content = "Gagal: Error system (2).";
					}

				}else{
					$msg_type = "error";
					$msg_content = "Gagal: Error system (1).";
				}
			}
			
		}

		$request->session()->flash($msg_type, $msg_content);
		return redirect()->back();

		
    }


    public function generate($panjang){

	$karakter = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
	$string = '';
	for($i = 0; $i < $panjang; $i++) {
		$pos = rand(0, strlen($karakter)-1);
		$string .= $karakter{$pos};
	}
	return $string;

    }

    public function history(){
        
    	return view('orders.socmed.history');
    }
    
    public function historys(){
        
        return view('orders.socmed.historys', compact('mydata'));
    }

    public function histo(){
    	$query = DB::table('orders')->where('user', \Auth::user()->username)->orderBy('id', 'DESC');
        return DataTables::of($query)->toJson();
    }
    public function getLayanan(){
        
        $key = "53155f07429d66115dd199a5fda0769c"; // your api key
        $postdata = "key=$key&action=services";
         
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://justanotherpanel.com/api/v2");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $chresult = curl_exec($ch);
        //echo $chresult;
        curl_close($ch);
        $json_result = json_decode($chresult, true);
        dd($json_result);
        $indeks=0;
        $i = 1;
        // get data service
        while($indeks < count($json_result)){
           
            $category=$json_result[$indeks]['category'];
            $id =$json_result[$indeks]['service'];
            $service = $json_result[$indeks]['name'];
            $min_order =$json_result[$indeks]['min'];
            $max_order = $json_result[$indeks]['max'];
            $note = $json_result[$indeks]['note'];
            $price = $json_result[$indeks]['rate'];
            $indeks++;
            $i++;
            // end get data service
            // setting price
            $rate = $price * 15500;
            $rate_asli = $rate; //setting penambahan harga
            // setting price
            $check_services_pulsa = mysqli_query($db, "SELECT * FROM services WHERE id = '$id'");
            $data_services_pulsa = mysqli_fetch_assoc($check_orders);
            if(mysqli_num_rows($check_services_pulsa) > 0) {
                echo "Service Sudah Ada Di database => $service \n <br />";
            } else {
                       
                $insert=mysqli_query($db, "INSERT INTO services (id, sid, category, service, note, min, max, price, status, pid, provider) VALUES ('$id','$id','$category','$service','$note','$min_order','$max_order','$rate_asli','Active','$id','JAP')");//Memasukan Kepada Database (OPTIONAL)
                if($insert == TRUE){
                echo"SUKSES INSERT -> Kategori : $category || ID : $id ||  Service :$service <br />";
                }else{
                    echo "GAGAL MEMASUKAN DATA";
                   
                }
            }
        }
    }
}
