<?php

header("Access-Control-Allow-Origin: https://auna.nationbuilder.com");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

    require_once 'secrets.php';
    require_once 'tools.php';
    require_once 'vendor/autoload.php';
    require_once 'models/InvoiceHelper.php';
    require_once 'netsuite/seach.php';
    require_once 'netsuite/crud.php';
    
    
    
    use OAuth\OAuth1\Signature\Signature;
    use OAuth\Common\Storage\Session;
    use OAuth\Common\Consumer\Credentials;
    use OAuth\ServiceFactory;
    use OAuth\Common\Http\Uri\Uri;
    use OAuth\Common\Http\Uri\UriInterface;
    use OAuth\Common\Http\Client\ClientInterface;
    use OAuth\Common\Http\Uri\UriFactory;
    use OAuth\Common\Http\Client\CurlClient;


    $categories = 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",
        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"
    );

    $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);
        
    }
    if(isset($_SERVER["HTTP_ORIGIN"]))
{
    // You can decide if the origin in $_SERVER['HTTP_ORIGIN'] is something you want to allow, or as we do here, just allow all
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
}
else
{
    //No HTTP_ORIGIN set, so we allow any. You can disallow if needed here
    header("Access-Control-Allow-Origin: *");
}

header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 600");    // cache for 10 minutes

if($_SERVER["REQUEST_METHOD"] == "OPTIONS")
{
    if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_METHOD"]))
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT"); //Make sure you remove those you do not want to support

    if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"]))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    //Just exit with 200 OK with the above headers for OPTIONS method
    exit(0);
}
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        header("Access-Control-Allow-Headers: Content-Type");
        $jsonData = json_decode(file_get_contents('php://input'), true);
        // Recibe los parámetros del formulario
        $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"];


        $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) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?,?)";
        
        // Prepara la sentencia
        $stmt = $conn->prepare($sql);
        
        // Vincula los parámetros
        $stmt->bind_param("ssidsssssssssssss", $firstName, $lastName, $statusDonation, $amount, $email, $phone, $country, $address, $address2, $zip, $rfc, $city, $state, $taxAddress, $taxRegime, $cfdiUse, $currentDate);
        
        // Ejecuta la consulta
        if ($stmt->execute()) {
            echo "Los datos se han guardado correctamente en la base de datos.";
        } else {
            echo "Error al guardar los datos: " . $stmt->error;
        }

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

        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"];


                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;

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

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

                if(isset($customer)){
                    
                }
                                
                //$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;
                }
                

                $invoiceData = new InvoiceHelper();
                $cfdiUsage = $invoiceData->getId($valor, $categories);
                $invoiceData->customerId = $customer->internalId;
                $invoiceData->locationId = 2;
                $invoiceData->departmentId = 308;
                $invoiceData->accountId = 550;
                $invoiceData->classId = 105;
                $invoiceData->termsId = 1;
                $invoiceData->itemId = 111;
                $invoiceData->amount = $customerInfo["amount"];
                $invoiceData->cfdiUsageId = $cfdiUsage;
                

                $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"]);
                
                // Ejecuta la consulta
                if ($stmt->execute()) {
                    echo "Se ha generado la factura ".$invoiceId." en netsuite";
                    error_log("factur: ".$invoiceId);
                } else {
                    echo "Error al guardar los datos: " . $stmt->error;
                }

                
                //generateInvoice();


                


                //echo json_encode($rfc);
                //$emailInfo = searchByEmail('pgcrurom4@gmail.com');
                //echo json_encode($emailInfo);

                /*$apiUrl = "https://8551419-SB1.suitetalk.api.netsuite.com/services/rest/record/v1/customer";
                $params = array();
                if (isset($customerInfo["rfc"]) && !empty($customerInfo["rfc"])) 
                {
                    //$apiUrl = $apiUrl."?q=%20START_WITH%20".$customerInfo["rfc"];
                    $params["q"] = "custentity_mx_rfc START_WITH ".$customerInfo["rfc"];
                }else{
                    $parts = explode("@", $customerInfo["email"]);
                    $partEmail = $parts[0];
                    
                    $params["q"] = "email START_WITH ".$customerInfo["rfc"];
                    //$apiUrl = $apiUrl."?q=%20START_WITH%20".$partEmail;
                }
                $method = 'GET'; // Cambia a GET para una solicitud GET
                // Generar una cadena base
                // Agregar los parámetros a la URL

                $rawParameters = (str_replace('+', '%20', http_build_query($params)));
                
                //$apiUrl .= '?' . http_build_query($params);
                $apiUrl .= '?' . $rawParameters;
                error_log("rawParameters: ".$apiUrl);


                // Generar una cadena base
                $baseString = $method . '&' . rawurlencode($apiUrl) . '&';
                
                ksort($params);
                $paramString = (str_replace('+', '%20', http_build_query($params, '', '&')));


                //$paramString = http_build_query($params, '', '&');
                $baseString .= rawurlencode($paramString);
                
                

                // Crear una clave de firma
                $key = rawurlencode($consumerSecret) . '&' . rawurlencode($tokenSecret);

                // Calcular la firma HMAC-SHA1
                $signature = base64_encode(hash_hmac('sha256', $baseString, $key, true));

                // Agregar la firma a la solicitud (en este ejemplo, se agrega como un encabezado Authorization)
                $authorizationHeader = 'OAuth ' .
                'realm="'.$realm.'", ' .
                'oauth_consumer_key="' . rawurlencode($consumerKey) . '", ' .
                'oauth_nonce="' . uniqid() . '", ' .
                'oauth_signature="' . rawurlencode($signature) . '", ' .
                'oauth_signature_method="HMAC-SHA256", ' .
                'oauth_timestamp="' . time() . '", ' .
                'oauth_token="' . rawurlencode($accessToken) . '", ' .
                'oauth_version="1.0"'
                ;

                

                error_log($authorizationHeader);
                error_log($apiUrl);
                // Inicializar la sesión cURL
                $ch = curl_init();

                // Configurar la URL de la solicitud GET
                curl_setopt($ch, CURLOPT_URL, $apiUrl);

                // Capturar la respuesta en lugar de imprimirla
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

                // Agregar la cabecera de autorización OAuth
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Authorization: ' . $authorizationHeader,
                ));

                
                // Realizar la solicitud HTTP
                $response = curl_exec($ch);

                // Comprobar errores
                if (curl_errno($ch)) {
                    echo 'Error en la solicitud cURL: ' . curl_error($ch);
                }

                // Cerrar la sesión cURL
                curl_close($ch);

                // Manejar la respuesta
                if ($response !== false) {
                    error_log(print_r('data: '.json_encode($response), TRUE));
                } else {
                    error_log(print_r('Error: '.json_encode($response), TRUE));
                }
                */
            
                
                
            }
        } 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();
    }


?>