<?php
include '../config.php';  include '../checkSession.php';


$lang = $_GET['lang'];
$enviado = $_GET['enviado'];

$titulo = trim($_GET['titulo']);
$avisoLink = trim($_GET['avisoLink']);
$avisoTextoBoton = trim($_GET['avisoTextoBoton']);
$avisoTexto = trim($_POST['avisoTexto']);
$avisoTexto = base64_decode($avisoTexto);

$tituloSolicitudprivado = trim($_GET['tituloSolicitudprivado']);

$textoSolicitudprivado = trim($_POST['textoSolicitudprivado']);
$textoSolicitudprivado = base64_decode($textoSolicitudprivado);


$titulo = urlencode($titulo);
$avisoLink = urlencode($avisoLink);
$avisoTextoBoton= urlencode($avisoTextoBoton);
$avisoTexto = rawurlencode($avisoTexto);
$tituloSolicitudprivado = urlencode($tituloSolicitudprivado);
$textoSolicitudprivado = rawurlencode($textoSolicitudprivado);
$oldimg = trim($_POST['oldimg']);
$newimg = trim($_POST['newimgimagenprod']);
$imagen = $oldimg;


$oldimglateral = trim($_POST['oldimglateral']);
$newimglateral = trim($_POST['newimgimagenlateral']);
$imagenlateral = $oldimglateral;

