<?php
    require_once 'secrets.php';
    require_once 'tools.php';
    require_once 'vendor/autoload.php';
    require_once 'models/InvoiceHelper.php';
    require_once 'models/VendorBillHelper.php';
    require_once 'models/VendorPaymentHelper.php';
    require_once 'netsuite/seach.php';
    require_once 'netsuite/crud.php';
    require 'Mailer.php';
    \Stripe\Stripe::setApiKey($stripeSecretKey);
    $stripe = new \Stripe\StripeClient($stripeSecretKey);


    $date = date('Y/m/d H:i:s');

    error_log("Entra a archivo");

    $mailer = new Mailer();

$usoCfdiList = array(
    -1 => "- Nuevo -",
    25 => "CN01 - Nómina",
    24 => "CP01 - Pagos",
    12 => "D01 - Honorarios Médicos, Dentales y Gastos Hospitalarios",
    13 => "D02 - Gastos Médicos por Incapacidad o Discapacidad",
    14 => "D03 - Gastos Funerales",
    15 => "D04 - Donativos (no aplica para membresía)",
    16 => "D05 - Intereses Reales Efectivamente Pagados por Créditos Hipotecarios (Casa Habitación)",
    17 => "D06 - Aportaciones Voluntarias al SAR",
    18 => "D07 - Primas por Seguros de Gastos Médicos",
    19 => "D08 - Gastos de Transportación Escolar Obligatoria",
    20 => "D09 - Depósitos en Cuentas para el Ahorro, Primas que Tengan como Base Planes de Pensiones",
    21 => "D10 - Pagos por Servicios Educativos (Colegiaturas)",
    1 => "G01 - Adquisición de Mercancías",
    2 => "G02 - Devoluciones, Descuentos o Bonificaciones",
    3 => "G03 - Gastos en General",
    4 => "I01 - Construcciones",
    5 => "I02 - Mobiliario y Equipo de Oficina por Inversiones",
    6 => "I03 - Equipo de Transporte",
    7 => "I04 - Equipo de Cómputo y Accesorios",
    8 => "I05 - Dados, Troqueles, Moldes, Matrices y Herramental",
    9 => "I06 - Comunicaciones Telefónicas",
    10 => "I07 - Comunicaciones Satelitales",
    11 => "I08 - Otra Maquinaria y Equipo",
    22 => "P01 - Por Definir",
    23 => "S01 - Sin efectos fiscales"
);

