<?php
    require './vendor/autoload.php';
    
    use PayPal\Api\Amount;
    use PayPal\Api\Details;
    use PayPal\Api\Item;
    use PayPal\Api\ItemList;
    use PayPal\Api\Payer;
    use PayPal\Api\Payment;
    use PayPal\Api\RedirectUrls;
    use PayPal\Api\Transaction;
    
    $bd = $_GET['bd'];
    $flag = $_GET['flag'];
    $id_cliente = $_GET['id_cliente'];
    $id_servicio = $_GET['id_servicio'];
    $costo;
    $plan = $_GET['plan'];
    $concepto;
    $idLocker;
    $lock_asig;
    $sucursal = $_GET['suc'];
    $tipo = $_GET['tipo'];
    $paquete_clase;
    $fecha_visita;
    $opcion;
    $url_complete_success;
    $url_complete_cancel;
    $CLIENT_ID;
    $SECRET_ID;
    $prueba = 0; 
    
    $var_bd = explode("_",$bd);
    $bdC = $var_bd[1];
    $conn = new mysqli("directoriofitness.com.mx","direct18","L4LL4v3M@3str@",'direct18_ProGymCloud');
    $conn -> set_charset("utf8");
    $queryApi = "SELECT info_paypal.*, info_plataformaspago.activar_paypal 
                    FROM info_paypal
                INNER JOIN gimnasios ON info_paypal.gimnasio_idGimnasio = gimnasios.idGimnasio 
                INNER JOIN info_plataformaspago ON info_plataformaspago.gimnasio_idGimnasio = gimnasios.idGimnasio 
                WHERE gimnasios.BaseDatos = '$bdC' AND info_paypal.sucursal_idSucursal = '$sucursal'";
    $resultApi = $conn->query($queryApi);
    
    
    if ($resultApi->num_rows > 0){
        
        $row = $resultApi->fetch_assoc();
    
        $CLIENT_ID = $row['client_id'];
        $SECRET_ID = $row['secret_id'];
        $prueba = $row['prueba'];
    }else{
        $bandApi = FALSE;
    }
    
    
    $conn->close();
    //$url = '&bd='.$bd.'&flag='.$flag.'&id_cliente='.$id_cliente.'&id_servicio='.$id_servicio.'&costo='.$costo.'&plan='.$plan;
     /*$apiContext = new \PayPal\Rest\ApiContext(
        new \PayPal\Auth\OAuthTokenCredential(
            'AbMNQuC6FuWRkohnxxl4AhiZetgL8_99SDtSz_4fVDkKHZD_hEHmY71Sx-2j9UOycGTni5swWzyAD_7l',     // ClientID
            'EFViUhNVgqghUeIZFy0R8sdIdP2XSeheTGQVnyY1VIKs3ioeG0lwz4n96t42hohh_5fs3K2AYVn5JCb6'      // ClientSecret
        )
    );
    
    $apiContext->setConfig(
      array(
        'mode' => 'live',
      )
    );*/
    
    $apiContext = new \PayPal\Rest\ApiContext(
        new \PayPal\Auth\OAuthTokenCredential(
            $CLIENT_ID,
            $SECRET_ID
                /*'ATcJBoIQOQWb8I9YgNFXTfBI1Vx_FhSuuHGuFmjR7f5MLl1MosLu2zM_jrfOTJu-AD3O5DnT1UqDNIKx',     // ClientID
                'EGLWdM-RaUxmWRFTuxNotLqhMGWbFGAILTLhqypO1X6ZUYtUIADmTsCHGIJ9dUXlp53D1uawQ6DcM9Zl' */      // ClientSecret
        )
    );
    
    if($prueba == 1){
        $apiContext->setConfig(
            array(
                'mode' => 'live',
            )
        );
    }
    
    
    if($tipo == 'planes'){
        
        $paquete_clase = $_GET['paquete_clase'];
        $fecha_visita = $_GET['fecha_visita'];
        $id_servicio = $_GET['id_servicio'];
        //$costo = $_GET['importe'];
        $plan = $_GET['plan'];
        $costo = (float)$_GET['importe'];
        $opcion =$_GET['opcion'];
        $url_complete_success = 'excecutePayment.php?success=true&bd='.$bd.'&flag='.$flag.'&id_cliente='.$id_cliente.'&id_servicio='.$id_servicio.'&costo='.$costo.'&plan='.$plan.'&paquete_clase='.$paquete_clase.'&fecha_visita='.$fecha_visita.'&suc='.$sucursal.'&opcion='.$opcion;
        $url_complete_cancel = 'excecutePayment.php?success=false';
    }
    if($tipo == 'locker'){
        $concepto = $_GET['concepto'];
        $idLocker = $_GET['idLocker'];
        $lock_asig = $_GET['lock_asig'];
        
        $costo = (float)$_GET['costo'];
        $opcion = $_GET['opcion'];
        $url_complete_success = 'excecutePaymentLockers.php?success=true&bd='.$bd.'&flag='.$flag.'&id_cliente='.$id_cliente.'&concepto='.$concepto.'&costo='.$costo.'&idLocker='.$idLocker.'&lock_asig='.$lock_asig.'&suc='.$sucursal.'&opcion='.$opcion;
        $url_complete_cancel = 'excecutePaymentLockers.php?success=false';

    }
    
    //echo 'bd: '.$bd.' flag: '.$flag.' id_servicio: '.$id_servicio.' plan: '.$plan.' tipo: '.$tipo.' paquete_clase: '.$paquete_clase.' fecha_visita: '.$fecha_visita.' plan: '.$plan.' costo: '.$costo.' opcion: '.$opcion;

   
    
    $payer = new Payer();
    $payer->setPaymentMethod("paypal");
    

    $amount = new Amount();
    $amount->setCurrency("MXN")
            ->setTotal($costo);
    

    $transaction = new Transaction();
    $transaction->setAmount($amount)
    ->setDescription("Payment description")
    ->setInvoiceNumber(uniqid());
    
    $redirectUrls = new RedirectUrls();
    $redirectUrls->setReturnUrl("https://api.progymcloud.com/progymcloud_app/pagos/paypal/".$url_complete_success)
    ->setCancelUrl("https://api.progymcloud.com/progymcloud_app/pagos/paypal/".$url_complete_cancel);
    $payment = new Payment();
    $payment->setIntent("sale")
    ->setPayer($payer)
    ->setRedirectUrls($redirectUrls)
    ->setTransactions(array($transaction));

    $request = clone $payment;
    try {
        $payment->create($apiContext);
        header("Location: ".$payment->getApprovalLink());
        
    } catch (Exception $ex) {
        echo "Error Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", null, $request, $ex;
        //echo 'bd: '.$bd.' flag: '.$flag.' id_servicio: '.$id_servicio.' plan: '.$plan.' tipo: '.$tipo.' paquete_clase: '.$paquete_clase.' fecha_visita: '.$fecha_visita.' plan: '.$plan.' costo: '.$costo.' opcion: '.$opcion."\n";

        //echo $payment->getApprovalLink();
        //header("Location: http://localhost/paypal_new/excecutePayment.php?success=true");
        exit(1);
    }

    //echo $approvalUrl = $payment->getApprovalLink();
    //header("Location: ".$approvalUrl);
    //echo "Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", "<a href='$approvalUrl' >$approvalUrl</a>", $request, $payment;

return $payment;
?>