//echo $newimg;


    ////////////////SI HUBO CAMBIO DE IMAGEN

    if($newimg == 1){

        if (isset($_FILES['imagenprod']) && $_FILES['imagenprod']['error'] === UPLOAD_ERR_OK)
        {
            // get details of the uploaded file
            $fileTmpPath = $_FILES['imagenprod']['tmp_name'];
            $fileName = $_FILES['imagenprod']['name'];
            $fileSize = $_FILES['imagenprod']['size'];
            $fileType = $_FILES['imagenprod']['type'];
            $fileNameCmps = explode(".", $fileName);
            $fileExtension = strtolower(end($fileNameCmps));
        
            // sanitize file-name
            $newFileName = "banner_destacado_".date().$lang. '.' . $fileExtension;
    
            // check if file has one of the following extensions
            $allowedfileExtensions = array('jpg', 'gif', 'png', 'webp', 'svg');
        
            if (in_array($fileExtension, $allowedfileExtensions))
            {
            ///////////////SUBIR A AWS
                /// AWS API keys
                $aws_access_key_id_privado = $aws_access_key_id_privado;
                $aws_secret_access_key_privado = $aws_secret_access_key_privado;
                // Bucket
                $bucket_name_privado = $bucket_name_privado;
                // AWS region and Host Name (Host names are different for each AWS region)
                // As an example these are set to us-east-1 (US Standard)
                $aws_region_privado = $aws_region_privado;
                $host_name = $bucket_name_privado . '.s3.amazonaws.com';

                // Server path where content is present. This is just an example
                //$content_path = $dest_path;
                $content = file_get_contents($fileTmpPath);

                // AWS file permissions
                $content_acl = 'public-read';

                // MIME type of file. Very important to set if you later plan to load the file from a S3 url in the browser (images, for example)
                $content_type = 'image/'.$fileExtension;

                if($content_type == 'image/svg' ){ $content_type = "image/svg+xml";}
                // Name of content on S3
                $content_title = 'img/privado/'.$newFileName;

                // Service name for S3
                $aws_service_name = 's3';

                // UTC timestamp and date
                $timestamp = gmdate('Ymd\THis\Z');
                $date = gmdate('Ymd');

                // HTTP request headers as key & value
                $request_headers = array();
                $request_headers['Content-Type'] = $content_type;
                $request_headers['Date'] = $timestamp;
                $request_headers['Host'] = $host_name;
                $request_headers['x-amz-acl'] = $content_acl;
                $request_headers['x-amz-content-sha256'] = hash('sha256', $content);
                // Sort it in ascending order
                ksort($request_headers);

                // Canonical headers
                $canonical_headers = [];
                foreach($request_headers as $key => $value) {
                    $canonical_headers[] = strtolower($key) . ":" . $value;
                }
                $canonical_headers = implode("\n", $canonical_headers);

                // Signed headers
                $signed_headers = [];
                foreach($request_headers as $key => $value) {
                    $signed_headers[] = strtolower($key);
                }
                $signed_headers = implode(";", $signed_headers);

                // Cannonical request 
                $canonical_request = [];
                $canonical_request[] = "PUT";
                $canonical_request[] = "/" . $content_title;
                $canonical_request[] = "";
                $canonical_request[] = $canonical_headers;
                $canonical_request[] = "";
                $canonical_request[] = $signed_headers;
                $canonical_request[] = hash('sha256', $content);
                $canonical_request = implode("\n", $canonical_request);
                $hashed_canonical_request = hash('sha256', $canonical_request);

                // AWS Scope
                $scope = [];
                $scope[] = $date;
                $scope[] = $aws_region_privado;
                $scope[] = $aws_service_name;
                $scope[] = "aws4_request";

                // String to sign
                $string_to_sign = [];
                $string_to_sign[] = "AWS4-HMAC-SHA256"; 
                $string_to_sign[] = $timestamp; 
                $string_to_sign[] = implode('/', $scope);
                $string_to_sign[] = $hashed_canonical_request;
                $string_to_sign = implode("\n", $string_to_sign);

                // Signing key
                $kSecret = 'AWS4' . $aws_secret_access_key_privado;
                $kDate = hash_hmac('sha256', $date, $kSecret, true);
                $kRegion = hash_hmac('sha256', $aws_region_privado, $kDate, true);
                $kService = hash_hmac('sha256', $aws_service_name, $kRegion, true);
                $kSigning = hash_hmac('sha256', 'aws4_request', $kService, true);

                // Signature
                $signature = hash_hmac('sha256', $string_to_sign, $kSigning);

                // Authorization
                $authorization = [
                    'Credential=' . $aws_access_key_id_privado . '/' . implode('/', $scope),
                    'SignedHeaders=' . $signed_headers,
                    'Signature=' . $signature
                ];
                $authorization = 'AWS4-HMAC-SHA256' . ' ' . implode( ',', $authorization);

                // Curl headers
                $curl_headers = [ 'Authorization: ' . $authorization ];
                foreach($request_headers as $key => $value) {
                    $curl_headers[] = $key . ": " . $value;
                }

                $url = 'https://' . $host_name . '/' . $content_title;
                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_HEADER, false);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_headers);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
                curl_exec($ch);
                $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                if($http_code != 200){
                    echo "Error AWS";
                    $info = curl_getinfo($ch);
                    print_r($info['request_header']);
                }
                if($http_code == 200){
                    $imagen = $content_title;
                    //echo "Sin Error AWS";
                }
        
                
            }
            else
            {
                $message = '<p style="color:red; font-size:12px;">Extensión de imagen no válida. Verifica que tu archivo tenga uno de los siguientes formatos: ' . implode(', ', $allowedfileExtensions).'</p>';
                echo $message;
                exit();
            }
        }
        else
        {
            $message = '<p style="color:red; font-size:12px;">Error en subida de imagen:<br></p> ';
            $message .= '<p style="color:red; font-size:12px;">Error:' . $_FILES['imagen']['error'].'</p>';
            echo $message;
            exit();
        }
        echo $message;
    }
    
    
    ////////////////SI HUBO CAMBIO DE IMAGEN LATERAL

    if($newimglateral == 1){

        if (isset($_FILES['imagenlateral']) && $_FILES['imagenlateral']['error'] === UPLOAD_ERR_OK)
        {
            // get details of the uploaded file
            $fileTmpPath = $_FILES['imagenlateral']['tmp_name'];
            $fileName = $_FILES['imagenlateral']['name'];
            $fileSize = $_FILES['imagenlateral']['size'];
            $fileType = $_FILES['imagenlateral']['type'];
            $fileNameCmps = explode(".", $fileName);
            $fileExtension = strtolower(end($fileNameCmps));
        
            // sanitize file-name
            $newFileName = "lateral_privado_".date().$lang. '.' . $fileExtension;
    
            // check if file has one of the following extensions
            $allowedfileExtensions = array('jpg', 'gif', 'png', 'webp', 'svg');
        
            if (in_array($fileExtension, $allowedfileExtensions))
            {
            ///////////////SUBIR A AWS
                /// AWS API keys
                $aws_access_key_id_privado = $aws_access_key_id_privado;
                $aws_secret_access_key_privado = $aws_secret_access_key_privado;
                // Bucket
                $bucket_name_privado = $bucket_name_privado;
                // AWS region and Host Name (Host names are different for each AWS region)
                // As an example these are set to us-east-1 (US Standard)
                $aws_region_privado = $aws_region_privado;
                $host_name = $bucket_name_privado . '.s3.amazonaws.com';

                // Server path where content is present. This is just an example
                //$content_path = $dest_path;
                $content = file_get_contents($fileTmpPath);

                // AWS file permissions
                $content_acl = 'public-read';

                // MIME type of file. Very important to set if you later plan to load the file from a S3 url in the browser (images, for example)
                $content_type = 'image/'.$fileExtension;

                if($content_type == 'image/svg' ){ $content_type = "image/svg+xml";}
                // Name of content on S3
                $content_title = 'img/privado/'.$newFileName;

                // Service name for S3
                $aws_service_name = 's3';

                // UTC timestamp and date
                $timestamp = gmdate('Ymd\THis\Z');
                $date = gmdate('Ymd');

                // HTTP request headers as key & value
                $request_headers = array();
                $request_headers['Content-Type'] = $content_type;
                $request_headers['Date'] = $timestamp;
                $request_headers['Host'] = $host_name;
                $request_headers['x-amz-acl'] = $content_acl;
                $request_headers['x-amz-content-sha256'] = hash('sha256', $content);
                // Sort it in ascending order
                ksort($request_headers);

                // Canonical headers
                $canonical_headers = [];
                foreach($request_headers as $key => $value) {
                    $canonical_headers[] = strtolower($key) . ":" . $value;
                }
                $canonical_headers = implode("\n", $canonical_headers);

                // Signed headers
                $signed_headers = [];
                foreach($request_headers as $key => $value) {
                    $signed_headers[] = strtolower($key);
                }
                $signed_headers = implode(";", $signed_headers);

                // Cannonical request 
                $canonical_request = [];
                $canonical_request[] = "PUT";
                $canonical_request[] = "/" . $content_title;
                $canonical_request[] = "";
                $canonical_request[] = $canonical_headers;
                $canonical_request[] = "";
                $canonical_request[] = $signed_headers;
                $canonical_request[] = hash('sha256', $content);
                $canonical_request = implode("\n", $canonical_request);
                $hashed_canonical_request = hash('sha256', $canonical_request);

                // AWS Scope
                $scope = [];
                $scope[] = $date;
                $scope[] = $aws_region_privado;
                $scope[] = $aws_service_name;
                $scope[] = "aws4_request";

                // String to sign
                $string_to_sign = [];
                $string_to_sign[] = "AWS4-HMAC-SHA256"; 
                $string_to_sign[] = $timestamp; 
                $string_to_sign[] = implode('/', $scope);
                $string_to_sign[] = $hashed_canonical_request;
                $string_to_sign = implode("\n", $string_to_sign);

                // Signing key
                $kSecret = 'AWS4' . $aws_secret_access_key_privado;
                $kDate = hash_hmac('sha256', $date, $kSecret, true);
                $kRegion = hash_hmac('sha256', $aws_region_privado, $kDate, true);
                $kService = hash_hmac('sha256', $aws_service_name, $kRegion, true);
                $kSigning = hash_hmac('sha256', 'aws4_request', $kService, true);

                // Signature
                $signature = hash_hmac('sha256', $string_to_sign, $kSigning);

                // Authorization
                $authorization = [
                    'Credential=' . $aws_access_key_id_privado . '/' . implode('/', $scope),
                    'SignedHeaders=' . $signed_headers,
                    'Signature=' . $signature
                ];
                $authorization = 'AWS4-HMAC-SHA256' . ' ' . implode( ',', $authorization);

                // Curl headers
                $curl_headers = [ 'Authorization: ' . $authorization ];
                foreach($request_headers as $key => $value) {
                    $curl_headers[] = $key . ": " . $value;
                }

                $url = 'https://' . $host_name . '/' . $content_title;
                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_HEADER, false);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_headers);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
                curl_exec($ch);
                $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                if($http_code != 200){
                    echo "Error AWS";
                    $info = curl_getinfo($ch);
                    print_r($info['request_header']);
                }
                if($http_code == 200){
                    $imagenlateral = $content_title;
                    //echo "Sin Error AWS";
                }
        
                
            }
            else
            {
                $message = '<p style="color:red; font-size:12px;">Extensión de imagen no válida. Verifica que tu archivo tenga uno de los siguientes formatos: ' . implode(', ', $allowedfileExtensions).'</p>';
                echo $message;
                exit();
            }
        }
        else
        {
            $message = '<p style="color:red; font-size:12px;">Error en subida de imagen:<br></p> ';
            $message .= '<p style="color:red; font-size:12px;">Error:' . $_FILES['imagenlateral']['error'].'</p>';
            echo $message;
            exit();
        }
        echo $message;
    }


    $curl = curl_init();
    $id="ckuwqltrkpenm0b788cug2f0d";

    if($lang == "en"){

        curl_setopt_array($curl, array(
            CURLOPT_URL => $endpoint_graph_cms,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS =>'{"query":"mutation MyMutation {\\r\\n  updateGeneralidadesSitioPrivado(data: {titulo: \\"'.$titulo.'\\",  avisoLink: \\"'.$avisoLink.'\\", avisoTextoBoton: \\"'.$avisoTextoBoton.'\\", avisoTexto: \\"'.$avisoTexto.'\\", tituloSolicitudPrivado: \\"'.$tituloSolicitudprivado.'\\", textoSolicitudPrivado: \\"'.$textoSolicitudprivado.'\\", avisoImagen: \\"'.$imagen.'\\",  imagenLateral: \\"'.$imagenlateral.'\\", enviadoRevision: \\"'.$enviado.'\\"}, where: {id: \\"'.$id.'\\"}) {\\r\\n    id\\r\\n  }\\r\\n  \\r\\n}\\r\\n","variables":{}}',
            CURLOPT_HTTPHEADER => array(
              'Content-Type: application/json',
              'Cookie: __cfduid=da2693cdfd39b7377a8a05e305da45b8f1613001694'
            ),
          ));

    }

    if($lang == "es"){
        curl_setopt_array($curl, array(
            CURLOPT_URL => $endpoint_graph_cms,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS =>'{"query":"mutation MyMutation {\\r\\n  updateGeneralidadesSitioPrivado(data: {localizations: {update: {data: {titulo: \\"'.$titulo.'\\",  avisoLink: \\"'.$avisoLink.'\\", avisoTextoBoton: \\"'.$avisoTextoBoton.'\\", avisoTexto: \\"'.$avisoTexto.'\\", tituloSolicitudPrivado: \\"'.$tituloSolicitudprivado.'\\", textoSolicitudPrivado: \\"'.$textoSolicitudprivado.'\\", avisoImagen: \\"'.$imagen.'\\", imagenLateral: \\"'.$imagenlateral.'\\", enviadoRevision: \\"'.$enviado.'\\"}, locale: es_MX}}}, where: {id: \\"'.$id.'\\"}) {\\r\\n    id\\r\\n  }\\r\\n  \\r\\n\\r\\n}","variables":{}}',
            CURLOPT_HTTPHEADER => array(
              'Content-Type: application/json',
              'Cookie: __cfduid=da2693cdfd39b7377a8a05e305da45b8f1613001694'
            ),
          ));

    }


    $response = curl_exec($curl);
    curl_close($curl);
    echo $response;

    $jsonrespuesta = json_decode($response, true);
    $id = $jsonrespuesta['data']['updateGeneralidadesSitioPrivado']['id'];

//echo $id;

  $sucess = "<p class='successmsg'>Información actualizada correctamente</p>";
  $fail = "<p class='errormsg'>Falló la actualización..</p>  ";


if(strlen($id)>10){

    echo $sucess;

    $string = $newstatus;
    $string = '"'.$string.'"';
    echo '<script>
        
        setTimeout(() => {
            $(".popUpGenerales").fadeOut();
        }, 1500);
    </script>';
}

else{
    echo $fail;
}

?>