<?php
session_start();
require_once '../../../config.php';
load('middleware', 'user');

if ($_SESSION['user']['level'] !== "Admin") {
    header('location:' . base_url('id'));
}
$date = date('Y-m-d H:i:s');
$kode_deposit = $_GET['order_id'];
$cek = $db->query("SELECT * FROM pembelian_guest WHERE order_id='$kode_deposit' AND status = 'Pending'");
while($data_depo = $cek->fetch_assoc()){
    $db->query("UPDATE pembelian_guest SET date_update='$date' WHERE order_id='".$data_depo['order_id']."' AND harga='".$data_depo['harga']."'");
    if($data_depo->num_rows !== 0){
        $fetch_pesanan = $data_depo;
        $query_layanan = mysqli_query($db, "SELECT * FROM layanan_pulsa WHERE id ='".$fetch_pesanan['layanan_id']."' AND provider_id='".$fetch_pesanan['sku']."'");
        if (mysqli_num_rows($query_layanan) == 0) {
            $_SESSION['alert'] = ['danger', 'Terjadi kesalahan!', 'Layanan Tidak Ditemukan'];
            exit(header('location: /id/invoice?no='.$fetch_pesanan['order_id']));

        }else{
                    $fetch_layanan = mysqli_fetch_assoc($query_layanan);
                    if ($fetch_layanan['provider'] == 'DF') {
                        $DFS = mysqli_query($db, "SELECT * FROM provider WHERE code = 'DF'");
                        $DF = mysqli_fetch_assoc($DFS);
                        $reff = $fetch_pesanan['order_id'];
                        $df_user = $DF['api_id'];
                        $df_key = $DF['api_key'];
                        
                        $post_data = json_encode([
                            'username' => $df_user,
                            'buyer_sku_code' => $fetch_pesanan['sku'],
                            'customer_no' => $fetch_pesanan['target'].$fetch_pesanan['additional_target'],
                            'ref_id' => $reff,
                            'sign' => md5($df_user.$df_key.$reff),
                        ]);
        
                        $ch = curl_init();
                        curl_setopt($ch, CURLOPT_URL, 'https://api.digiflazz.com/v1/transaction');
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                        curl_setopt($ch, CURLOPT_POST, 1);
                        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
                        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
                        $result = curl_exec($ch);
                        $result = json_decode($result, true);
                        
                        if (isset($result['data'])) {
                            if ($result['data']['status'] == 'Gagal') {
                                mysqli_query($db, "UPDATE pembelian_guest SET sn = 'Silahkan Hubungi Admin', status = 'Canceled' WHERE id = '".$fetch_pesanan['id']."'");
                                if($fetch_pesanan['username'] !== "" || $fetch_pesanan['username'] !== "none"){
                                        $db->query("UPDATE users SET saldo=saldo+{$fetch_pesanan['harga']} WHERE username='{$fetch_pesanan['username']}'");
                                        $db->query("INSERT INTO history_balance VALUES ('','{$fetch_pesanan['username']}','{$fetch_pesanan['harga']}','+','$date')");
                                    }
                                $_SESSION['alert'] = ['danger', 'Terjadi kesalahan!', 'Pesanan gagal direorder. Result Digifalzz : ' . $result['data']['message']];
                                exit(header('location: /id/invoice?no='.$fetch_pesanan['order_id']));
                            } else if($result['data']['status'] == 'Sukses'){
                                $sn = $result['data']['sn'] !== '' ? $result['data']['sn'] : $result['data']['message'];
                                mysqli_query($db, "UPDATE pembelian_guest SET status = 'Success', sn='$sn' WHERE id = '".$fetch_pesanan['id']."'");
                                $_SESSION['alert'] = ['success', 'Berhasil!', 'Pesanan berhasil di reorder.'];
                                exit(header('location: /id/invoice?no='.$fetch_pesanan['order_id']));
                            } else{
                                mysqli_query($db, "UPDATE pembelian_guest SET status = 'Processing', sn='Transaksi Pending' WHERE id = '".$fetch_pesanan['id']."'");
                                $_SESSION['alert'] = ['success', 'Berhasil!', 'Pesanan berhasil di reorder.'];
                                exit(header('location: /id/invoice?no='.$fetch_pesanan['order_id']));
                            }
                        } else {
                            mysqli_query($db, "UPDATE pembelian_guest SET sn = 'Silahkan Hubungi Admin' WHERE id = '".$fetch_pesanan['id']."'");
                            if($fetch_pesanan['username'] !== "" || $fetch_pesanan['username'] !== "none"){
                                        $db->query("UPDATE users SET saldo=saldo+{$fetch_pesanan['harga']} WHERE username='{$fetch_pesanan['username']}'");
                                        $db->query("INSERT INTO history_balance VALUES ('','{$fetch_pesanan['username']}','{$fetch_pesanan['harga']}','+','$date')");
                                    }
                            $_SESSION['alert'] = ['danger', 'Terjadi kesalahan!', 'Pesanan gagal. Result Digiflazz : ' . $result['data']['message']];
                            exit(header('location: /id/invoice?no='.$fetch_pesanan['order_id']));
                        }
                    } else if ($fetch_layanan['provider'] == 'VR'){
                        $check_data = $db->query("SELECT * FROM provider WHERE code = 'VR'");
                        $vip = $check_data->fetch_assoc();
                        $params = [
                            'key' => $vip['api_key'],
                            'sign' => md5($vip['api_id'].$vip['api_key']),
                            'type' => 'order',
                            'service' => $fetch_pesanan['sku'],
                            'data_no' => $fetch_pesanan['target'],
                            'data_zone' => $fetch_pesanan['additional_target'],
                        ];
                        $curl = curl_init();
                        curl_setopt_array($curl, array(
                        CURLOPT_URL => 'https://vip-reseller.co.id/api/game-feature',
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_ENCODING => '',
                        CURLOPT_MAXREDIRS => 10,
                        CURLOPT_TIMEOUT => 0,
                        CURLOPT_FOLLOWLOCATION => true,
                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                        CURLOPT_CUSTOMREQUEST => 'POST',
                        CURLOPT_POSTFIELDS => $params,
                        CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
                        ));
                        $result = curl_exec($curl);
                        $result = json_decode($result, true);
                        if(isset($result)){
                            if($result['result'] == true){
                                $poi = $result['data']['trxid'];
                                $note = $result['data']['note'];
                                $status = $result['data']['status'];
                                if($status == 'success'){
                                    $statuss = 'Success';
                                    $db->query("UPDATE pembelian_guest SET status='$statuss', sn='Transaksi Pending', date_update='$date', provider_order_id='$poi' WHERE id='".$fetch_pesanan['id']."'");
                                    
                                    $_SESSION['alert'] = ['success', 'Berhasil!', 'Pesanan berhasil di reorder.'];
                                    exit(header('location: /id/invoice?no='.$fetch_pesanan['order_id']));
                                }else if($status == 'error'){
                                    $statuss = 'Canceled';
                                    $notes = $result['message'];
                                    $db->query("UPDATE pembelian_guest SET status='$statuss', sn='Silahkan Hubungi Admin', date_update='$date' WHERE id='".$fetch_pesanan['id']."'");
                                    if($fetch_pesanan['username'] !== "" || $fetch_pesanan['username'] !== "none"){
                                        $db->query("UPDATE users SET saldo=saldo+{$fetch_pesanan['harga']} WHERE username='{$fetch_pesanan['username']}'");
                                        $db->query("INSERT INTO history_balance VALUES ('','{$fetch_pesanan['username']}','{$fetch_pesanan['harga']}','+','$date')");
                                }
                                    $_SESSION['alert'] = ['danger', 'Failed!', 'Pesanan Gagal di reorder. Respon: '.$result['message']];
                                    exit(header('location: /id/invoice?no='.$fetch_pesanan['order_id']));
                                }else{
                                    $statuss = 'Processing';
                                    $db->query("UPDATE pembelian_guest SET status='$statuss', sn='Transaksi Pending', date_update='$date', provider_order_id='$poi' WHERE id='".$fetch_pesanan['id']."'");
                                    $_SESSION['alert'] = ['success', 'Berhasil!', 'Pesanan berhasil di reorder.' .$note];
                                    exit(header('location: /id/invoice?no='.$fetch_pesanan['order_id']));
                                }
                            }else{
                                $db->query("UPDATE pembelian_guest SET status='Canceled', sn='Silahkan Hubungi Admin', date_update='$date', provider_order_id='$poi' WHERE id='".$fetch_pesanan['id']."'");
                                if($fetch_pesanan['username'] !== "" || $fetch_pesanan['username'] !== "none"){
                                        $db->query("UPDATE users SET saldo=saldo+{$fetch_pesanan['harga']} WHERE username='{$fetch_pesanan['username']}'");
                                        $db->query("INSERT INTO history_balance VALUES ('','{$fetch_pesanan['username']}','{$fetch_pesanan['harga']}','+','$date')");
                                    }
                                $_SESSION['alert'] = ['danger', 'Failed!', 'Pesanan Gagal di proses. Respon: '.$result['message']];
                                exit(header('location: /id/invoice?no='.$fetch_pesanan['order_id']));
                                
                            }
                        }
                    } else if($fetch_layanan['provider'] == "SO"){
                        $check_data = $db->query("SELECT * FROM provider WHERE code = 'SO'");
                        $SO = $check_data->fetch_assoc();
                        $Smile = new SmileOne();
                        $result = $Smile->order($fetch_pesanan['target'],$fetch_pesanan['additional_target'],$fetch_pesanan['sku']);
                        $result = json_decode($result);
                        if(isset($result)){
                            $status = $result->status;
                            $poi = $result->trxId;
                            if($status == true){
                                $statuss = 'Processing';
                                $db->query("UPDATE pembelian_guest SET status='$statuss', sn='Transaksi Pending', date_update='$date', provider_order_id='$poi' WHERE id='".$fetch_pesanan['id']."'");
                                $_SESSION['alert'] = ['danger', 'Success!', 'Pesanan Berhasil Diproses'];
                                exit(header('location: /id/invoice?no='.$fetch_pesanan['order_id']));
                            }else{
                                $statuss = 'Canceled';
                                $db->query("UPDATE pembelian_guest SET status='$statuss', sn='{$result['message']}', date_update='$date', provider_order_id='$poi' WHERE id='".$fetch_pesanan['id']."'");
                                if($fetch_pesanan['username'] !== "" || $fetch_pesanan['username'] !== "none"){
                                    $db->query("UPDATE users SET saldo=saldo+{$fetch_pesanan['harga']} WHERE username='{$fetch_pesanan['username']}'");
                                    $db->query("INSERT INTO history_balance VALUES ('','{$fetch_pesanan['username']}','{$fetch_pesanan['harga']}','+','$date')");
                                }
                                $_SESSION['alert'] = ['danger', 'Failed!', 'Pesanan Gagal di proses.'];
                                exit(header('location: /id/invoice?no='.$fetch_pesanan['order_id']));
                            }
                        }else{
                            $statuss = 'Canceled';
                            $db->query("UPDATE pembelian_guest SET status='Canceled', sn='Harap menghubungi Admin', date_update='$date', provider_order_id='$poi' WHERE id='".$fetch_pesanan['id']."'");
                            if($fetch_pesanan['username'] !== "" || $fetch_pesanan['username'] !== "none"){
                                $db->query("UPDATE users SET saldo=saldo+{$fetch_pesanan['harga']} WHERE username='{$fetch_pesanan['username']}'");
                                $db->query("INSERT INTO history_balance VALUES ('','{$fetch_pesanan['username']}','{$fetch_pesanan['harga']}','+','$date')");
                            }
                            $_SESSION['alert'] = ['danger', 'Failed!', 'Pesanan Gagal di proses.'];
                            exit(header('location: /id/invoice?no='.$fetch_pesanan['order_id']));
                        }
                    } else if($fetch_layanan['provider'] == 'MP'){
                        $check_data = $db->query("SELECT * FROM provider WHERE code = 'MP'");
                    $MP = $check_data->fetch_assoc();
                    $result = $curl->connectPost($vip['link'].'order',['api_key' => $MP['api_key'],'api_id' => $MP['api_id'],'type' => 'order','service' => $fetch_pesanan['sku'],'target' => $fetch_pesanan['target'],'quantity' => $fetch_pesanan['quantity']]);
                   if(isset($result)){
                                $status = $result['status'];
                                $poi = $result['data']['id'];
                                if($status == true){
                                    $statuss = 'Waiting';
                                    $db->query("UPDATE pembelian_guest SET status='$statuss', sn='Pesanan Akan Di Proses Secepatnya', date_update='$date', provider_order_id='$poi' WHERE id='".$fetch_pesanan['id']."'");
                                }else if($status == false){
                                    $statuss = 'Canceled';
                                    $db->query("UPDATE pembelian_guest SET status='Canceled', sn='Silahkan Hubungi Admin', date_update='$date', provider_order_id='$poi' WHERE id='".$fetch_pesanan['id']."'");
                                    if($fetch_pesanan['username'] !== "" || $fetch_pesanan['username'] !== "none"){
                                        $db->query("UPDATE users SET saldo=saldo+{$fetch_pesanan['harga']} WHERE username='{$fetch_pesanan['username']}'");
                                        $db->query("INSERT INTO history_balance VALUES ('','{$fetch_pesanan['username']}','{$fetch_pesanan['harga']}','+','$date')");
                                    }
                                }else{
                                    $statuss = 'Waiting';
                                    $db->query("UPDATE pembelian_guest SET status='$statuss', sn='Pesanan Akan Di Proses Secepatnya', date_update='$date', provider_order_id='$poi' WHERE id='".$fetch_pesanan['id']."'");
                                }
                            }else{
                                $db->query("UPDATE pembelian_guest SET status='Canceled', sn='Tidak Terkoneksi Ke MP', date_update='$date', provider_order_id='$poi' WHERE id='".$fetch_pesanan['id']."'");
                                if($fetch_pesanan['username'] !== "" || $fetch_pesanan['username'] !== "none"){
                                        $db->query("UPDATE users SET saldo=saldo+{$fetch_pesanan['harga']} WHERE username='{$fetch_pesanan['username']}'");
                                        $db->query("INSERT INTO history_balance VALUES ('','{$fetch_pesanan['username']}','{$fetch_pesanan['harga']}','+','$date')");
                                    }
                                $_SESSION['alert'] = ['danger', 'Failed!', 'Pesanan Gagal di proses. Respon: '.$result['message']];
                                exit(header('location: /id/invoice?no='.$fetch_pesanan['order_id']));
                                
                            }
                        }else if($fetch_layanan['provider'] == 'AG'){
                            $check_data = $db->query("SELECT * FROM provider WHERE code = 'AG'");
                            $AG = $check_data->fetch_assoc();
                            $curl = curl_init();
                            $postt = json_encode([
                                "ref_id" => $fetch_pesanan['order_id'],
                                "merchant_id" => $AG['merchant_id'],
                                "produk" => $fetch_pesanan['sku'],
                                "tujuan" => $fetch_pesanan['target'].$fetch_pesanan['additional_target'],
                                "signature" => md5($AG['api_key'].$AG['merchant_id'].$fetch_pesanan['order_id'].$fetch_pesanan['sku'].$fetch_pesanan['target'].$fetch_pesanan['additional_target'])]);
                            curl_setopt_array($curl, array(
                                CURLOPT_URL => 'https://v1.apigames.id/transaksi',
                                CURLOPT_RETURNTRANSFER => true,
                                CURLOPT_ENCODING => '',
                                CURLOPT_MAXREDIRS => 10,
                                CURLOPT_TIMEOUT => 0,
                                CURLOPT_FOLLOWLOCATION => true,
                                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                                CURLOPT_CUSTOMREQUEST => 'POST',
                                CURLOPT_POSTFIELDS =>$postt,
                                CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
));
                            $resultS = curl_exec($curl);
                            $resultS = json_decode($resultS, true);
    
                            if (isset($resultS['data'])) {
                                
                                if ($resultS['data']['status'] === 'Gagal') {
                                    mysqli_query($db, "UPDATE pembelian_guest SET error_msg = 'Silahkan Hubungi Admin', status = 'Canceled' WHERE id = '".$fetch_pesanan['id']."'");
                                    if($fetch_pesanan['username'] !== "" || $fetch_pesanan['username'] !== "none"){
                                        $db->query("UPDATE users SET saldo=saldo+{$fetch_pesanan['harga']} WHERE username='{$fetch_pesanan['username']}'");
                                        $db->query("INSERT INTO history_balance VALUES ('','{$fetch_pesanan['username']}','{$fetch_pesanan['harga']}','+','$date')");
                                    }
                                    $_SESSION['alert'] = ['danger', 'Terjadi kesalahan!', 'Pesanan gagal direorder. Result ApiGames : ' . $resultS['data']['message']];
                                    exit(header('location: /id/invoice?no='.$fetch_pesanan['order_id']));
                                } else if ($resultS['data']['status'] === 'Sukses') {
                                    $sn = $resultS['data']['sn'] !== '' ? $resultS['data']['sn'] : $resultS['data']['message'];
                                    
                                    mysqli_query($db, "UPDATE pembelian_guest SET status = 'Success', sn='$sn' WHERE id = '".$fetch_pesanan['id']."'");
                                    $_SESSION['alert'] = ['success', 'Berhasil!', 'Pesanan berhasil di reorder.'];
                                    exit(header('location: /id/invoice?no='.$fetch_pesanan['order_id']));
                                }else{
                                    mysqli_query($db, "UPDATE pembelian_guest SET status = 'Processing', sn='Transaksi Pending' WHERE id = '".$fetch_pesanan['id']."'");
                                    $_SESSION['alert'] = ['success', 'Berhasil!', 'Pesanan berhasil di reorder.'];
                                    exit(header('location: /id/invoice?no='.$fetch_pesanan['order_id']));
                                }
                            }else{
                                mysqli_query($db, "UPDATE pembelian_guest SET error_msg = 'ApiGames tidak mereponse' WHERE id = '".$fetch_pesanan['id']."'");
                                if($fetch_pesanan['username'] !== "" || $fetch_pesanan['username'] !== "none"){
                                        $db->query("UPDATE users SET saldo=saldo+{$fetch_pesanan['harga']} WHERE username='{$fetch_pesanan['username']}'");
                                        $db->query("INSERT INTO history_balance VALUES ('','{$fetch_pesanan['username']}','{$fetch_pesanan['harga']}','+','$date')");
                                    }
                                $_SESSION['alert'] = ['danger', 'Terjadi kesalahan!', 'Pesanan gagal. Result ApiGames : ' .$resultS['data']['message']];
                                exit(header('location: /id/invoice?no='.$fetch_pesanan['order_id']));
                            }
                    }
                }
    }
    }