<?php

namespace App\Http\Controllers;

use Session;
use Pusher\Pusher;

use App\Helper\Helper;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;


class ApiDashboardController extends Controller
{
    function dashboardNew(){
        return view('dashboard.dashboard-new');
    }
    function dashboardNewCrm(){
        return view('dashboard.dashboard-crm');
    }
    function index(Request $request)
    {

        $inherit_list = new InheritApiController;
        $url = env('API_URL').'extension';
        $body=array(
            'id' => Session::get('id'),
            'token' => Session::get('tokenId'),
            'parent_id' => Session::get('parent_id'),
            'role' => 2
        );

        $campaign_list =  $inherit_list->getCampaign();
        if(!is_array($campaign_list)){
            $campaign_list =array();
        }
        $arrCampaignListRekeyed = ClientPackageController::rekeyArray($campaign_list,'id');


        $extension_list =  $inherit_list->getExtensionList();
        if(!is_array($extension_list)){
            $extension_list =array();
        }
        $arrExtensionListRekeyed = ClientPackageController::rekeyArray($extension_list,'extension');
        $arrExtensionListRekeyedByAltExtension = ClientPackageController::rekeyArray($extension_list,'alt_extension');
       

       /* $callbackStatus = $this->getReminderStatus();
        if($callbackStatus == null){
            $callbackStatus = new stdClass();
            $callbackStatus->callback_reminder = null;
        }*/

        $callback = array();
        //$callbackCount=array();
        $callbackCount=0;


      if ($request->isMethod('GET'))
        {
            $lower_limit = 0;
            $url = env('API_URL').'callback';
             $body=array(
                'id' => Session::get('id'),
                'token' => Session::get('tokenId'),
                'campaign_id' => $request->campaign,
                'extension'   =>$request->extension,
                'start_date' =>  date('Y-m-d', strtotime("-1 year", time())),
                'end_date'  =>  date('Y-m-d', strtotime("+1 year", time()))
            );
                //echo "<pre>";print_r($body);die;

             $callback_data = Helper::PostApi($url,$body);

            if($callback_data->success == 'true'){
                $callback = $callback_data->data;
                $callbackCount = count($callback);
                //echo "<pre>";print_r($callbackCount);die;

            }
        }


        $availablePackages = [];

		//error_reporting(0);
        if (empty(Session::get('tokenId'))) {
            return redirect('/');
        }

        $errors = new MessageBag();
        $map = [];
        $url = env('API_URL') . "extension-group-map";
        try
        {
            $response = Helper::GetApi($url);
            if ($response->success)
            {
                $map = $response->data;
            }
            else
            {
                foreach ( $response->errors as $key => $message )
                {
                    $errors->add($key, $message);
                }
            }
        }
        catch (RequestException $ex)
        {
            $errors->add("error", $ex->getMessage());
            return view("dashboard.dashboard", compact("errors", $errors));
        }

        $group = [];
        $url = env('API_URL') . "extension-group";
        try
        {
            $response = Helper::GetApi($url);
            if ($response->success)
            {
                $group = $response->data;
            }
            else
            {
                foreach ( $response->errors as $key => $message )
                {
                    $errors->add($key, $message);
                }
            }
        }
        catch (RequestException $ex)
        {
            $errors->add("error", $ex->getMessage());
            return view("dashboard.dashboard", compact("errors", $errors));
        }


        $errors = new MessageBag();
        $lists = [];
        $url = env('API_URL') . "count-lists";
        try
        {
            $response = Helper::GetApi($url);
            //echo "<pre>";print_r($response);die;
            if ($response->success)
            {
                $lists = $response->data[0];
            }
            else
            {
                foreach ( $response->errors as $key => $message )
                {
                    $errors->add($key, $message);
                }
            }
        }
        catch (RequestException $ex)
        {
            $errors->add("error", $ex->getMessage());
            return view("dashboard.dashboard", compact("errors", $errors));
        }

        $dids = [];
        $url = env('API_URL') . "count-dids";
        try
        {
            $response = Helper::GetApi($url);
            //echo "<pre>";print_r($response);die;
            if ($response->success)
            {
                $dids = $response->data[0];
            }
            else
            {
                foreach ( $response->errors as $key => $message )
                {
                    $errors->add($key, $message);
                }
            }
        }
        catch (RequestException $ex)
        {
            $errors->add("error", $ex->getMessage());
            return view("dashboard.dashboard", compact("errors", $errors));
        }



        $inherit_list = new InheritApiController;
        $didCount = $dids; //$inherit_list->getDidListCount();
        $userCount = $inherit_list->getUserCount();
        $campaignCount = $inherit_list->getCampaignsCount();
        $leadCount = $inherit_list->getLeadCount();
        $extensionList = $inherit_list->fetchEmployeeDirectory();
        $extension_list = $inherit_list->getExtensionList();
        //$list=$inherit_list->getListList();
        $listCount = $lists; //count($list);
        // $callbackCount=$inherit_list->getCallBackList();
        // dd($callbackCount);
        $liveCalls = $inherit_list->liveCalls();
        //$getSmsList = $inherit_list->getSmsList();

		$getSmsList = $inherit_list->getSmsListNew();
        if (empty($getSmsList)) {
            $getSmsList = array();
        } else {
            // Convert the object to an array
            $getSmsList = json_decode(json_encode($getSmsList), true);
        
            // Sort the array by date in descending order
            usort($getSmsList, function ($a, $b) {
                return strtotime($b['date']) - strtotime($a['date']);
            });
        
            // Get the first 10 records
            $getSmsList = array_slice($getSmsList, 0, 10);
        }
//return $getSmsList;
        $campaign_list = [];
        $errors = new MessageBag();
        $url = env('API_URL') . "campaigns";
        try {
            $response = Helper::GetApi($url);
            if ($response->success) {
                $campaign_list = $response->data;
            } else {
                foreach ( $response->errors as $key => $message ) {
                    $errors->add($key, $message);
                }
            }
        } catch (RequestException $ex) {
            $errors->add("error", $ex->getMessage());
            return view("dashboard.dashboard", compact("errors", $errors));
        }

        /*$campaign_list = $inherit_list->getCampaign();
        if (!is_array($campaign_list))
        {
            $campaign_list = array();
        }*/
        

        $getVoicemailUnreadCount = $inherit_list->getVoicemailUnreadCount();


        $body = array(
            'id' => Session::get('id'),
            'token' => Session::get('tokenId')
        );
        $urlSms = env('API_URL') . 'unread-sms-count';
        $smsCountResponse = Helper::PostApi($urlSms, $body);
        if(!isset($smsCountResponse->data->countRow)){
            $smsUnreadCount = 0 ;
        }else{
            $smsUnreadCount = $smsCountResponse->data->countRow > 0 ?  $smsCountResponse->data->countRow : '' ;
        }

        $urlClientPackages = env('API_URL') . "client-packages";
        $response = Helper::GetApi($urlClientPackages);
        if ($response->success) {
            $availablePackages = (array) $response->data;
        }

        // $options = array(
        //     'cluster' => env('PUSHER_APP_CLUSTER'),
        //     'encrypted' => true
        // );


        // $pusher = new Pusher(
        //     env('PUSHER_APP_KEY'),
        //     env('PUSHER_APP_SECRET'),
        //     env('PUSHER_APP_ID'), $options
        // );

        // $message= $smsUnreadCount;
        // $message= 5;

        // //Send a message to notify channel with an event name of notify-event
        // $pusher->trigger('notification', 'notification-event', $message);

        // $file_path = sys_get_temp_dir().'/a.pdf';
        // $image = file_get_contents("https://www.tutorialspoint.com/php/php_tutorial.pdf");
        // file_put_contents($file_path, $image);
        // exit;
       $dashboard = [];
        $errors = new MessageBag();
        $url = env('API_URL') . "dashboard";
            $body=array(
                'id' => Session::get('id'),
                'token' => Session::get('tokenId'),
                'campaign_id' => $request->campaign,
                'extension'   =>$request->extension,
                'start_date' =>  date('Y-m-d', strtotime("-1 year", time())),
                'end_date'  =>  date('Y-m-d', strtotime("+1 year", time())),
                'startTime' => $request->startTime,
            'endTime' => $request->endTime,
            'userId'=>$request->userId
            );
        try {
            $response = Helper::PostApi($url,$body);
            //echo "<pre>";print_r($response);die;

            if ($response->success && isset($response->data)) {
        $dashboard = $response->data;
    } else {
        foreach ($response->errors ?? [] as $key => $message) {
            $errors->add($key, $message);
        }}
        } catch (RequestException $ex) {
            $errors->add("error", $ex->getMessage());
            return view("dashboard.dashboard", compact("errors", $errors));
        }
        if ($request->ajax()) {
    return response()->json([
          'didCount' => $dashboard->totalDids ?? 0,
            'userCount' => $dashboard->totalUsers ?? 0,
            'campaignCount' =>  $dashboard->totalCampaigns ?? 0,
            'leadCount' => $dashboard->totalLeads ?? 0,
            'extensionList' => $extensionList,
            'liveCalls' => $liveCalls,
            'getSmsList' => $getSmsList,
            'getVoicemailUnreadCount' => $getVoicemailUnreadCount,
            'availablePackages' => $availablePackages,
            'extension_list'=>$extension_list,
            'campaign_list'=>$campaign_list,
            "map"=>$map,
            "group"=>$group,
            "callback" => $callback,
             "listCount"=>$dashboard->totalList ?? 0,
            "callbackCount"=>$dashboard->totalCallbacks ?? 0,
           "incomingSms"=>$dashboard->incomingSms ?? 0,
           "outgoingSms" =>$dashboard->outgoingSms ?? 0,
           "unreadVoicemail"=>$dashboard->unreadVoicemail ?? 0,
            "receivedVoicemail"=>$dashboard->receivedVoicemail ?? 0,

    ], 200);
} else {
        $userdetails = InheritApiController::headerUserDetails();
    $dashboardType = $userdetails->data->dashboard_type ?? 1;

    if ($dashboardType == 2) {
        // User prefers CRM, redirect immediately
        return redirect()->to('crm-dashboard');
    }
        return view('dashboard.dashboard')->with([
            // 'didCount' => $didCount,
            // 'userCount' => $userCount,
            // 'campaignCount' => $campaignCount,
            // 'leadCount' => $leadCount,
                   'didCount' => $dashboard->totalDids ?? 0,
            'userCount' => $dashboard->totalUsers ?? 0,
            'campaignCount' =>  $dashboard->totalCampaigns ?? 0,
            'leadCount' => $dashboard->totalLeads ?? 0,
            'extensionList' => $extensionList ?? [],
            'liveCalls' => $liveCalls ?? [],
            'getSmsList' => $getSmsList ?? [],
            'getVoicemailUnreadCount' => $getVoicemailUnreadCount ?? 0,
            'availablePackages' => $availablePackages ?? [],
            'extension_list'=>$extension_list ?? [],
            'campaign_list'=>$campaign_list ?? [],
            "map"=>$map,
            "group"=>$group ?? [],
            "callback" => $callback ?? [],
            // "listCount"=>$listCount,
            // "callbackCount"=>$callbackCount
                "listCount"=>$dashboard->totalList ?? 0,
            "callbackCount"=>$dashboard->totalCallbacks ?? 0,
        ]);
    }
    }

