<?php
    include_once("../../vendor/autoload.php");
    use Transbank\Webpay\WebpayPlus\MallTransaction;
    // SDK 2.x
    // Por defecto, la clase MallTransaction viene configurada para integración con un código Webpay Plus Mall Captura simultanea
    // También se puede configurar \Transbank\Webpay\WebpayPlus::configureForTestingMall() y  \Transbank\Webpay\WebpayPlus::configureForTestingMallDeferred()

	$mode="PRODUCCION";
	$commerceCode="597037376434";
	$apiKeySecret="af6c37f24926bb3f2c159e8029edfdec";

    $transaction_details = [];
    foreach($_POST["childs"] as $child){
        if($mode == "PRODUCCION" && $child["codigo_comercio"] == ""){
            header("HTTP/1.0 403 Forbidden");
            echo json_encode(array("message"=>"Codigos de Comercio de Tienda Invalidos","data"=>$_POST["childs"]));
            exit;
        }
        $transaction_details[] = [
            "amount" =>  $child["total_pagar"],
            "commerce_code" => isset($child["codigo_comercio"]) && $child["codigo_comercio"] != "" ? $child["codigo_comercio"] : 597055555536,
            "buy_order" => $child["child"]
        ];
    }

    $buy_order = $_POST["orden_compra"];
    $session_id = md5(uniqid(rand(), true));
    $return_url = url()."ejemplo_confirmar_pago.php";
    
    
    if($mode == "PRODUCCION"){
    	$response = (new MallTransaction)->configureForProduction($commerceCode, $apiKeySecret)->create($buy_order, $session_id, $return_url, $transaction_details);
    }
    else{
        $response = (new MallTransaction)->create($buy_order, $session_id, $return_url, $transaction_details);
    }
    
    
    $salida = array("data" => $response);
    echo json_encode($salida);

    function url(){
      return sprintf(
        "%s://%s%s",
        isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
        $_SERVER['SERVER_NAME'],
        substr($_SERVER['REQUEST_URI'], 0, strrpos($_SERVER['REQUEST_URI'], '/') + 1)
        //$_SERVER['REQUEST_URI']
      );
    }

?>