<?php

namespace App\Http\Controllers;

use Session;
use App\Helper\Helper;
use Illuminate\Http\Request;
use GuzzleHttp\Exception\RequestException;
use App\Http\Controllers\InheritApiController;
use GuzzleHttp\Exception\BadResponseException;
use Illuminate\Support\MessageBag;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Facades\Log;

class ApiLabelController extends Controller
{
  function getLabel(Request $request)
  {
    $inherit_label = new InheritApiController;
    $label_list =  $inherit_label->getLabel();

    if (!is_array($label_list)) {
      $label_list = array();
    }



    if (empty($label_list)) {
      if (empty(Session::get('tokenId'))) {
        return redirect('/');
      }
    }
    if ($request->ajax()) {
      // log::info("run coustom ajax");
      return DataTables::of($label_list)
        ->addIndexColumn()
        ->addColumn('status', function ($row) {
          $activeClass = $row->status == '1' ? 'active' : '';
          return '
            <button type="button" data-listid="' . $row->id . '"
                class="btn btn-sm btn-toggle ' . $activeClass . '"
                data-bs-toggle="button" aria-pressed="true" autocomplete="off">
                <div class="handle"></div>
            </button>';
        })
        ->addColumn('action', function ($row) {
          return '<a style="cursor:pointer;margin-right:5px;"title="Edit"
                                                                            class="editLabel"
                                                                            data-id="' . $row->id . '"><i
                                                                                class="fa fa-edit fa-lg"></i></a>
                                                                        <a style="cursor:pointer;" title="Delete"
                                                                            class="openLabelDelete" data-id="' . $row->id . '"><i
                                                                                class="fa fa-trash-o fa-lg"></i></a>';
        })

        ->rawColumns(['status', 'action'])
        ->make(true);
    }
    return view('configuration.label', compact('label_list'));
  }

  function storeLabel(Request $request)
  {



    if (!empty($request->label_id)) {
      $body = array(
        'id' => Session::get('id'),
        'token' => Session::get('tokenId'),
        'label_id' => $request->label_id,
        'title' => $request->title
      );

      //echo "<pre>";print_r($body);die;

      $url = env('API_URL') . 'edit-label';
      // echo "<pre>";print_r($body);die;
      try {
        $ext_group = Helper::PostApi($url, $body);
        //echo "<pre>";print_r($ext_group);die;
        if ($ext_group->success == 'true') {
          // echo "<pre>";print_r($group);die;
          //return back()->withSuccess($result->message);
          return back()->withSuccess($ext_group->message);
        }

        if ($ext_group->success == 'false') {
          return redirect('/');
          //return back()->withSuccess($ext_group->message);
        }
      } catch (BadResponseException   $e) {
        return back()->with('message', "Error code - (edit-label): Oops something went wrong :( Please contact your administrator.)");
      } catch (RequestException $ex) {
        return back()->with('message', "Error code - (edit-label): Oops something went wrong :( Please contact your administrator.)");
      }
    } else {
      $body = array(
        'id' => Session::get('id'),
        'token' => Session::get('tokenId'),
        'title' => $request->title
      );

      // echo "<pre>";print_r($body);die;

      $url = env('API_URL') . 'add-label';
      // echo "<pre>";print_r($body);die;

      try {
        $add_label = Helper::PostApi($url, $body);
        //echo "<pre>";print_r($ext_group);die;
        if ($add_label->success == 'true') {
          // echo "<pre>";print_r($group);die;
          //return back()->withSuccess($result->message);
          return back()->withSuccess($add_label->message);
        }

        if ($add_label->success == 'false') {
          return redirect('/');
          //return back()->withSuccess($ext_group->message);
        }
      } catch (BadResponseException   $e) {
        return back()->with('message', "Error code - (add-label): Oops something went wrong :( Please contact your administrator.)");
      } catch (RequestException $ex) {
        return back()->with('message', "Error code - (add-label): Oops something went wrong :( Please contact your administrator.)");
      }
    }
  }

