<?php
# Access
define('access', 'api');

# Load WebEngine
if(!@include_once(rtrim(str_replace('\\','/', dirname(__DIR__)), '/') . '/includes/webengine.php')) throw new Exception('Could not load WebEngine.');

# Load Config File
loadModuleConfigs('mercadopago');

# Load Class
$MercadoPago   =   new MercadoPago();

# Api MercadoPago
$raw_post_data = file_get_contents('php://input');
$json_string = json_decode($raw_post_data, true);

$myPost = array();
$id = $json_string['data']['id'];
$action = $json_string['action'];

if($action == "payment.created" || $action == "payment.updated"){
 
    $ACCESS_TOKEN = mconfig('access_token');;
    $url = 'https://api.mercadopago.com/v1/payments/'.$id.'?access_token='.$ACCESS_TOKEN;

    $response = file_get_contents($url);

    if($response){
        $json = json_decode($response, true);
        $IP_Payed = $json["additional_info"]["ip_address"];
        $ID_Bought = $json["id"];
        $Description = $json["description"];
        $Method = $json["payment_method_id"];
        $Method_Payed = $json["payment_type_id"];
        $Date_Create = $json["date_created"];
        $Total_Payed = $json["transaction_amount"];
        $Money = $json["currency_id"];
        $Status = $json["status"];
        $Detail_Status = $json["status_detail"];
        $Date_Approved = $json["date_approved"];
        
        $InfoBuy = explode ("|", $Description);
        $UserName = $InfoBuy[0];
        $Credits = $InfoBuy[1];
        $Descript = $InfoBuy[2];
        $Type_vipmoney = $InfoBuy[3];

        $GetUserID = $MercadoPago->GetUserID($UserName);
        foreach($GetUserID as $myid){
            $UserID = $myid['memb_guid'];
        }

        $Logs = array(
            'ip_payed' => $IP_Payed,
            'userID' => $UserID,
            'buy_id' => $ID_Bought,
            'username' => $UserName,
            'credits' => $Credits,
            'description' => $Descript,
            'method' => $Method,
            'method_payed' => $Method_Payed,
            'date_create' => $Date_Create,
            'amount' => $Total_Payed,
            'type_money' => $Money,
            'buy_status' => $Status,
            'buy_detail' => $Detail_Status,
            'approved_date' => $Date_Approved,
        );

        $GetPayID = $MercadoPago->GetPayID($id);
        $GetStatusBuy = $MercadoPago->GetStatusBuy($id);

        if($Status === "approved" && $Detail_Status === "accredited"){
            if(!$GetPayID){
                if($Descript == 'COINS') $MercadoPago->SetCoins($UserID, $Credits,$Type_vipmoney);
                else $MercadoPago->SetVIP($UserName, $Credits, $Type_vipmoney);
                $MercadoPago->InsertLOGS($Logs);

            }
        }else{
            if(!$GetPayID){
                $MercadoPago->InsertLOGS($Logs);
            }
        }
    }   
}
?>