    function getCallDetail(Request $request)
    {
        //echo "<pre>";print_r($request->all());die;
        $fetchCallDetail = $this->fetchCallDetail($request->start_date, $request->end_date,$request->extension_user_check);
        return response()->json($fetchCallDetail);
    }

    function fetchCallDetail($start_date, $end_date, $extension_user_check)
    {
        if (!empty($start_date) && !empty($end_date)) {

            $date1_ts = strtotime($start_date);
            $date2_ts = strtotime($end_date);
            $diff = $date2_ts - $date1_ts;
            $date_diff = round($diff / 86400);

            $inherit_list = new InheritApiController;

            $extListDashboard = $inherit_list->getExtensionListDashboard($start_date, $end_date, $extension_user_check);
            $data['extListDashboard'] = $extListDashboard;

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


            $data['getDispositionWiseCalls'] = $inherit_list->getDispositionWiseCalls($start_date, $end_date, $extension_user_check);

            $data['outBoundDialer'] = $inherit_list->getCdrCallCount('OUT', 'dialer', $start_date, $end_date, $extension_user_check);
            $data['outBoundDialerC2C'] = $inherit_list->getCdrCallCount('OUT', 'c2c', $start_date, $end_date, $extension_user_check);

            $data['outBoundPredictive'] = $inherit_list->getCdrCallCount('OUT', 'predictive_dial', $start_date, $end_date, $extension_user_check);

            $data['outBoundManual'] = $inherit_list->getCdrCallCount('OUT', 'manual', $start_date, $end_date, $extension_user_check);
            $data['inBoundManual'] = $inherit_list->getCdrCallCount('IN', 'manual', $start_date, $end_date, $extension_user_check);
            $data['inBoundDailer'] = $inherit_list->getCdrCallCount('IN', 'dialer', $start_date, $end_date, $extension_user_check);
            $data['loggedInAgent'] = $inherit_list->getLoggedInAgent($start_date, $end_date, $extension_user_check);

       // echo "<pre>";print_r( $data['inBoundDailer']);die;



            $data['voicemails'] = $inherit_list->getVoiceMailCount($start_date, $end_date, $extension_user_check);

            $data['getStatewiseCalls'] = $inherit_list->getStatewiseCalls($start_date, $end_date, $extension_user_check);
            return $data;
        }
    }

