<?php
    require_once "/var/www/html/track/tools/FlowApi.class.php";
    require_once "/var/www/html/track/func/fn_st_flow_common.php";
    require_once "/var/www/html/track/func/fn_st_bsale_common.php";
    require_once "/var/www/html/track/config.custom.php";
    require_once "/var/www/html/track/func/fn_common.php";
    require_once "/var/www/html/track/tools/email.php";

    header("Content-Type: text/html;charset=utf-8");

    $ms = mysqli_connect($gsValues["DB_HOSTNAME"], $gsValues["DB_USERNAME"], $gsValues["DB_PASSWORD"], $gsValues["DB_NAME"], $gsValues["DB_PORT"]);
    mysqli_set_charset($ms, "UTF8");

    if (mysqli_connect_errno($ms)) {
        error(500, "Error de conexión: ".mysqli_connect_error($ms));
    }

    //Prepara el arreglo de datos
    $params = array(
        "token" => $_POST["token"]
    );
    //Define el metodo a usar
    $serviceName = "payment/getStatus";

    try {
        // Instancia la clase FlowApi
        $flowApi         = new FlowApi();
        // Ejecuta el servicio
        $response        = $flowApi->send($serviceName, $params, "GET");
        $optional        = shortDecode($response["optional"]["Firma"]);
        $optional        = setOptionalParamsKeys($optional);
        $paymentData     = $response["paymentData"];
    } catch (Exception $e) {
        echo $e->getCode() . " - " . $e->getMessage();
    }

    $paymentPayload = [
        "status"       => $response["status"],
        "flowOrder"    => $response["flowOrder"],
        "date"         => $paymentData["date"]
    ];

    $objectPayload = [
        "plate_number" => $optional["plate_number"],
        "period"       => $optional["period"],
        "period_type"  => $optional["period_type"],
        "flowOrder"    => $response["flowOrder"]
    ];

    updatePayment($ms, $paymentPayload);
    
    if ($response["status"] == 2) {
        
        updateObject($ms, $objectPayload);
        $bsaleDoc = createDocument($gsValues["BSALE_TOKEN"], +$response["amount"], $response["subject"]);
        $pdfURL = $bsaleDoc->urlPdf;
        $bsaleJson = json_encode($bsaleDoc);

        $template = getDefaultTemplate("payed_object", "spanish");
        $emailSubject = $template["subject"];
        $emailMessage = $template["message"];

        $emailMessage = str_replace("%PLATE_NUMBER%", $optional["plate_number"], $emailMessage);
        $emailMessage = str_replace("%PDF_URL%", $pdfURL, $emailMessage);

        sendEmail(
            $response["payer"],
            $emailSubject,
            $emailMessage,
            true
        );
    }
    
    mysqli_close($ms);
?>
