<?php 
    include("../db.php"); 
?>
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script data-ad-client="ca-pub-8624645278635300" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.css" integrity="sha256-uXf0U0UCIqBp2J3S53b28h+fpC9uFcA8f+b/NNmiwVk=" crossorigin="anonymous" />
    <title>Live Stream</title>
<style>
.switch {
  position: relative;
  display: inline-block;
  width: 50px;
  height: 24px;
}

.switch input { 
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 16px;
  width: 16px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
</style>

<script src="https://apis.google.com/js/api.js"></script>
    <script>
      /**
       * Sample JavaScript code for youtube.liveBroadcasts.insert
       * See instructions for running APIs Explorer code samples locally:
       * https://developers.google.com/explorer-help/guides/code_samples#javascript
       */
     var broadcastid="";
     var streamid="";
     var channelid="";
     var timeout="";
      function authenticate() {
          return gapi.auth2.getAuthInstance()
              .signIn({scope: "https://www.googleapis.com/auth/youtube.force-ssl"})
            .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
      }
      function loadClient() {
          gapi.client.setApiKey("AIzaSyCTHo_9GiCiMErvzmF9jo0HuKc7L2zM8JU");
          return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
              .then(function() { console.log("GAPI client loaded for API"); 
                            $('#myModal').modal('hide');
                            <?php $_SESSION['authenticate']='yes'; ?>
                        getAllBroadcast();
              },
                  function(err) { console.error("Error loading GAPI client for API", err); });
      }

      function getAllBroadcast() {
      return gapi.client.youtube.liveBroadcasts.list({
          "part": "snippet,contentDetails,status",
            "broadcastType": "all",
      "mine": true
      })
          .then(function(response) {
                  // Handle the results here (response.result has the parsed body).
                  console.log("get Broadcast By id Response", response);
                  var items=response.result.items;
                  var html="";
                  for(var i=0;i<items.length;i++){
                      var temp=items[i];
                      var title=temp.snippet.title;
                      var desc=temp.snippet.description;
                      var id=temp.id;
                      var schTime=temp.snippet.scheduledStartTime.toLocaleString();
                        var thumb=temp.snippet.thumbnails.default.url;
                        var img='<img src="'+thumb+'" alt="thumb" >';
                      html+='<option style="color: #333333;"  time="'+schTime+'"desc="'+desc+'" title="'+title+'" value="'+id+'"><div class="row"> <div class="col-md-3">'+img+'</div><div class="col-md-9">'+title+'</div></div> <div class="row"> <divclass="col-md-3"> </div><div>Streamed: '+schTime+' </div></option>';
                  }
                 // var iframe=response.result.items[0].contentDetails.monitorStream.embedHtml;
                    //var iframe = response.result;
                  document.getElementById("broadlist").innerHTML=html;
              },
              function(err) { console.error("Execute error", err); });
  }
  function createNewBroadCast(key){
      
     if(key==1){
          var title=document.getElementById("retitle").value;
          var desc=document.getElementById("redescription").value;
            if(!title){
          alert("Please enter title")
          return false;
      }
        if(!desc){
          alert("Please enter description")
          return false;
      }
           createStream(title,desc);
     }else{
          var schdate=document.getElementById("schDate").value;
       var schtime=document.getElementById("schTime").value;
       if(schtime)
       var newDate=new Date(schdate+" "+schtime).toISOString();
       else
       var newDate=new Date().toISOString();
      var title=document.getElementById("title").value;
      if(!title){
          alert("Please enter title")
          return false;
      }
       var desc=document.getElementById("description").value;
       if(!desc){
          alert("Please enter description")
          return false;
      }
           return gapi.client.youtube.liveBroadcasts.insert({
      "part": "snippet,contentDetails,status",
      "resource": {
          "snippet": {
              "title":title,
              "description":desc,
          "scheduledStartTime": newDate
        },
        "contentDetails": {
              "enableAutoStart":true,
              "enableClosedCaptions": true,
          "enableContentEncryption": true,
          "enableDvr": true,
          "enableEmbed":false,
          "recordFromStart": true,
          "startWithSlate": false,
            "monitorStream": {
                "enableMonitorStream": true,
                "broadcastStreamDelayMs": 5
            }
        },
        "status": {
              "privacyStatus": "unlisted",
        }
      }
    })
        .then(function(response) {
          // Handle the results here (response.result has the parsed body).
          console.log("Response", response);
                broadcastid=response.result.id;
                createStream(title,desc)

      },
          function(err) { console.error("Execute error", err); });
     }
       
     
  }
  function updateBroadcast(){
      return gapi.client.youtube.liveBroadcasts.update({
      "part": "contentDetails",
      "resource": {
        "id": broadcastid,
        "contentDetails": {
         "enableClosedCaptions": false,
    "enableContentEncryption": true,
    "enableDvr":false,
    "enableEmbed": true,
    "recordFromStart": true,
    "startWithSlate": true,
    "monitorStream": {
      "enableMonitorStream": true,
      "broadcastStreamDelayMs": 5
            }
        }
      }
    })
        .then(function(response) {
                // Handle the results here (response.result has the parsed body).
                console.log("update embed Response", response);
              },
              function(err) { console.error("Execute error", err); });
  }
  function createStream(title,desc) {
      return gapi.client.youtube.liveStreams.insert({
          "part": "snippet,cdn,contentDetails,status",
          "resource": {
              "snippet": {
                  "title": title,
                  "description": desc
              },
              "cdn": {
                  "frameRate": "variable",
                  "ingestionType": "rtmp",
                  "resolution": "variable"
              },
              "contentDetails": {
                  "isReusable": true
              }
          }
      })
          .then(function(response) {
                  // Handle the results here (response.result has the parsed body).
                  console.log("Response", response);
                   streamid=response.result.id;
                   channelid=response.result.snippet.channelId;
                   bindStream();
                   addStream(channelid,title,desc,broadcastid,streamid);
              },
              function(err) { console.error("Execute error", err); });
  }
  function bindStream() {
      return gapi.client.youtube.liveBroadcasts.bind({
          "id":broadcastid,
          "part": "snippet",
          "streamId": streamid
      })
          .then(function(response) {
                  // Handle the results here (response.result has the parsed body).
                  console.log("Response", response);
                  showStream();
                  streamStatus();
                  
              },
              function(err) { console.error("Execute error", err); });
  }
  function streamStatus() {
      return gapi.client.youtube.liveStreams.list({
          "part": "snippet,cdn,contentDetails,status",
          "id": streamid
      })
          .then(function(response) {
                  // Handle the results here (response.result has the parsed body).
                  console.log("Stream status Response", response);
                  var key=response.result.items[0].cdn.ingestionInfo.streamName;
                  document.getElementById("streamkey").value=key;
                  var status=response.result.items[0].status.streamStatus;
                  console.log(status);
                  if(status=="active"){
                      document.getElementById("checkStatus").style.display='none';
                       document.getElementById("goLive").style.display='block';
                        document.getElementById("endStream").style.display='none';
                         updateBroadcast();
                        
                  }
                    if(status=="ready" || status=="inactive"){
                      document.getElementById("checkStatus").style.display='block';
                       document.getElementById("goLive").style.display='none';
                        document.getElementById("endStream").style.display='none';
                        updateDbStream(channelid,1,streamid,"");
                     
                        setTimeout(function(){
                            streamStatus();
                            console.log(timeout);
                        },3000)
                        
                       
                  }
              },
              function(err) { console.error("Execute error", err); });
  }
  function getBoradcastByID() {
      return gapi.client.youtube.liveBroadcasts.list({
          "part": "snippet,contentDetails,status",
          "id": broadcastid
      })
          .then(function(response) {
                  // Handle the results here (response.result has the parsed body).
                  console.log("get Broadcast By id Response", response);
                  var iframe=response.result.items[0].contentDetails.monitorStream.embedHtml;
                  document.getElementById("videoPlayer").innerHTML=iframe;
                  var video_id=response.result.items[0].id;
                  var src="https://studio.youtube.com/live_chat?is_popout=1&v="+video_id;
                 
                   document.getElementById("popupChat").setAttribute("url",src);
                    updateDbStream(channelid,2,streamid,video_id);
              },
              function(err) { console.error("Execute error", err); });
  }
  function transition(status) {
       if(status=="live"){
            getBoradcastByID();
             updateBroadcast();
             document.getElementById("checkStatus").style.display='none';
                       document.getElementById("goLive").style.display='block';
                        document.getElementById("goLive").innerHTML='LIVE';
                        document.getElementById("endStream").style.display='block';
       }
      return gapi.client.youtube.liveBroadcasts.transition({
          "broadcastStatus": status,
          "id": broadcastid,
          "part": "snippet,status"
      })
          .then(function(response) {
                  // Handle the results here (response.result has the parsed body).
                  console.log("Response", response);
                  if(status=="live"){
                       document.getElementById("checkStatus").style.display='none';
                       document.getElementById("goLive").style.display='block';
                        document.getElementById("goLive").innerHTML='LIVE';
                        document.getElementById("endStream").style.display='block';
                        getBoradcastByID();
                          
                  }
                  if(status=="complete"){
                       updateDbStream(channelid,3,streamid,"");
                        document.getElementById("checkStatus").style.display='none';
                       document.getElementById("goLive").style.display='none';
                        document.getElementById("goLive").innerHTML='LIVE';
                        document.getElementById("endStream").style.display='block';
                        document.getElementById("endStream").innerHTML='ENDED';
                    
                  }
                  
        
              },
              function(err) { console.error("Execute error", err); });
  } 
  function popupChatWindow(url)
  {
      if(url){
            window.open(url,"MyWindow","toolbar=no, menubar=no,scrollbars=no,resizable=no,location=no,directories=no,status=no,width=300,height=600,top=30,left="+(screen.width-20));
      }else{
          alert("not ready")
      }
      console.log(url);
  
  }
  
</script>

  </head>
  <body style="background-color:white;">

    <div class="container-fluid">
        <div class="row">
            <?php include("sidebar.php"); ?>

                    <!-- The Modal -->
                      <div class="modal fade" id="myModal" tabindex='-1' data-keyboard='false' data-backdrop='static'>
                        <div class="modal-dialog modal-sm modal-dialog-centered">
                          <div class="modal-content">
                            
                            <!-- Modal body -->
                            <div class="modal-body" style="width:400;height:200px;">
                                    
                                    <button class="btn btn-primary" onclick="authenticate().then(loadClient)" >Authenticate</button>
                                     
                            </div>
                            
                          </div>
                        </div>
                      </div>



            <div class="col-md-10" style="background:#f6f6f6;position:;margin-left:;height:800px;float:right;">

                <div class="row">
                    
                    <div class="col-md-12 text-white" id="streamdiv" style="display:none;">
                         <div class="col-md-12" style="display:inline-block;position:relative;background:orange;"> 
                            <h4 style="color:white;font-weight:bold;font-size:20px;text-align:center;">LIVE CLASS</h4>
                         </div>
                        <div class="col-md-8" style="background:green;display:inline-block;position:relative;"><br>
                            
                            <div class="col-md-8" id="videoPlayer" style="display:inline-block;position:relative;">
                                <video width="400" height="240" controls>
                                  <source src="" type="video/mp4">
                                  
                                </video>
                            </div>
                            <div class="col-md-3" style="display:inline-block;position:absolute;">
                                <p>Title</p>
                                <p id="videotitle"></p><br>
                                <p>Category</p>
                                <p id="">Education</p>
                            </div>
                            <hr style="border:solid 3px;color:black;">
                            <div class="col-md-12"><br>
                                <p>Stream Key</p>
                                <input type="text" id="streamkey" value="" style="width:400px;border:none;background:transparent;border-bottom:solid 2px white;color:white;" />
                                
                            </div>
                            <br><br>
                        </div>
                        
                        <div class="col-md-3 text-white" style="display:inline-block;margin-top:0px;position:absolute;margin-left:10px;height:100%;background:green;">

                          <button  id="checkStatus" class="btn btn-warning" style="float:right;width:200px;">CHECKING STATUS</button><br>
                          <button onclick="popupChatWindow(getAttribute('url'))" id="popupChat" url="" class="btn btn-info" style="float:right;width:200px;">POPUP CHAT</button><br>
                          <button onclick="transition('live')" id="goLive" class="btn btn-info" style="float:right;display:none">GO LIVE</button><br>
                        <button onclick="transition('complete')" id="endStream" class="btn btn-danger" style="color:white;float:right;display:none">END STREAM</button>
                            
                        </div>
                        
                    </div>
                    
                    <div class="col-md-6 offset-3 bg-dark mt-5 pb-4"  style="display:none;" id="firstdiv">
                        <h4 class="text-white" style="background:#333;margin:0px -15px;padding:8px;text-align:center;">New stream with last used settings</h4>
                        <h6 class="text-white mt-4" style="padding:5px;font-family:arial;">You can create a new live stream by copying stream settings, privacy, and details (title, category, etc.) from a previously completed stream.</h6><br>

                        <select class="form-control" id="broadlist" style="border:none;border-bottom:solid 2px white;background:transparent;color:white;">
                             
                            </select><br>

                        <button onclick="showreusediv()" class="btn btn-info" style="float:right;">REUSE SETTINGS</button>
                        <button onclick="showdiv()" class="btn btn-link" style="color:white;float:right;">DISMISS</button>

                    </div>
                    
                        <div class="col-md-6 offset-3 mt-5 pb-4" id="formdiv" style="background:green;">

                            <h4 class="text-white" style="background:orange;margin:0px -15px;padding:8px;text-align:center;">New stream</h4><br>

                            <input type="text" id="title" placeholder="Create a title" class="form-control" style="border:none;border-bottom:solid 2px white;background:;color:;"/><br>

                            <input type="text" id="description" placeholder="Add a description" class="form-control" style="border:none;border-bottom:solid 2px white;background:;color:;"/><br>

                            <select class="form-control" style="border:none;border-bottom:solid 2px white;background:transparent;color:;">
                              <option value="">Private</option>
                            </select><br>

                            <select class="form-control" style="border:none;border-bottom:solid 2px white;background:transparent;color:white;">
                              <option value="">Education</option>
                            </select><br>

                            <p class="text-white"><i class="fa fa-calendar"></i> Schedule for later 
                                <label class="switch">
                                  <input type="checkbox" onclick="showtimer($(this))" id="arun">
                                  <span class="slider round"></span>
                                </label>
                            </p>
                            
                            <div id="schedulediv" style="display:none;color:white;">
                                <span style="display:inline-block;">
                                    Date<br><input id="schDate" type="date">
                                </span>
                                <span style="display:inline-block;">
                                    Time<br><input id="schTime" type="time">
                                </span>
                                <br>
                            </div>
                            
                            <!--<p style="color:white;"><input type="radio" checked/> No, it's not made for kids</p>-->
                            
                            <input  onclick="createNewBroadCast(0)" type="submit" value="CREATE STREAM" class="btn btn-info" style="float:right;">
                            <!--<button onclick="goback()" class="btn btn-link" style="color:white;float:right;">BACK</button>-->

                        </div>
                        
                            <div class="col-md-6 offset-3 bg-dark mt-5 pb-4" id="reusediv" style="display:none;">

                            <h4 class="text-white" style="background:#333;margin:0px -15px;padding:8px;text-align:center;">New stream</h4><br>


                            <input type="text" id="retitle" placeholder="Create a title" class="form-control" style="border:none;border-bottom:solid 2px white;background:transparent;color:white;"/><br>

                            <input type="text" id="redescription" placeholder="Add a description" class="form-control" style="border:none;border-bottom:solid 2px white;background:transparent;color:white;"/><br>

                            <select class="form-control" style="border:none;border-bottom:solid 2px white;background:transparent;color:white;">
                              <option value="">Private</option>
                            </select><br>

                            <select class="form-control" style="border:none;border-bottom:solid 2px white;background:transparent;color:white;">
                              <option value="">Education</option>
                            </select><br>


                            <div id="schedulediv" style="color:white;">
                                <span style="display:inline-block;">
                                    Date<br><input id="reschDate" type="date">
                                </span>
                                <span style="display:inline-block;">
                                    Time<br><input id="reschTime" type="time">
                                </span>
                                <br>
                            </div>
                             
                            <p style="color:white;"><input type="radio" checked/> No, it's not made for kids</p>
                            
                            <input type="submit" onclick="createNewBroadCast(1)"  value="CREATE STREAM" class="btn btn-info" style="float:right;">
                            <button onclick="goback()" class="btn btn-link" style="color:white;float:right;">BACK</button>

                        </div>
                    
                </div>


                
            </div>            
            
        </div>
    </div>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script type="text/javascript">
    function addStream(channelid,name,detail,broadcastid,streamid){
	var data="type=addStream";
	$.post( "ajax.php?"+data, { channel_id: channelid,name:name,detail:detail,photo:"",status:0,broadcastid:broadcastid,streamid:streamid} , function( res ) {
		//alert(data);
	  	if(res==1){
		  alert("saved");
		}else{
			alert(res);
		
		}
	});
	return false;
}  
function updateDbStream(channelid,status,streamid,video_id){
	var data="type=updateStream";
	$.post( "ajax.php?"+data, { channel_id: channelid,status:status,streamid:streamid,video_id:video_id} , function( res ) {
		//alert(data);
		    //window.location.href="previousvideo.php"
	  	if(res==1){
		   
		}else{
// 			alert(res);
		
		}
	});
	return false;
}  


    function showdiv(){
     document.getElementById('firstdiv').style.display='none';
     document.getElementById('formdiv').style.display='block';   
    }
    function showreusediv(){
     document.getElementById('firstdiv').style.display='none';
     document.getElementById('reusediv').style.display='block'; 
     broadcastid=$("#broadlist").children("option:selected").val();
     var title=$("#broadlist").children("option:selected").attr('title');
     var desc=$("#broadlist").children("option:selected").attr('desc');
     var time=$("#broadlist").children("option:selected").attr('time');
     time=new Date(time);
     if(time.getMonth()<10){
         var month="0"+time.getMonth();
     }else{
          var month=time.getMonth();
     }
      if(time.getDate()<10){
         var date="0"+time.getDate();
     }else{
          var date=time.getDate();
     }
       if(time.getHours()<10){
         var hours="0"+time.getHours();
     }else{
          var hours=time.getHours();
     }
       if(time.getMinutes()<10){
         var min="0"+time.getMinutes();
     }else{
          var min=time.getMinutes();
     }
     var d=time.getFullYear()+"-"+month+"-"+date;
     var t=hours+":"+min;
     $("#retitle").val(title);
     $("#redescription").val(desc);
     $("#reschDate").val(d);
     $("#reschTime").val(t);
     console.log(d)
    }
    function goback(){
     document.getElementById('firstdiv').style.display='block';
     document.getElementById('formdiv').style.display='none';
     document.getElementById('reusediv').style.display='none';
    }

    function showStream(){
        var title = document.getElementById('title').value;
        var description = document.getElementById('description').value;
        // if(title == ""){
        //     alert('Please enter title');
        // }
        // else if(description == ""){
        //     alert('Please enter Description');
        // }
        // else {
         document.getElementById('videotitle').innerHTML = title;
         document.getElementById('firstdiv').style.display = 'none';
         document.getElementById('formdiv').style.display  = 'none';
         document.getElementById('reusediv').style.display = 'none';
         document.getElementById('streamdiv').style.display = 'block';
        //}
    }

    function showtimer(t){
        if (t.is(':checked')) {
            document.getElementById('schedulediv').style.display = 'block';
        } else {
            document.getElementById('schedulediv').style.display = 'none';
        }
    }

</script>

<script type="text/javascript">
      $(window).on('load',function(){

        $('#myModal').modal('show');
    });

$(document).ready(function() {
     gapi.load("client:auth2", function() {
      gapi.auth2.init({client_id: "28874148227-86p31hrfgvvafkignpkpal5tkkgpog3d.apps.googleusercontent.com"})
  });

});

</script>

  </body>
</html>