  function editLabel($label_id)
  {

    $body = array(
      'id' => Session::get('id'),
      'token' => Session::get('tokenId'),
      'label_id' => $label_id,

    );

    // echo "<pre>";print_r($body);die;

    $url = env('API_URL') . 'label';
    // echo "<pre>";print_r($body);die;

    $ext_group = Helper::PostApi($url, $body);
    //echo "<pre>";print_r($ext_group);die;

    try {
      $ext_group = Helper::PostApi($url, $body);
      /* echo "<pre>";print_r($ext_group);die;*/
      if ($ext_group->success == 'true') {

        $group = $ext_group->data;

        return $group;
      }

      if ($ext_group->success == 'false') {
        return back()->withSuccess($ext_group->message);
      }
    } catch (BadResponseException   $e) {
      return back()->with('message', "Error code - (label): Oops something went wrong :( Please contact your administrator.)");
    } catch (RequestException $ex) {
      return back()->with('message', "Error code - (label): Oops something went wrong :( Please contact your administrator.)");
    }
  }


  function deleteLabel($label_id)
  {
    $body = array(
      'id' => Session::get('id'),
      'token' => Session::get('tokenId'),
      'label_id' => $label_id,
      'is_deleted' => 1

    );
    //echo "<pre>";print_r($body);

    $url = env('API_URL') . 'edit-label';
    //echo "<pre>";print_r($body);die;

    /*  $delete_dnc = Helper::PostApi($url,$body);
              echo "<pre>";print_r($delete_dnc);die;*/

    try {
      $delete_dnc = Helper::PostApi($url, $body);
      //echo "<pre>";print_r($ext_group);die;
      if ($delete_dnc->success == 'true') {
        // echo "<pre>";print_r($group);die;
        //return back()->withSuccess($result->message);
        return back()->withSuccess($delete_dnc->message);
      }

      if ($delete_dnc->success == 'false') {
        return back()->withSuccess($delete_dnc->message);
        //return back()->withSuccess($ext_group->message);
      }
    } catch (BadResponseException   $e) {
      return back()->with('message', "Error code - (edit-label): Oops something went wrong :( Please contact your administrator.)");
    } catch (RequestException $ex) {
      return back()->with('message', "Error code - (edit-label): Oops something went wrong :( Please contact your administrator.)");
    }
  }



  function getLiveExtension(Request $request)
  {
    $inherit_label = new InheritApiController;
    $label_list =  $inherit_label->getLiveExtension();
    if (!is_array($label_list)) {
      $label_list = array();
    }

    if (empty($label_list)) {
      if (empty(Session::get('tokenId'))) {
        return redirect('/');
      }
    }
    // if ($request->ajax()) {
    //   Log::info("Returning campaign list via AJAX:", $label_list); // Debug
    //   return DataTables::of(collect($label_list)) // Convert array to collection
    //     ->addIndexColumn()
    //     ->make(true);
    // }

    if ($request->ajax()) {
      return DataTables::of($label_list)
        ->addIndexColumn()
        ->addColumn('status', function ($row) {
          if ($row->status == '0') return '<span class="badge badge-success">Ready For Calls</span>';
          if ($row->status == '1') return '<span class="badge badge-success">In Call</span>';
          if ($row->status == '2') return '<span class="badge badge-success">Hangup</span>';
          return '<span class="badge badge-warning">Pause</span>';
        })
        ->addColumn('action', function ($row) {
          return '<a href="#" class="openLabelDelete" data-id="' . $row->extension . '">
                        <i class="fa fa-refresh" title="Reset Extension"></i>
                    </a>';
        })
        ->rawColumns(['status', 'action'])
        ->make(true);
    }
    return view('configuration.extlive', compact('label_list'));
  }