$regimenList = array(
    1 => "601 - General de Ley Personas Morales",
    2 => "603 - Personas Morales con Fines no Lucrativos",
    11 => "605 - Sueldos y Salarios e Ingresos Asimilados a Salarios",
    12 => "606 - Arrendamiento",
    10 => "607 - Régimen de Enajenación o Adquisición de Bienes",
    13 => "608 - Demás ingresos",
    4 => "610 - Residentes en el Extranjero sin Establecimiento Permanente en México",
    14 => "611 - Ingresos por Dividendos (socios y accionistas)",
    15 => "612 - Personas Físicas con Actividades Empresariales y Profesionales",
    16 => "614 - Ingresos por intereses",
    19 => "615 - Régimen de los ingresos por obtención de premios",
    17 => "616 - Sin obligaciones fiscales",
    5 => "620 - Sociedades Cooperativas de Producción que Optan por Diferir sus Ingresos",
    18 => "621 - Incorporación Fiscal",
    6 => "622 - Actividades Agrícolas, Ganaderas, Silvícolas Y Pesqueras",
    7 => "623 - Opcional para Grupos de Sociedades",
    8 => "624 - Coordinados",
    22 => "625 - Régimen de las Actividades Empresariales con ingresos a través de Plataformas Tecnológicas",
    23 => "626 - Régimen Simplificado de Confianza"
);
$url_base = "https://auna.nationbuilder.com";
    try{
        $argumentos = $argv[1];

    $session = json_decode($argumentos);

    
    /*$jsonData = $session->metadata;

        $firstName = $jsonData["firstName"];
        $lastName = $jsonData["lastName"];
        $amount = $jsonData["amount"];
        $email = $jsonData["email"];
        $phone = $jsonData["phone"];
        $country = $jsonData["country"];
        $address = $jsonData["address"];
        $address2 = $jsonData["address2"];
        $zip = $jsonData["zip"];
        $rfc = $jsonData["rfc"];
        $city = $jsonData["city"];
        $state = $jsonData["state"];

        $taxAddress = $jsonData["taxAddress"];
        $taxRegime = $jsonData["taxRegime"];
        $cfdiUse = $jsonData["cfdiUse"];
        $currentDate = date("Y-m-d H:i:s");
        $isTest = $jsonData["isTest"];
        */

        $metadata = $session->metadata;

        $firstName = $metadata->firstName;
        $lastName = $metadata->lastName;
        $amount = $metadata->amount;
        $email = $metadata->email;
        $phone = $metadata->phone;
        $country = $metadata->country;
        $address = $metadata->address;
        $address2 = $metadata->address2;
        $zip = $metadata->zip;
        $rfc = $metadata->rfc;
        $city = $metadata->city;
        $state = $metadata->state;
        $satName = $metadata->satName;
        $pageSlug = $metadata->pageSlug;
        $capitulo = null;

        //$taxAddress = $metadata->taxAddress;
        $taxAddress = "";
        $taxRegime = $metadata->taxRegime;
        $cfdiUse = $metadata->cfdiUse;
        $currentDate = date("Y-m-d H:i:s");
        $isTest = $metadata->isTest;

        $itemInvoice = $item;
        $classInvoice = $class;
        $departmentInvoice = $department;

        $template = $custbody_psg_ei_template;
        if(isset($metadata->itemMembresia)){
            $itemInvoice = $metadata->itemMembresia;
        }
        if(isset($metadata->classMembresia)){
            $classInvoice = $metadata->classMembresia;
        }
        if(isset($metadata->departmentMembresia)){
            $departmentInvoice = $metadata->departmentMembresia;
        }
        if(isset($metadata->templateCFDI)){
            $template = $metadata->templateCFDI;
        }
        if(isset($metadata->capitulo)){
            $capitulo = $metadata->capitulo;
        }

        $isMembership = 0;
        if(isset($metadata->isMembership)){
            if($metadata->isMembership){
                $isMembership = 1;
            }
            
        }

        error_log("Es test?: " . $isTest);

        $conn = new mysqli($servername, $username, $password, $dbname,  $port);

        if ($conn->connect_error) {
            die("La conexión a la base de datos ha fallado: " . $conn->connect_error);
            
        }


        
        

        $statusDonation = 1;
        
        // Prepara la consulta SQL para insertar los datos en la tabla
        $sql = "INSERT INTO donation (firstName, lastName, statusDonation, amount, email, phone, country, address, address2, zip, rfc, city, state,taxAddress, taxRegime, cfdiUsage, createdAt,satName) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?,?,?)";
        
        // Prepara la sentencia
        $stmt = $conn->prepare($sql);
        
        // Vincula los parámetros
        $stmt->bind_param("ssidssssssssssssss", $firstName, $lastName, $statusDonation, $amount, $email, $phone, $country, $address, $address2, $zip, $rfc, $city, $state, $satName, $taxRegime, $cfdiUse, $currentDate, $satName);
        
        // Ejecuta la consulta
        if ($stmt->execute()) {
            error_log("Los datos se han guardado correctamente en la base de datos.");
        } else {
            error_log("Error al guardar los datos: " . $stmt->error);
        }
        

        $sql = "SELECT * FROM donation WHERE statusDonation = 1 ORDER BY id DESC LIMIT 1";
            $result = $conn->query($sql);

            error_log("Entra a búsqueda");

            if ($result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {

                    $customerInfo["email"] = $row["email"];
                    $customerInfo["rfc"] = $row["rfc"];
                    $customerInfo["amount"] = $row["amount"];
                    $customerInfo["cfdiUsage"] = $row["cfdiUsage"];
                    $customerInfo["taxRegime"] = $row["taxRegime"];
                    $customerInfo["address"] = $row["address"];
                    $customerInfo["address2"] = $row["address2"];
                    $customerInfo["zip"] = $row["zip"];
                    $customerInfo["city"] = $row["city"];
                    $customerInfo["state"] = $row["state"];
                    $customerInfo["satName"] = $row["satName"];


                    if (isset($customerInfo["cfdiUsage"]) && !empty($customerInfo["cfdiUsage"])) {
                        if($customerInfo["cfdiUsage"] === "G01 Gastos en general"){
                            $customerInfo["cfdiUsage"] = "G03 Gastos en General";
                        }
                    }else{
                        $customerInfo["cfdiUsage"] = "G03 Gastos en General";
                    }
                    error_log(print_r('data: '.json_encode($row), TRUE));

                    $customer = null;
                    $customerId = 0;

                    if (isset($customerInfo["rfc"]) && !empty($customerInfo["rfc"]) && $isTest == "false" && $customerInfo["rfc"] != $genericRFC) {
                        $foundCustomer = searchByRFC($customerInfo["rfc"]);

                        if(isset($foundCustomer)){
                            error_log("Found by RFC");
                            $customer = $foundCustomer[0];
                            $customerId = $customer->internalId;
                        }
                    }else{
                        if (isset($customerInfo["email"]) && !empty($customerInfo["email"])) {
                            $foundCustomer = searchByEmail($customerInfo["email"]);
                            if(isset($foundCustomer)){
                                error_log("Found by email");
                                $customer = $foundCustomer[0];
                                $customerId = $customer->internalId;
                            }
                        }
                    }

                    if (isset($customerInfo["cfdiUsage"]) && !empty($customerInfo["cfdiUsage"])) {
                        if($customerInfo["cfdiUsage"] === "G01 Gastos en general"){
                            $customerInfo["cfdiUsage"] = "G03 Gastos en General";
                        }
                        
                    }else{
                        $customerInfo["cfdiUsage"] = "G03 Gastos en General";
                    }



                    if($isTest == true){
                        $customerInfo["rfc"] = $testRFC;
                        $customerInfo["cfdiUsageId"] = $testUsoCFDI;
                    }

                    $valor = array_search($customerInfo["cfdiUsage"], $usoCfdiList);

                    if ($valor !== false) {
                        
                        $customerInfo["cfdiUsageId"] = $valor;
                    } else {
                        $customerInfo["cfdiUsageId"] = 3;
                    }

                    error_log("Uso: ".$customerInfo["cfdiUsage"]." - ".$customerInfo["cfdiUsageId"]);


                    $row["subsidiary"] = $subsidiary;
                    $row["customFormCustomer"]= $customFormCustomer;
                    $row["customerEntityStatus"]= $customerEntityStatus;
                    $row["customerEntityDoc"] = $customerEntityDoc;

                    $idRegimen = null; // Variable para almacenar el ID una vez encontrado

                    foreach ($regimenList as $id => $valor) {
                        if ($valor == $row["taxRegime"]) {
                            $idRegimen = $id;
                            break; // Detiene el bucle una vez que se encuentra la coincidencia
                        }
                    }

                    if ($idRegimen !== null) {
                        error_log("El ID Regimen encontrado es: " . $idRegimen);
                    } else {
                        $idRegimen = "15";
                        error_log("No se encontró la cadena buscada.".$row["taxRegime"]);
                    }
                    

                    if(!isset($customer)){
                        if($isTest == "true"){
                            //DESARROLLO
                            
                            $row["satName"] = "JIMENEZ ESTRADA SALAS A A";
                            $row["rfc"] = "JES900109Q90";
                            $row["satIndustry"] = "15";
                            $row["zip"] = "01030";
                            
                            
                        }/*else{
                            $row["satName"] = $row["firstName"]." ".$row["lastName"];
                            $row["satIndustry"] = "15";
                            
                        }*/
                        else{
                            $row["satIndustry"] = $idRegimen;
                            
                        }
                        $foundCustomerId = createCustomer($row);

                        $customerId = $foundCustomerId;

                        $customerInfo["email"] = $row["email"];
                        $customerInfo["rfc"] = $row["rfc"];
                        $customerInfo["amount"] = $row["amount"];
                        $customerInfo["cfdiUsage"] = $row["cfdiUsage"];

                        
                    }else{
                        if($isTest == "true"){

                            $row["satName"] = "JIMENEZ ESTRADA SALAS A A";
                            $row["rfc"] = "JES900109Q90";
                            $row["satIndustry"] = "15";
                            $row["zip"] = "01030";
                        }else{
                            //$row["satName"] = $row["firstName"]." ".$row["lastName"];
                            //$row["satIndustry"] = "01030";
                            $row["satIndustry"] = $idRegimen;
                        }
                        updateCustomer($row, $customerId);
                        
                    }
                                    
                    //$json = json_encode($customer);

                    //$newJson = json_decode($json, true, 512, JSON_UNESCAPED_UNICODE);
                    //echo json_encode($newJson);

                    $partes = explode(' ', $customerInfo["cfdiUsage"]);
                    $valor = "";

                    if (count($partes) > 0) {
                        $valor = $partes[0];
                        
                    } else {
                        $valor = 3;
                    }


                    $idUsoCfdi = null; // Variable para almacenar el ID una vez encontrado

                    foreach ($usoCfdiList as $id => $valor) {
                        if ($valor === $row["cfdiUsage"]) {
                            $idUsoCfdi = $id;
                            break; // Detiene el bucle una vez que se encuentra la coincidencia
                        }
                    }

                    if ($idUsoCfdi !== null) {
                        echo "El usoCfdi encontrado es: " . $idUsoCfdi;
                    } else {
                        $idUsoCfdi = "15";
                        echo "No se encontró la cadena buscada.";
                    }
                    
                    

                    error_log("Item Selected: ".$itemInvoice);
                    $invoiceData = new InvoiceHelper();
                    //$cfdiUsage = isset($categories[$customerInfo["cfdiUsage"]]) ? $categories[$customerInfo["cfdiUsage"]] : 3;
                    $cfdiUsage = $idUsoCfdi;
                    $invoiceData->customerId = $customerId;
                    //$invoiceData->locationId = $location;
                    //$invoiceData->departmentId = $department;
                    $invoiceData->departmentId = $departmentInvoice;
                    $invoiceData->accountId = $accountId;
                    //$invoiceData->classId = $class;
                    $invoiceData->classId = $classInvoice;
                    $invoiceData->termsId = 1;
                    //$invoiceData->itemId = $item;
                    $invoiceData->itemId = $itemInvoice;
                    $invoiceData->amount = $customerInfo["amount"];
                    //$invoiceData->cfdiUsageId = $customerInfo["cfdiUsageId"];
                    $invoiceData->cfdiUsageId = $cfdiUsage;
                    $invoiceData->subsidiary = $subsidiary;
                    //$invoiceData->custbody_psg_ei_template = $custbody_psg_ei_template;
                    $invoiceData->custbody_psg_ei_template = $template;

                    error_log("Location: ".strtoupper($customerInfo["state"]));

                    $customerState = json_decode('"' . $customerInfo["state"] . '"');
                    $customerState = mb_strtoupper($customerState, 'UTF-8');
                    error_log("Location: ".$customerState);

                    if(isset($capitulo)){
                        error_log("Entra capítulo: ".$capitulo);
                        $customerState = $capitulo;
                    }
                    $tagMembresia = "Capítulo_CDMX";

                    switch($customerState){
                        case "CDMX":
                        case "CIUDAD DE MÉXICO":
                        case "CIUDAD DE MEXICO":
                            $invoiceData->locationId = $LocationCDMX;
                            $tagMembresia = "Capítulo_CDMX";
                            break;
                        case "OAXACA":
                            $invoiceData->locationId = $LocationOax;
                            $tagMembresia = "Capítulo_Oaxaca";
                            break;
                        case "JALISCO":
                            $invoiceData->locationId = $LocationJal;
                            $tagMembresia = "Capítulo_Jalisco";
                            break;
                        case "GUERRERO":
                        case "GRO":
                            $invoiceData->locationId = $LocationGro;
                            $tagMembresia = "Capítulo_Guerrero";
                            break;
                        case "NUEVO LEÓN":
                        case "NUEVO LEON":
                            $invoiceData->locationId = $LocationNvoL;
                            $tagMembresia = "Capítulo_NL";
                            break;
                        default:
                            $invoiceData->locationId = $LocationNacional;
                            break;
                    }

                    error_log("ID capítulo: ".$invoiceData->locationId);


                    if($pageSlug == 'atria_2024_prueba' || $pageSlug == 'atria_2024' || $pageSlug == 'cobro_integrado'
                    || $pageSlug == 'cobro_integrado_test')
                    {
                        $invoiceData->classId = $classAtria;
                        $invoiceData->departmentId = $deptoAtria;
                        $invoiceData->itemId = $itemAtria;
                        
                    }else if($pageSlug == 'donativos_2024'){
                        $invoiceData->classId = $classAtria;
                        $invoiceData->departmentId = $deptoAtria;
                        $invoiceData->itemId = $itemAtriaParticipante;
                    }else if($pageSlug == 'ventaservicios'){
                        $invoiceData->classId = $classFormacion;
                        $invoiceData->departmentId = $deptoFormacion;
                        $invoiceData->itemId = $itemFormacion;
                    }
                    
                    
                    $invoiceId = generateInvoice($invoiceData);


                    $sql = "UPDATE donation SET statusDonation = 2, invoiceId = ? WHERE id = ?";
            
                    // Prepara la sentencia
                    $stmt = $conn->prepare($sql);
                    
                    // Vincula los parámetros
                    $stmt->bind_param("ii", $invoiceId, $row["id"]);

                    $facturaGenerada = false;

                    if(isset($invoiceId)){
                        $facturaGenerada = true;
                    }else{
                        $facturaGenerada = false;
                    }
                    
                    // Ejecuta la consulta
                    if ($stmt->execute()) {
                        error_log( "Se ha generado la factura ".$invoiceId." en netsuite");
                        error_log("factur: ".$invoiceId);
                        
                    } else {
                        error_log("Error al guardar los datos: " . $stmt->error);
                    }

                    
                    //$to = 'administracion@auna.org.mx';
                    $to = $correoNotificacion;
                    $subject = 'Factura generada';
                    $body = 'Se ha generado la factura  <b>'.$invoiceId.'</b> y se encuentra disponible para facturar. Puedes entrar desde esta url: https://8551419-sb1.app.netsuite.com/app/accounting/transactions/custinvc.nl?id='.$invoiceId.'&whence=';
                    $altBody = 'Se ha generado la factura'.$invoiceId.' y se encuentra disponible para facturar. Puedes entrar desde esta url: https://8551419-sb1.app.netsuite.com/app/accounting/transactions/custinvc.nl?id='.$invoiceId.'&whence=';
                    //$attachments = ['/var/tmp/file.tar.gz', '/tmp/image.jpg'];

                    //if ($mailer->sendEmail($to, $subject, $body, $altBody, $attachments)) {

                        try{
                            $urlBuscar = $url_base.'/api/v1/people/push'.'?access_token='.$tokenNB;
    
                            $dataPerson = array(
                                'person' => array(
                                    'email' => $email,
                                    'first_name' => $firstName,
                                    'last_name' => $lastName,
                                    'phone' => $phone,
                                    'billing_address' => array(
                                        'address1' => $address,
                                        'address2' => $address2,
                                        'city' => $city,
                                        'state' => $state,
                                        'country_code' => $country,
                                        'zip' => $zip
                                    )
                                    
                                )
                            );
                    
                            $personJson = json_encode($dataPerson);
                            
                            $ch = curl_init($urlBuscar);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $personJson);
                            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                'Content-Type: application/json'
                            ));
                    
                            $resultado = curl_exec($ch);
                    
                            if ($resultado === false) {
                                error_log("[".$date."] Error al ejecutar la solicitud: " . curl_error($ch));
                            } else {
                                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                            
                                if ($httpCode == 200 || $httpCode == 201) {
                                    $respuesta = json_decode($resultado, true);

                                    $arrayTags = array();
                                    $arrayTags[] = "MembresiaNueva24";
                                    $arrayTags[] = $tagMembresia;
                    
                                    if(isset($respuesta["person"]["id"])){
                                        $idPerson = $respuesta["person"]["id"];
                                        error_log("id person encontrado: ".$idPerson );

                                        $hasTag = false;
                                        $tags = $respuesta["person"]["tags"];

                                                
                                        foreach ($tags as $elemento) {
                                            if ($tags == "MembresiaNueva24") {
                                                $hasTag = true;
                                                error_log("Tag encontrado MembresiaNueva24");

                                                $indice = array_search("MembresiaNueva24", $arrayTags);

                                                if ($indice !== false) {
                                                    unset($arrayTags[$indice]);
                                                }
                                                //break;
                                            }
                                            if($tags == $tagMembresia){
                                                $hasTag = true;
                                                error_log("Tag encontrado ".$tagMembresia);
                                                $indice = array_search($tagMembresia, $arrayTags);

                                                if ($indice !== false) {
                                                    unset($arrayTags[$indice]);
                                                }
                                            }
                                        }

                                        

                                        if($isMembership == 1){
                                            //if($hasTag == false){
                                            if(count($arrayTags)>0){
                                                try{
                                                    foreach($arrayTags as $tagNB){
                                                        $urlTags = $url_base.'/api/v1/people/'.$idPerson.'/taggings'.'?access_token='.$tokenNB;
                                                                        
                                                        $tagData = array(
                                                            'tagging' => array(
                                                                'tag' => $tagNB
                                                            )
                                                        );
        
                                                        
                                    
                                                        
                                                        $tagJson = json_encode($tagData);
                                                        error_log("tag agregado: ".$tagNB);
                                    
                                                        $ch = curl_init($urlTags);
                                                        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                                                        curl_setopt($ch, CURLOPT_POSTFIELDS, $tagJson);
                                                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                                                        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                                            'Content-Type: application/json'
                                                        ));
                                    
                                                        $resultado = curl_exec($ch);
                                    
                                                        if ($resultado === false) {
                                                            error_log("[".$date."] Error al ejecutar la solicitud: " . curl_error($ch));
                                                        } else {
                                                            $codigoRespuesta = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                                                            error_log("Código de Respuesta: ".$codigoRespuesta);
                                                            error_log("Cuerpo de la Respuesta: ".$resultado);
        
                                                            
        
        
                                                        }
                                                    }
                                                }catch(Exception $errTags){

                                                }
                                            }

                                            try{
                                                date_default_timezone_set('America/Mexico_City');
                                                $date = new DateTime();
                                                $formatter = new IntlDateFormatter(
                                                    'es_MX',
                                                    IntlDateFormatter::FULL,
                                                    IntlDateFormatter::NONE,
                                                    'America/Mexico_City',
                                                    IntlDateFormatter::GREGORIAN,
                                                    "d 'de' MMMM 'del' y"
                                                );
    
                                                $formattedDate = $formatter->format($date);
    
                                                $mailer = new Mailer();
    
                                                $templateDonation = 'templates/donation_membresia.html';
    
                                                $htmlContent = file_get_contents($templateDonation);
    
                                                $fullAddress = $customerInfo["address"]." ".$customerInfo["address2"]." "
                                                    .$customerInfo["city"]." ".$customerInfo["state"]." ".$customerInfo["zip"];
    
                                                $datos = array(
                                                    '{{first_name}}' => $firstName,
                                                    '{{long_name}}' => $firstName." ".$lastName,
                                                    '{{donationId}}' => '',
                                                    '{{donation.succeeded_at}}' => $formattedDate,
                                                    '{{billing_address}}' => $fullAddress,
                                                    '{{name}}' => $firstName,
                                                    '{{phone}}' => $phone,
                                                    '{{email}}' => $email,
                                                    '{{amount}}' => "$".$amount,
                                                    '{{nex_billing_date}}' =>  '',
                                                    '{{paymentType}}' => 'Card'
    
                                                );
                                                
                                                // Reemplazar los marcadores de posición con los valores reales
                                                foreach ($datos as $clave => $valor) {
                                                    $htmlContent = str_replace($clave, $valor, $htmlContent);
                                                }
    
                                                $to = $email;
                                                $subject = '¡Bienvenida a Aúna!';
                                                $body = $htmlContent;
                                                $altBody = '';
                                                $attachments = [];
    
                                                if ($mailer->sendEmail($to, $subject, $body, $altBody, $attachments)) {
                                                    error_log("Correo enviado a : ".$email);
                                                }else{
                                                    error_log("No se pudo enviar el correo a : ".$email);
                                                }
                                            }catch(Exception $errorMail){
                                                error_log(print_r('error: '.json_encode($errorMail), TRUE));
    
                                            }

                                            try{
                                                date_default_timezone_set('America/Mexico_City');
                                                $date = new DateTime();
                                                $formatter = new IntlDateFormatter(
                                                    'es_MX',
                                                    IntlDateFormatter::FULL,
                                                    IntlDateFormatter::NONE,
                                                    'America/Mexico_City',
                                                    IntlDateFormatter::GREGORIAN,
                                                    "d 'de' MMMM 'del' y"
                                                );

                                                $formattedDate = $formatter->format($date);

                                                $mailer = new Mailer();

                                                $templateMembresia = 'templates/membresia.html';

                                                $htmlContent = file_get_contents($templateMembresia);

                                                $datos = array(
                                                    '{{recipient.first_name}}' => $firstName." ".$lastName

                                                );
                                                
                                                // Reemplazar los marcadores de posición con los valores reales
                                                foreach ($datos as $clave => $valor) {
                                                    $htmlContent = str_replace($clave, $valor, $htmlContent);
                                                }

                                                $to = $email;
                                                $subject = '¡Bienvenida a Aúna!';
                                                $body = $htmlContent;
                                                $altBody = '';
                                                $attachments = [];

                                                if ($mailer->sendEmail($to, $subject, $body, $altBody, $attachments)) {
                                                    error_log("Correo enviado a : ".$email);
                                                }else{
                                                    error_log("No se pudo enviar el correo a : ".$email);
                                                }
                                            }catch(Exception $errorMail){
                                                error_log(print_r('error: '.json_encode($errorMail), TRUE));

                                            }
                                        }else{
                                            if($pageSlug == 'donativos_2024'){
                                                $hasTag = false;
                                                    $tags = $respuesta["person"]["tags"];

                                                            
                                                    foreach ($tags as $elemento) {
                                                        if ($tags == "Voto2024") {
                                                            $hasTag = true;
                                                            error_log("Tag encontrado");
                                                            break;
                                                        }
                                                    }
                                                    if($hasTag == false){
                                                        $urlTags = $url_base.'/api/v1/people/'.$idPerson.'/taggings'.'?access_token='.$tokenNB;
                                                                                
                                                        $tagData = array(
                                                            'tagging' => array(
                                                                'tag' => 'Voto2024'
                                                            )
                                                        );
                                    
                                                        
                                                        $tagJson = json_encode($tagData);
                                    
                                                        $ch = curl_init($urlTags);
                                                        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                                                        curl_setopt($ch, CURLOPT_POSTFIELDS, $tagJson);
                                                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                                                        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                                            'Content-Type: application/json'
                                                        ));
                                    
                                                        $resultado = curl_exec($ch);
                                    
                                                        if ($resultado === false) {
                                                            error_log("[".$date."] Error al ejecutar la solicitud: " . curl_error($ch));
                                                        } else {
                                                            $codigoRespuesta = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                                                            echo "Código de Respuesta: $codigoRespuesta\n";
                                                            echo "Cuerpo de la Respuesta: $resultado\n";
                                                        }
                                                    }
                                            }
                                            else if($pageSlug == 'atria_2024_prueba' || $pageSlug == 'atria_2024'){
                                                $hasTag = false;
                                                    $tags = $respuesta["person"]["tags"];

                                                            
                                                    foreach ($tags as $elemento) {
                                                        if ($tags == "Atria24") {
                                                            $hasTag = true;
                                                            error_log("Tag encontrado");
                                                            break;
                                                        }
                                                    }
                                                    if($hasTag == false){
                                                        $urlTags = $url_base.'/api/v1/people/'.$idPerson.'/taggings'.'?access_token='.$tokenNB;
                                                                                
                                                        $tagData = array(
                                                            'tagging' => array(
                                                                'tag' => 'Atria24'
                                                            )
                                                        );
                                    
                                                        
                                                        $tagJson = json_encode($tagData);
                                    
                                                        $ch = curl_init($urlTags);
                                                        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                                                        curl_setopt($ch, CURLOPT_POSTFIELDS, $tagJson);
                                                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                                                        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                                            'Content-Type: application/json'
                                                        ));
                                    
                                                        $resultado = curl_exec($ch);
                                    
                                                        if ($resultado === false) {
                                                            error_log("[".$date."] Error al ejecutar la solicitud: " . curl_error($ch));
                                                        } else {
                                                            $codigoRespuesta = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                                                            echo "Código de Respuesta: $codigoRespuesta\n";
                                                            echo "Cuerpo de la Respuesta: $resultado\n";
                                                        }

                                                        
                                                    }
                                            }
                                            
                                        }

                                        $urlDonacion = $url_base.'/api/v1/donations'.'?access_token='.$tokenNB;
                                        $zona_horaria = date_default_timezone_get();
                    
                                        $fecha_actual = date('Y-m-d\TH:i:s', time()) . date('P');
                    
                                        $donacionData = array(
                                            'donation' => array(
                                                'donor_id' => $idPerson,
                                                'amount_in_cents' => $amount*100,
                                                'payment_type_name' => 'Credit Card',
                                                'succeeded_at' => $fecha_actual,
                                                'page_slug' => $pageSlug,
                                                'custom_values' => array(
                                                    'rfc' => $rfc,
                                                    'direccion_fiscal' => isset($taxAddress) ? $taxAddress : null,
                                                    'r_gimen_fiscal' => isset($taxRegime) ? $taxRegime : null,
                                                    'uso_cfdi' => isset($cfdiUse) ? $cfdiUse : null
                                                )
                                            )
                                        );
                    
                                        
                                        $donacionJson = json_encode($donacionData);
                    
                                        $ch = curl_init($urlDonacion);
                                        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                                        curl_setopt($ch, CURLOPT_POSTFIELDS, $donacionJson);
                                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                                        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                            'Content-Type: application/json'
                                        ));
                    
                                        $resultado = curl_exec($ch);
                    
                                        if ($resultado === false) {
                                            error_log("[".$date."] Error al ejecutar la solicitud: " . curl_error($ch));
                                        } else {
                                            $codigoRespuesta = curl_getinfo($ch, CURLINFO_HTTP_CODE);

                                            echo "Código de Respuesta: $codigoRespuesta\n";
                                            echo "Cuerpo de la Respuesta: $resultado\n";
                                        }

                                        try{
                                            date_default_timezone_set('America/Mexico_City');
                                            $date = new DateTime();
                                            $formatter = new IntlDateFormatter(
                                                'es_MX',
                                                IntlDateFormatter::FULL,
                                                IntlDateFormatter::NONE,
                                                'America/Mexico_City',
                                                IntlDateFormatter::GREGORIAN,
                                                "d 'de' MMMM 'del' y"
                                            );

                                            $formattedDate = $formatter->format($date);

                                            $mailer = new Mailer();

                                            $templateDonation = 'templates/donation_unique.html';

                                            $htmlContent = file_get_contents($templateDonation);

                                            $fullAddress = $customerInfo["address"]." ".$customerInfo["address2"]." "
                                                .$customerInfo["city"]." ".$customerInfo["state"]." ".$customerInfo["zip"];

                                            $datos = array(
                                                '{{first_name}}' => $firstName,
                                                '{{long_name}}' => $firstName." ".$lastName,
                                                '{{donationId}}' => '',
                                                '{{donation.succeeded_at}}' => $formattedDate,
                                                '{{billing_address}}' => $fullAddress,
                                                '{{name}}' => $firstName,
                                                '{{phone}}' => $phone,
                                                '{{email}}' => $email,
                                                '{{amount}}' => "$".$amount,
                                                '{{nex_billing_date}}' =>  '',
                                                '{{paymentType}}' => 'Card'

                                            );
                                            
                                            // Reemplazar los marcadores de posición con los valores reales
                                            foreach ($datos as $clave => $valor) {
                                                $htmlContent = str_replace($clave, $valor, $htmlContent);
                                            }

                                            $to = $email;
                                            $subject = '¡Gracias por donar a Aúna!';
                                            $body = $htmlContent;
                                            $altBody = '';
                                            $attachments = [];

                                            if ($mailer->sendEmail($to, $subject, $body, $altBody, $attachments)) {
                                                error_log("Correo enviado a : ".$email);
                                            }else{
                                                error_log("No se pudo enviar el correo a : ".$email);
                                            }
                                        }catch(Exception $errorMail){
                                            error_log(print_r('error: '.json_encode($errorMail), TRUE));

                                        }

                                        if($isMembership == 1){
                                            $urlMembresia = $url_base.'/api/v1/people/'.$idPerson.'/memberships?access_token='.$tokenNB;
                                            $zona_horaria = date_default_timezone_get();
                        
                                            $fecha_actual = date('Y-m-d\TH:i:s', time()) . date('P');

                                            $fechaExpiracion = new DateTime();

                                            
                                            $fechaExpiracion->modify('+1 year');


                                            $fechaExpiracion = $fechaExpiracion->format('Y-m-d\TH:i:sP');

                        
                                            $membershipData = array(
                                                'membership' => array(
                                                    'name' => 'Aúna',
                                                    'status' => 'active',
                                                    'status_reason' => 'paid',
                                                    'started_at' => $fecha_actual,
                                                    'expires_on' => $fechaExpiracion
                                                )
                                            );
                        
                                            
                                            $membresiaJson = json_encode($membershipData);
                        
                                            $ch = curl_init($urlMembresia);
                                            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                                            curl_setopt($ch, CURLOPT_POSTFIELDS, $membresiaJson);
                                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                                            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                                'Content-Type: application/json'
                                            ));
                        
                                            $resultado = curl_exec($ch);
                        
                                            if ($resultado === false) {
                                                error_log("[".$date."] Error al ejecutar la solicitud: " . curl_error($ch));
                                            } else {
                                                $codigoRespuesta = curl_getinfo($ch, CURLINFO_HTTP_CODE);

                                                echo "Código de Respuesta: $codigoRespuesta\n";
                                                echo "Cuerpo de la Respuesta: $resultado\n";
                                            }
                                        }
                    
                                        
                    
                                    }else{
                                        error_log("Hubo un erro al crear al usuario. Datos capturados: ".json_encode($dataPerson));
                                    }
                                } else {
                                    // Hubo un error en la solicitud
                                    error_log("[".$date."] Error en la solicitud. Código de respuesta HTTP: " . $httpCode);
                                }
                            }
                            curl_close($ch);
                        }catch(Exception $err){
                            error_log(print_r('error: '.json_encode($error), TRUE));
                        }

                    //PRUEBAS DE PRODUCCIÓN
                    $stmt->close();
                    $conn->close();
                    return;
                        

                    if($facturaGenerada === true){
                        /*if ($mailer->sendEmail($to, $subject, $body, $altBody)) {
                            error_log('Message has been sent. '.$altBody);
                        } else {
                            error_log('Message could not be sent');
                        }*/

                        $payment_intent = $stripe->paymentIntents->retrieve($session->payment_intent);

                        $balance_transaction_id = $payment_intent->charges->data[0]->balance_transaction;
                        $balance_transaction = \Stripe\BalanceTransaction::retrieve($balance_transaction_id);

                        $comisionStripe = $balance_transaction->fee / 100;
                        $docRef = $session->id;              


                        $sql = "UPDATE donation SET statusDonation = 3, comisionStripe = ?, docRefStripe = ? WHERE id = ?";
                
                        // Prepara la sentencia
                        $stmt = $conn->prepare($sql);
                        $comisionIva = $comisionStripe / 1.16;
                        
                        // Vincula los parámetros
                        $stmt->bind_param("dsi", $comisionStripe, $docRef, $row["id"]);
                        
                        // Ejecuta la consulta
                        if ($stmt->execute()) {
                        
                            error_log("Se ha guardado comisión ");
                        } else {
                            error_log("Error al guardar los datos: " . $stmt->error);
                        }


                        $vendorBill = new VendorBillHelper();
                        $vendorBill->vendorId = $vendorId;//530;
                        $vendorBill->account = $vendorAccount;//569;
                        $vendorBill->formVendor = $formularioOrden;//421;
                        $vendorBill->subsidiary = $subsidiary;//2;
                        $vendorBill->memo = $memo;//"Factura creada desde stripe";
                        $vendorBill->location = $locationVendor;//1;
                        $vendorBill->currency = $currencyVendor;//1;
                        $vendorBill->itemId = $itemVendor;//123;
                        $vendorBill->class = $classVendor;//105;
                        $vendorBill->department = $departmentVendor;//308;
                        $vendorBill->amount = $comisionIva;
                        $vendorBill->docRef = $row["id"];


                        $vendorBillId = generateBillOrder($vendorBill, $comisionIva, $row["id"]);


                        $sql = "UPDATE donation SET statusDonation = 4, vendorBillId = ? WHERE id = ?";
                
                        // Prepara la sentencia
                        $stmt = $conn->prepare($sql);
                        
                        // Vincula los parámetros
                        $stmt->bind_param("si", $vendorBillId, $row["id"]);
                        
                        // Ejecuta la consulta
                        if ($stmt->execute()) {
                            error_log( "Se ha generado la Factura de proveedor ".$vendorBillId." en netsuite");
                            error_log("VendorBill: ".$vendorBillId);
                        } else {
                            error_log("Error al guardar los datos: " . $stmt->error);
                        }

                        $vendorPayment = new VendorPaymentHelper();
                        $vendorPayment->appAccount = $appAccountVendor;//569;
                        $vendorPayment->formPayment = $formularioPayment;//410;
                        $vendorPayment->vendorId = $vendorId;//530;
                        $vendorPayment->subsidiary = $subsidiary;//2;
                        $vendorPayment->account = $accountPayment;//835;
                        $vendorPayment->currency = $currencyVendor;//1;
                        $vendorPayment->class = $classVendor;//105;
                        $vendorPayment->department = $departmentVendor;//308;
                        $vendorPayment->location = $locationVendor;//1;
                        $vendorPayment->billOrder = $vendorBillId;
                        $vendorPayment->amount = $comisionStripe;

                        $vendorPayment = generatePaymentBill($vendorPayment, $vendorBillId, $comisionStripe);

                        $sql = "UPDATE donation SET statusDonation = 5, vendorPaymentId = ? WHERE id = ?";
                
                        // Prepara la sentencia
                        $stmt = $conn->prepare($sql);
                        
                        // Vincula los parámetros
                        $stmt->bind_param("si", $vendorPayment, $row["id"]);
                        
                        // Ejecuta la consulta
                        if ($stmt->execute()) {
                            error_log( "Se ha generado el pago a proveedor ".$vendorPayment." en netsuite");
                            error_log("Vendor Payment: ".$vendorPayment);
                        } else {
                            error_log("Error al guardar los datos: " . $stmt->error);
                        }



                        //enviar correo
                        /*
                            {{ long_name }} => firstName + lastName
                                {{ donationId }} => ""
                                {{ donation.succeeded_at }} => createdDate
                                {{ billing_address }} => address + address2 + city + state + zip
                                {{ name }} => firstName
                                {{ billing_address }} => address + address2 + city + state + zip
                                {{ phone }} => phone
                                {{ email }} => email
                                {{ amount }} => amount
                                {{ nex_billing_date }} => createdDate + 1 year
                                {{ paymentType }} => stripe.payment_method_types

                        */

                        try{
                            

                            /*

                            $customerInfo["email"] = $row["email"];
                    $customerInfo["rfc"] = $row["rfc"];
                    $customerInfo["amount"] = $row["amount"];
                    $customerInfo["cfdiUsage"] = $row["cfdiUsage"];
                    $customerInfo["taxRegime"] = $row["taxRegime"];
                    $customerInfo["address"] = $row["address"];
                    $customerInfo["address2"] = $row["address2"];
                    $customerInfo["zip"] = $row["zip"];
                    $customerInfo["city"] = $row["city"];
                    $customerInfo["state"] = $row["state"];
                    $customerInfo["satName"] = $row["satName"];
                            */

                            
                        }catch(Exception $errorMail){

                        }
                    }
                    

                    
                }
            } else {
                //echo "No se encontraron resultados.";
                error_log(print_r('Error: No se encontraron resultados'), TRUE);
            }
        
        // Cierra la sentencia y la conexión
        $stmt->close();
        $conn->close();
    }catch(Exception $error){
        error_log(print_r('error: '.json_encode($error), TRUE));
    }

?>