@extends('crm.layouts.app')

@section('title')
    Support Dashboard
@endsection

@section('content')
<div class="content-wrapper">
    <div class="content">
        <div class="container-fluid">
          <div class="row">
              <div class="col-md-6">
                <form action="{{url('/support/ticket')}}" method="POST">
                    @csrf
                    <div class="form-group">
                        <label for="name">Name</label>
                        <input class="form-control" name="name" type="text" id="name">
                    </div>
                    <div class="form-group">
                        <label for="phone_number">Phone number</label>
                        <input class="form-control" name="phone_number" type="text" id="phone_number">
                    </div>
                    <div class="form-group">
                        <label for="description">Description</label>
                        <textarea class="form-control" name="description" cols="50" rows="10" id="description"></textarea>
                    </div>
                    <div class="form-group">
                      <button type="submit" class="btn btn-primary btn-lg btn-block">Submit ticket</button>
                    </div>
                </form>
              </div>
              <div class="col-md-6">
                  <div class="card">
                    <h5 class="card-header"> Make a call </h5>
                    <div class="card-body">
                      <div class="form-group row">
                        <label for="call-status" class="col-3 col-form-label">Status</label>
                        <div class="col-9">
                          <input id="call-status" class="form-control" type="text" placeholder="Connecting to Twilio..." readonly>
                        </div>
                      </div>
                      <button class="btn btn-lg btn-success answer-button" disabled>Answer call</button>
                      <button class="btn btn-lg btn-danger hangup-button" disabled onclick="hangUp()">Hang up</button>
                    </div>
                  </div>
              </div>
          </div>
            <div class="row">
              <div class="col">
                <h2>Support Tickets</h2>
            
                <p class="lead">
                  This is the list of most recent support tickets. Click the "Call customer" button to start a phone call from your browser.
                </p>
              </div>
            </div>
        
        
            <div class="row">
        

        
              <div class="col-md-7 order-md-1">
                @foreach ($tickets as $ticket)
                  <div class="card border-default">
                    <h5 class="card-header">
                      Ticket #{{ $ticket->id }}
                      <small class="float-right">{{ $ticket->created_at }}</small>
                    </h5>
        
                    <div class="card-body">
                      <div class="row">
                        <div class="col">
                          <p><strong>Name:</strong> {{ $ticket->name }}</p>
                          <p><strong>Phone number:</strong> {{ $ticket->phone_number }}</p>
                          <p><strong>Description:</strong></p>
                          {{ $ticket->description }}
                        </div>
        
                        <div class="col col-auto">
                          <button onclick="callCustomer('{{ $ticket->phone_number }}')" type="button" class="btn btn-primary btn-lg call-customer-button">
                            Call customer
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                @endforeach
              </div>
        
            </div>
          </div>        
    </div>
</div>
@endsection

@section('scripts')

<script>

const Device = Twilio.Device;
/**
 * Twilio Client configuration for the browser-calls-laravel
 * example application.
 */

// Store some selectors for elements we'll reuse
var callStatus = $("#call-status");
var answerButton = $(".answer-button");
var callSupportButton = $(".call-support-button");
var hangUpButton = $(".hangup-button");
var callCustomerButtons = $(".call-customer-button");

var device = null;

/* Helper function to update the call status bar */
function updateCallStatus(status) {
    callStatus.attr('placeholder', status);
}

/* Get a Twilio Client token with an AJAX request */
$(document).ready(function() {
    setupClient();
});

function setupHandlers(device) {
    device.on('ready', function (_device) {
        updateCallStatus("Ready");
    });

    /* Report any errors to the call status display */
    device.on('error', function (error) {
        updateCallStatus("ERROR: " + error.message);
    });

    /* Callback for when Twilio Client initiates a new connection */
    device.on('connect', function (connection) {
        // Enable the hang up button and disable the call buttons
        hangUpButton.prop("disabled", false);
        callCustomerButtons.prop("disabled", true);
        callSupportButton.prop("disabled", true);
        answerButton.prop("disabled", true);

        // If phoneNumber is part of the connection, this is a call from a
        // support agent to a customer's phone
        if ("phoneNumber" in connection.message) {
            updateCallStatus("In call with " + connection.message.phoneNumber);
        } else {
            // This is a call from a website user to a support agent
            updateCallStatus("In call with support");
        }
    });

    /* Callback for when a call ends */
    device.on('disconnect', function(connection) {
        // Disable the hangup button and enable the call buttons
        hangUpButton.prop("disabled", true);
        callCustomerButtons.prop("disabled", false);
        callSupportButton.prop("disabled", false);

        updateCallStatus("Ready");
    });

    /* Callback for when Twilio Client receives a new incoming call */
    device.on('incoming', function(connection) {
        updateCallStatus("Incoming support call");

        // Set a callback to be executed when the connection is accepted
        connection.accept(function() {
            updateCallStatus("In call with customer");
        });

        // Set a callback on the answer button and enable it
        answerButton.click(function() {
            connection.accept();
        });
        answerButton.prop("disabled", false);
    });
};

function setupClient() {
    // +++++++++++++++++++++++++++++++
    url="{{url('support/token')}}";
    $.ajaxSetup({
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
      }
    });
    $.ajax({
      url: url,
      type: 'POST',
      dataType: 'JSON',
      success: function (data) { 
        device = new Device();
        device.setup(data.token);
        setupHandlers(device);
      }
    });    


};

/* Call a customer from a support ticket */
window.callCustomer = function(phoneNumber) {
    updateCallStatus("Calling " + phoneNumber + "...");
    
    var params = {"phoneNumber": phoneNumber};
    device.connect(params);
};

/* Call the support_agent from the home page */
window.callSupport = function() {
    updateCallStatus("Calling support...");

    // Our backend will assume that no params means a call to support_agent
    device.connect();
};

/* End a call */
window.hangUp = function() {
    device.disconnectAll();
};


</script>
@endsection