<?php
    require $_SERVER['DOCUMENT_ROOT'].'/progymcloud_app/pagos/paypal/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;
    use PayPal\Api\PaymentExecution;
    
    $msg;
    
    
    if (isset($_GET['success']) && $_GET['success'] == 'true') {
    
   
        $bd = str_replace('_', ' ', $_GET['bd']);
        $id_cliente = str_replace('_', ' ', $_GET['id_cliente']);
        $id_servicio = str_replace('_', ' ', $_GET['plan']);
        $plan = str_replace('_', ' ', $_GET['pago']);
        $importe = str_replace('_', ' ', $_GET['importe']);
        $nombre = str_replace('_', ' ', $_GET['nombre']);
        $apellido = str_replace('_', ' ', $_GET['apellido']);
        $fechaN = str_replace('_', ' ', $_GET['fechaN']);
        $email = str_replace('_', ' ', $_GET['email']);
        $tel = str_replace('_', ' ', $_GET['telefono']);
        $domi = str_replace('_', ' ', $_GET['domi']);
        $col = str_replace('_', ' ', $_GET['colonia']);
        $cp = str_replace('_', ' ', $_GET['cp']);
        $genero = str_replace('_', ' ', $_GET['genero']);
        $fechaR = str_replace('_', ' ', $_GET['fechaR']);
        $sucursal = str_replace('_', ' ', $_GET['sucursal']);
        $qr = str_replace('_', ' ', $_GET['qr']);
        
        $apiContext = new \PayPal\Rest\ApiContext(
        new \PayPal\Auth\OAuthTokenCredential(
            'AZ2e7-OodO8jiPAhnHaWENlkzjfUDVPw20UA6BFS1bu__j95ztWXJ0dawDDle9-SAq2YRX2zTLOGIFvX',     // ClientID
            'EOK2gQSj6960G6Au6LYdCs2UpqVvzRHvwF8teBdbQRAqqrBCGU9HcXCGWNDIqjIoDPW9Ds6GDrvRiQ_V'      // ClientSecret
        )
        );
        $paymentId = $_GET['paymentId'];
        $payment = Payment::get($paymentId, $apiContext);
        $execution = new PaymentExecution();
        $execution->setPayerId($_GET['PayerID']);
        $transaction = new Transaction();
        $amount = new Amount();
        $details = new Details();
        /*$details->setShipping(2.2)
        ->setTax(1.3)
        ->setSubtotal(17.50);*/
    
        $amount->setCurrency('MXN');
        $amount->setTotal($importe);
        //$amount->setDetails($details);
        $transaction->setAmount($amount);
        $execution->addTransaction($transaction);
        try {
            $result = $payment->execute($execution, $apiContext);
            //echo "Executed Payment", "Payment", $payment->getId(), $execution, $result;
            try {
                $payment = Payment::get($paymentId, $apiContext);
                //echo 'Payment success';
            } catch (Exception $ex) {
                echo "Error Get Payment", "Payment", null, null, $ex;
                exit(1);
            }
        } catch (Exception $ex) {
            //$result = $payment->execute($execution, $apiContext);
            echo "Error Executed Payment", " Payment", null, null, $ex;
            echo "<br><br>";
            echo "paymente result ",Payment::get($paymentId, $apiContext);
            exit(1);
            
        }
        
        $conn = new mysqli("directoriofitness.com.mx","direct18","L4LL4v3M@3str@",'direct18_'.$bd);
        $conn -> set_charset("utf8");
        
        /*
                    telefono_prospecto
                */
                $id_insert;
                $query_socio = "INSERT INTO socio_servicio(idServicio,idSocio,idSocioTitular,FechaSolicitud,FechaInscripcion) 
                VALUES('$id_servicio','$id_cliente','$id_cliente',CURDATE(),CURDATE())";
                
                if($conn->query($query_socio) === TRUE){
                    $q_select = "SELECT MAX(idSocio_Servicio) AS idInsert FROM socio_servicio WHERE idSocioTitular = '$id_cliente'";
    
                    $result = $conn->query($q_select);
    
                    $row = $result->fetch_assoc();
    
                    $id_insert = $row['idInsert'];
                    
                    $fecha_vencimiento = "DATE_ADD( '$fechaR', INTERVAL 1 DAY)";
                    
                    $query_pagos ="INSERT INTO pagos (idSocio_Servicio,Concepto,FechaPago,Importe,idUsuario,Pago,Descuento,Subtotal,
                    FechaInicio,Forma1,Importe1,Forma2,Importe2,idSucursal,Visible,FechaFin,Cancelado) 
                    VALUES ($id_insert,'00',NOW(),$importe,2,2,0.00,$importe,CURDATE(),'Stripe',0.00,'Stripe',0.00,$sucursal,0,$fecha_vencimiento,0)";
                    
                    if($conn->query($query_pagos) === TRUE){
                        $query = "INSERT INTO prospectos (nombre_prospecto,apll_prospecto,fecha_nacimiento,genero,correo_prospecto,telefono_prospecto,
                        domicilio_prospecto,colonia_prospecto,cp_prospecto,notas_prospecto,fecha_registro,estatus_prospecto,qr) 
                        VALUES ('$nombre','$apellido','$fechaN',$genero,'$email','$tel',
                        '$domi','$col','$cp','visita',NOW(),6,'$qr')";
                        
                        $conn->query($query);
                        if($conn->query($query) === TRUE){
                            $msg = 'Pago Exitoso';
                        }else{
                            $msg ='error';
                        }
                    }else{
                        $msg = 'error';
                    }
                
                }else{
                    $msg = 'error';
                }
        
        
        $conn->close();
    }
?>

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" />
        <title>Paypal</title>
    </head>
    <style>
    .padre {

    padding: 0 1rem;
    margin: 1rem;
    }

    .hijo {
        /* IMPORTANTE */
        width: 200px;
        margin-left: auto;
        margin-right: auto;
    }
    .recibo{
        border-style: ridge;
    }

    </style>
    <body>
        <div class="padre">
            <p class="hijo" style="text-align: center;">
                <img src="https://logos-marcas.com/wp-content/uploads/2020/04/PayPal-Logo.png" alt="PayPal-Logo" width="180px">
            </p>
            
            <?php 
                if($msg == 'error'){ ?>
                
                    <p class="hijo" style="text-align: center; color: #d11515; font-size: 70px;">
                        <i class="fas fa-times-circle"></i>
                    </p>
                    <h3 class="hijo" style="text-align: center;">Error al realizar el pago</h3>
                
            <?php    
                    
                }else{
            ?>
            
                    <p class="hijo" style="text-align: center; color: #73E45E; font-size: 70px;">
                        <i class="fas fa-check-circle"></i>
                    </p>
                    <h3 class="hijo" style="text-align: center;">Pago Exitoso</h3>
            <?php } ?>
        </div> 
    </body>
    </html>