<?php
   
       /*$collection_id = $_GET['collection_id'];
       $collection_status = $_GET['collection_status'];
       $payment_id = $_GET['payment_id'];
       $external_reference = $_GET['external_reference'];
       $payment_type = $_GET['payment_type'];
       $merchand_order = $_GET['external_reference'];
       $preference_id = $_GET['preference_id'];
       $processing_mode =$_GET['processing_mode'];*/
       $error = $_GET['error'];
       
       $bd = $_GET['bd'];
       $id_cliente = $_GET['id_cliente'];
       $id_servicio;
       $costo;
       $plan;
       $tipo = $_GET['tipo'];
       $fecha_visita;
       $paquete_clase;
       $opcion;
       $url_redirect;
       $concepto;
       $idLocker;
       $lock_asig;
       $suc;
        
        $msgQuery;
        $conn = new mysqli("directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$bd);
       if($tipo == 'planes'){
            $id_servicio = $_GET['id_servicio'];
            $costo = $_GET['importe'];
            $plan = $_GET['plan'];
            $tipo = $_GET['tipo'];
            $fecha_visita = $_GET['fecha_visita'];
            $paquete_clase = $_GET['paquete_clase'];
            $opcion = $_GET['opcion'];
              
            
            $hoy = date('d/m/Y h:i:s A');
            $id_insert;
            $mes;
            $nombreGim;
            $desc_plan;
            $fechaI;
            $fechaA;
            $query = "INSERT INTO socio_servicio(idServicio,idSocio,idSocioTitular,FechaSolicitud,FechaInscripcion)
                VALUES('$id_servicio','$id_cliente','$id_cliente',CURDATE(),CURDATE())";
                //$resultado = $conn->query($query);
                //$resultado = $conn->insert_query($query,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$bd);
            
            if($conn->query($query) == TRUE){
                $id_insert = $conn->insert_id;
                $query_suc = "SELECT sucursal_idSucursal AS sucursal FROM socios WHERE idSocio = '$id_cliente'";
                $recult_suc = $conn->query($query_suc);
                $row_suc = $recult_suc->fetch_assoc();
                $id_sucursal = $row_suc['sucursal'];
                
                switch($plan){
                    case 1:
                        $desc_plan = 'VISITA';
                        $mes = 0;
                        break;
                    case 2:
                        $desc_plan = 'SEMANAL';
                        $mes = 7;
                        break;
                    case 3:
                        $desc_plan = 'QUINCENAL';
                        $mes = 15;
                        break;
                    case 4:
                        $desc_plan = 'MENSUAL';
                        $mes = 1;
                        break;
                    case 5:
                        $desc_plan = 'BIMESTRAL';
                        $mes = 2;
                        break;
                    case 6:
                        $desc_plan = 'TRIMESTRAL';
                        $mes = 3;
                        break;
                    case 7:
                        $desc_plan = 'CUATRIMESTRAL';
                        $mes = 4;
                        break;
                    case 8:
                        $desc_plan = 'SEMESTRAL';
                        $mes = 6;
                        break;
                    case 9:
                        $desc_plan = 'ANUAL';
                        $mes = 12;
                        break;
                        
                }
                    
                    //echo $mes;
                $query_fecha ="SELECT  * FROM(SELECT 
                    socio_servicio.idServicio as 'id',
                    pagos.FechaInicio,
                    servicios.NombreServicio,
                    socio_servicio.idSocio_Servicio AS 'idss',
                    socio_servicio.idSocioTitular as 'st',
                    pagos.FechaFin
                    FROM 
                    socio_servicio
                        INNER JOIN pagos
                    	    ON socio_servicio.idSocio_Servicio = pagos.idSocio_Servicio
                        INNER JOIN servicios
                    	    ON socio_servicio.idServicio = servicios.idServicio
                        INNER JOIN socios
                    	    ON socio_servicio.idSocio = socios.idSocio
                    WHERE
                        socio_servicio.idSocio = '$id_cliente'
                        AND pagos.Cancelado = 0  
                        AND pagos.Visible = 1
        			GROUP BY
        				socio_servicio.idSocio_Servicio DESC
                    ) AS tmp
                    GROUP BY
                    	tmp.id
                    ORDER BY
                        tmp.idss DESC";
                    
                $result_fecha = $conn->query($query_fecha);
                $row_fecha = $result_fecha->fetch_assoc();
                $fecha_hoy = date('Y-m-d');
                    
                    //$fechaI = $row_fecha['FechaFin'];
                $fecha_actual_hoy = date("d-m-Y", strtotime($fechaI));
                    
                $concepto;
                $visible;
                    //echo 'Op '.$obj->opcion."\n";
                if($obj->opcion != "00"){
                    $fechaI = $row_fecha['FechaFin'];
                    $concepto = "99";
                    $visible = '1';
                }else{
                    $fechaI = $obj->fecha_visita;
                    $concepto = "00";
                    $visible = '0';
                }
                $desc_plan = $desc_plan.' '.$row_fecha['NombreServicio'];
                if($mes == 0 || $mes == 7 || $mes == 15){
                    $fecha_vencimiento = "DATE_ADD( '$fechaI', INTERVAL ".$mes." DAY)";
                    $fechaA = date("d/m/Y",strtotime($fechaI."+ ".$mes." days"));
                }else{
                    $fecha_vencimiento = "DATE_ADD( '$fechaI', INTERVAL ".$mes." MONTH)";
                    $fechaA = date("d/m/Y",strtotime($fechaI."+ ".$mes." month"));
                }
                    
                $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,$concepto,NOW(),$costo,2,2,0.00,$costo,CURDATE(),'Paypal',0.00,'Stripe',0.00,$id_sucursal,$visible,$fecha_vencimiento,0)";
                    
        
                if ($conn->query($query_pagos) === TRUE) {
                    $msgQuery = "&iexcl;Transacci&oacute;n Exitosa!";
                      
                } else {
                    $msgQuery = "Error al registrar su pago, cheque en Administraci&oacute;n";
                } 
                    //$conn->close();
            }else{
                    //$conn->close();
                $msgQuery = 'Error al registrar su pago, cheque en Administraci&oacute;n';
            }
        
        
        }else{
            $costo = $_GET['costo'];
            $idLocker = $_GET['idLocker'];
            $lock_asig = $_GET['lock_asig'];
            $suc = $_GET['suc'];
            
            $bd = $_GET['bd'];
            //echo "<br>";
            $flag = $_GET['flag'];
            //echo "<br>";
            $id_cliente = $_GET['id_cliente'];
            //echo "<br>";
            $concepto = $_GET['concepto'];
            //echo "<br>";
            $costo = $_GET['costo'];
            //echo "<br>";
            $idLocker = $_GET['idLocker'];
            //echo "<br>";
            $lock_asig = $_GET['lock_asig']; 
            //echo "<br>";
            $suc = $_GET['suc'];
            $desc_plan;
            
            $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($costo);
            //$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) {
                echo "Error Executed Payment", "Payment", null, null, $ex;
                exit(1);
                
            }
            //codigo para insertar
                $fechaA;
                $addFecha;
                $queryLocker ="SELECT ls.*, l.*, locks.*
                FROM socios s JOIN lockers_socios ls ON s.idSocio = ls.Socios_idSocio JOIN locker l ON ls.id_lockers_socios = l.id_locker JOIN lockers locks ON locks.idLocker = l.Lockers_idLockers
                WHERE ls.id_lockers_socios = (SELECT MAX(id_lockers_socios) FROM lockers_socios WHERE Socios_idSocio = '$id_cliente')";
                
                //$resultadoL = $conn->insert_query($queryLocker,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
                //$row_fecha = mysqli_fetch_array($resultadoL);
                $resultadoL =$conn->query($queryLocker);
                $row_fecha = $resultadoL->fetch_assoc();
                $fechaVen = $row_fecha['FechaVencimiento'];
                $fecha_act = $row_fecha['FechaAsignacion'];
                switch($concepto){
                    case '1':
                        $desc_plan = 'Pago Locker 1 d&iacute;a';
                        $addFecha = "DATE_ADD( '$fechaVen', INTERVAL 1 DAY)";
                        $fechaA = date("d/m/Y",strtotime($fechaVen."+ 1 days"));
                        break;
                    case '2':
                        $desc_plan = 'Pago Locker semanal';
                        $addFecha = "DATE_ADD( '$fechaVen', INTERVAL 7 DAY)";
                        $fechaA = date("d/m/Y",strtotime($fechaVen."+ 7 days"));
                        break;
                    case '3':
                        $desc_plan = 'Pago Locker quincenal';
                        $addFecha = "DATE_ADD( '$fechaVen', INTERVAL 15 DAY)";
                        $fechaA = date("d/m/Y",strtotime($fechaVen."+ 15 days"));
                        break;
                    case '4':
                        $desc_plan = 'Pago Locker mensual';
                        $addFecha = "DATE_ADD( '$fechaVen', INTERVAL 1 MONTH)";
                        $fechaA = date("d/m/Y",strtotime($fechaVen."+ 1 month"));
                        break;
                    case '5':
                        $desc_plan = 'Pago Locker semestral';
                        $addFecha = "DATE_ADD( '$fechaVen', INTERVAL 6 MONTH)";
                        $fechaA = date("d/m/Y",strtotime($fechaVen."+ 6 month"));
                        break;
                    case '6':
                        $desc_plan = 'Pago Locker anual';
                        $addFecha = "DATE_ADD( '$fechaVen', INTERVAL 12 MONTH)";
                        $fechaA = date("d/m/Y",strtotime($fechaVen."+ 12 month"));
                        break;
                }
                
                $query = "INSERT lockers_socios(Lockers_idLocker,Socios_idSocio,locker_asignado,FechaAsignacion,FechaVencimiento,estado,concepto_pago,tipo_pago,
                cantidad_tarjeta,importe,user_idUsuario,sucursal_idSucursal,cancelado)
                VALUES('$idLocker','$id_cliente','$lock_asig','$fechaVen',$addFecha,1,'$concepto',2,'$costo','$costo',21,'$suc',0)";
                
                //$resultado = $conn->insert_query($query,"directoriofitness.com.mx","direct18","L4LL4v3M@3str@",$obj->bd);
                if($conn->query($query) == TRUE){
                    $msgQuery = '&iexcl;Transacci&oacute;n Exitosa!';
                }else{
                    $msgQuery = 'Error al registrar su pago, cheque en Administraci&oacute;n';
                }
        }
      
    $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.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>

  <title>Mercado Pago</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>
  <nav class="navbar navbar-dark bg-primary">
    <a class="navbar-brand" href="#" style="margin-left: 15px;">ProgymCloud</a>
  </nav>
  <div class="container">
    <div class="padre">
      <p class="hijo" style="text-align: center;">
        <img src="https://i.pinimg.com/originals/71/81/e8/7181e84d50cb87fa4ab9a5a8ab613dbe.jpg" alt="PayPal-Logo" width="130px">
      </p>
      <p class="hijo" style="text-align: center; color: #00E013; font-size: 70px;">
      <i class="fas fa-check-circle"></i>
      <h3 class="hijo" style="text-align: center;"><?= $msgQuery ?></h3>
      </p>
      
    </div>
  </div>

</body>
</html>
