<?php
$id = $_POST['id'];
$status = $_POST['status'];
$modelo = $_POST['modelo'];

$endpoint = "https://api-us-east-1.graphcms.com/v2/ckkxmrn6cw3ga01ywc1spb2qu/master";
if(strlen($id)>10 && strlen($status)>2 && strlen($modelo)>2){

    $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $endpoint,
            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  update'.$modelo.'(data: {enviadoRevision: \\"publicado\\" localizations: {update: {data: {enviadoRevision: \\"publicado\\"}, locale: es_MX}}}, where: {id: \\"'.$id.'\\"}) {\\r\\n    id\\r\\n  }\\r\\n  unpublish'.$modelo.'(where: {id: \\"'.$id.'\\"}) {\\r\\n    id\\r\\n  }\\r\\n  publish'.$modelo.'(where: {id: \\"'.$id.'\\"}, locales: es_MX, to: PUBLISHED) {\\r\\n    id\\r\\n  }\\r\\n}\\r\\n","variables":{}}',
            CURLOPT_HTTPHEADER => array(
              'Content-Type: application/json',
              'Cookie: __cfduid=da2693cdfd39b7377a8a05e305da45b8f1613001694'
            ),
          ));

    $modeloupdate = 'update'.$modelo;
    $response = curl_exec($curl);
    curl_close($curl);
    //echo $response;
    
    $jsonrespuesta = json_decode($response, true);
    $id = $jsonrespuesta['data'][$modeloupdate]['id'];

    //echo $id;

    $sucess = "<p class='successmensaje'>Status actualizado correctamente</p>";
    $fail = "<p class='errormensaje'>Falló la actualización de status..</p> ";


    if(strlen($id)>10){

        

        if($status== 'oculto'){
            echo '<script>
                    $("body table .'.$id.'").fadeOut();
                    $(".'.$id.'").addClass("oculto");
                 </script>';
            exit();     
            
        }

        echo $sucess;

        if($status == 'borrador'){
            $newstatus = "<span class='statusenespera'>Borrador</span>";
        }
        
        if($status== 'publicado'){
            $newstatus = "<span class='statusentregado'>Publicado</span>";
        }
    
        $string = $newstatus;
        $string = '"'.$string.'"';
        echo '<script>
            $("#status'.$id.'").html('.$string.');
            setTimeout(() => {
                
                $(".popUpStatus").fadeOut();
            }, 1500);
        </script>';
    }

    else{
        echo $fail;
    }


}