    public function getSmsCounts(Request $request)
    {
        $url = env('API_URL') . 'sms-count';
        $body = [
            'startTime' => $request->startTime,
            'endTime' => $request->endTime,
            'userId'=>$request->userId
        ];
        $response = Helper::PostApi($url, $body);
        if ($response->success) {
            return response()->json($response->data);
        } else {
            return response()->json($response->errors, 500);
        }
    }

    public function getSmsCountsunread(Request $request)
    {
        $body = array(
            'id' => Session::get('id'),
            'token' => Session::get('tokenId')
        );
        $urlSms = env('API_URL') . 'unread-sms-count';
        $response = Helper::PostApi($urlSms, $body);

        if ($response->success) {
            return response()->json($response->data);
        } else {
            return response()->json($response->errors, 500);
        }
    }

    public function getCdrChartData(Request $request)
    {
        $url = env('API_URL') . 'cdr-count-range';
        $body = [
            'range' => $request->range
        ];
        $response = Helper::PostApi($url, $body);
        if ($response->success) {
            return response()->json($response->data);
        } else {
            return response()->json($response->errors, 500);
        }
    }

    function setSessionValue()
    {
       Session::put('timezone_session', 1);
    }
  public function setDashboardToggle(Request $request)
{
    $state = (int) $request->input('state', 1); // default = dashboard
    Session::put('dashboard_type', $state);

    $url = env('API_URL') . 'dashboard-state';
    $body = [
        'state' => $state
    ];

    $response = Helper::PostApi($url, $body);

    if (!empty($response->success) && $response->success) {
        return response()->json([
            'success' => true,
            'data' => $response->data
        ]);
    } else {
        return response()->json([
            'success' => false,
            'errors' => $response->errors ?? ['Failed to save state']
        ], 500);
    }
}


}