  function getLiveExtension_old()
  {
    $inherit_label = new InheritApiController;
    $label_list =  $inherit_label->getLiveExtension();
    if (!is_array($label_list)) {
      $label_list = array();
    }

    if (empty($label_list)) {
      if (empty(Session::get('tokenId'))) {
        return redirect('/');
      }
    }
    return view('configuration.extlive', compact('label_list'));
  }
  public function deleteExtLiv($id)
  {

    $body = array(
      'id' => Session::get('id'),
      'token' => Session::get('tokenId'),
      'sip' => $id
    );
    $url = env('API_URL') . 'delete-ext-live';

    try {
      $delete_dnc = Helper::PostApi($url, $body);
      if ($delete_dnc->success == 'true') {
        return back()->withSuccess($delete_dnc->message);
      }
      if ($delete_dnc->success == 'false') {
        return redirect('/');
      }
    } catch (BadResponseException   $e) {
      return back()->with('message', "Error code - (delete-extension): Oops something went wrong :( Please contact your administrator.)");
    } catch (RequestException $ex) {
      return back()->with('message', "Error code - (delete-extension): Oops something went wrong :( Please contact your administrator.)");
    }
  }

  public function updateDisplayOrder(Request $request)
  {

    //dd(array_filter($this->getBuildBody($request)));

    $intLabelId = $request->label_id;
    $errors = new MessageBag();
    try {
      $url = env('API_URL') . "/label/updateDisplayOrder";
      $response = Helper::PostApi($url, array_filter($this->getBuildBody($request)));

      echo "<pre>";
      print_r($response);
      die;
      if (!$response->success) {
        foreach ($response->errors as $key => $message) {
          if (is_array($message)) {
            foreach ($message as $index => $strInsideMessage)
              $errors->add($index, $strInsideMessage);
          } else {
            $errors->add($key, $message);
          }
        }
        return redirect()->back()->withInput($request->input())->withErrors($errors);
      } else {
        /* echo $response->data->lead_status;
              echo $response->data->old_lead_status;die;*/

        $leadId = $response->data->id;
        if ($response->data->lead_status != $response->data->old_lead_status)
          $notifications = array('lead_id' => $leadId, 'message' => 'updated lead status from <b>' . strtoupper(str_replace('_', ' ', $response->data->old_lead_status)) . '</b> to <b>' . strtoupper(str_replace('_', ' ', $response->data->lead_status)) . '</b>.');
        else
          $notifications = array('lead_id' => $leadId, 'message' => 'updated <b>lead</b> information.');
        $result = (new NotificationController)->add($notifications);
      }
    } catch (RequestException $ex) {
      $errors->add("error", $ex->getMessage());
      return redirect()->back()->withInput($request->input())->withErrors($errors);
    }
    session()->flash("success", "Lead updated");
    return redirect()->back();
  }

  private function getBuildBody(Request $request)
  {

    $body = [
      "title" => trim(ucwords($request->get("title"))),
      "display_order" => $request->get("display_order"),

    ];
    return $body;
  }
  public function updateLabelStatus($id = "", $status = "")
  {
    $body = array(
      'id' => Session::get('id'),
      'token' => Session::get('tokenId'),
      'listId' => $id,
      'status' => $status,
    );

    $url = env('API_URL') . 'status-update-label';
    try {
      $list = Helper::PostApi($url, $body);
      //echo"<pre>";print_r($list);die;

      if ($list->success == 'true') {
        //return redirect('/list')->withSuccess($delete_list->message);
        echo json_encode(array('status' => "true", 'message' => $list->message));
      }
      if ($list->success == 'false') {
        //return redirect('/list')->withSuccess($delete_list->message);
        echo json_encode(array('status' => "false", 'message' => $list->message));
      }
    } catch (BadResponseException $e) {
      return back()->with('message', "Error code - (edit-list): Oops something went wrong :( Please contact your administrator.)");
    }
  }
}
