<?php
require '../../config.php';
    $CEK = $db->query("SELECT * FROM provider WHERE code='MP'");
    $MP = $CEK->fetch_assoc();
    $hmem = $db->query("SELECT * FROM options WHERE opt_name='df_harga_member'");
    $hmems = $hmem->fetch_assoc();
    $hres = $db->query("SELECT * FROM options WHERE opt_name='df_harga_reseller'");
    $hress = $hres->fetch_assoc();
    $hpre = $db->query("SELECT * FROM options WHERE opt_name='df_harga_premium'");
    $hprem = $hpre->fetch_assoc();
    $h2h = $db->query("SELECT * FROM options WHERE opt_name='df_harga_h2hspecial'");
    $h2hh = $h2h->fetch_assoc();
    $results = $curl->connectPost($MP['link'].'services',['api_id' => $MP['api_id'],'api_key' => $MP['api_key'],'service_fav' => true]);
    if(isset($results['data'])){
        foreach($results['data'] as $loop){
            $product = $loop['name'];
            $price = $loop['price'];
            $operator = $loop['category'];
            $sku = $loop['id'];
            $min = $loop['min'];
            $max = $loop['max'];
            $note = $loop['description'];
            $pmember = $price * $hmems['opt_value'] / 100;
            $preseller = $price * $hress['opt_value'] / 100;
            $ppremium = $price * $hprem['opt_value'] / 100;
            $ph2hspecial = $price * $h2hh['opt_value'] / 100;
            $price_member = $price + $pmember;
            $price_reseller = $price + $preseller;
            $price_premium = $price + $ppremium;
            $price_h2hspecial = $price + $ph2hspecial;
            $check_data = $db->query("SELECT * FROM layanan_pulsa WHERE operator='$operator' AND service_id='$sku' AND tipe='SOSMED' AND provider='MP'");
            if($check_data->num_rows == 0){
                $db->query("INSERT INTO `layanan_pulsa` VALUES ('', '$sku', '$sku', '$operator', '$product', 'null','$min','$max','$price_member', '$price_reseller', '$price_premium', '$price_h2hspecial', '0', 'Normal', 'MP', 'SOSMED', '$note')");
                $db->query("DELETE FROM layanan_pulsa WHERE status='Gangguan'");
            }else{
                $db->query("UPDATE layanan_pulsa SET note='$note', status='$statuss', min='$min',max='$max',harga='$price_member', harga_reseller='$price_reseller', harga_premium='$price_premium' WHERE operator='$operator' AND service_id ='$sku' AND tipe='SOSMED'");
                $db->query("DELETE FROM layanan_pulsa WHERE status='Gangguan'");
            }
        }
    }
if (isset($_GET['redirect'])) {
    header('location: /admin/setting/provider');
}