<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\Apptitle;
use App\Models\Footertext;
use App\Models\Seosetting;
use App\Models\Pages;
use App\Models\User;
use App\Models\Ticket\Ticket;
use App\Models\Userrating;
use App\Models\Employeerating;
use App\Models\Articles\Article;
use App\Models\LiveChatConversations;
use App\Models\LiveChatCustomers;
use Torann\GeoIP\Facades\GeoIP;
use Jenssegers\Agent\Agent;
use App\Models\EmployeeActivity;
use Illuminate\Support\Facades\Auth;

class AdminReportController extends Controller
{
   public function index()
   {
        $this->authorize('Reports Access');

        $users = User::latest('updated_at')->paginate(6);
        $data['users'] = $users;

        $title = Apptitle::first();
        $data['title'] = $title;

        $footertext = Footertext::first();
        $data['footertext'] = $footertext;

        $seopage = Seosetting::first();
        $data['seopage'] = $seopage;

        $post = Pages::all();
        $data['page'] = $post;

        $agentactivec = User::where('status','1')->count();
        $data['agentactivec'] = $agentactivec;
        $agentinactive = User::where('status','0')->count();
        $data['agentinactive'] = $agentinactive;

        $livecust = LiveChatCustomers::get();
        $newchatcountdata = $livecust->filter(function ($item) {
            $currentOnlineUsers = setting('liveChatCustomerOnlineUsers');
            $onlineUsersArray = explode(',', $currentOnlineUsers);
            if(in_array($item->id, $onlineUsersArray)){
                $item->onlineoroffline = 'online';
            }else{
                $item->onlineoroffline = 'offline';
            }
        });

        $customeractive = $livecust->where('onlineoroffline','online')->count();
        $data['customeractive'] = $customeractive;
        $customerinactive = $livecust->where('onlineoroffline','offline')->count();
        $data['customerinactive'] = $customerinactive;

        $newticket = Ticket::where('status', 'New')->count();
        $data['newticket'] = $newticket;

        $closedticket = Ticket::where('status', 'Closed')->count();
        $data['closedticket'] = $closedticket;

        $inprogressticket = Ticket::where('status', 'Inprogress')->count();
        $data['inprogressticket'] = $inprogressticket;

        $onholdticket = Ticket::where('status', 'On-Hold')->count();
        $data['onholdticket'] = $onholdticket;

        $reopenticket = Ticket::where('status', 'Re-Open')->count();
        $data['reopenticket'] = $reopenticket;

        $newchatcountdata = $livecust->filter(function ($item) {
            if($item->livechatconversation->last() != null){
                return ($item->engage_conversation === null || $item->engage_conversation === '') && $item->status != 'solved' && $item->livechatconversation->last()->delete == null;
            }else{
                $convers = LiveChatConversations::where('unique_id',$item->cust_unique_id)->first();
                if($convers != null && $convers->delete == null){
                    return ($item->engage_conversation === null || $item->engage_conversation === '') && $item->status != 'solved';
                }
            }
        });
        $data['newchatcount'] = $newchatcountdata->count();

        $myopenedcountdata = $livecust->filter(function ($item) {
            $engageConversation = json_decode($item->engage_conversation, true);
            return $item->banstatus !== 'banned' && collect($engageConversation)->contains('id', auth()->id());
        });
        $data['myopenedcount'] = $myopenedcountdata->count();

        $solvedcountdata = $livecust->filter(function ($item) {
            return ($item->engage_conversation === null || $item->engage_conversation === '') && $item->status == 'solved' && $item->banstatus !== 'banned';
        });
        $data['solvedcount'] = $solvedcountdata->count();

        $data['unassingedticketscount'] = Ticket::whereNull('myassignuser_id')->whereNull('selfassignuser_id')->where('status', '!=' ,'Closed')->count();
        $data['assignedticketscount'] = Ticket::whereNotNull('selfassignuser_id')->where('status', '!=' ,'Closed')->count();
        $data['myclosedticketscount'] = Ticket::where('status' ,'Closed')->count();

        $articlepublished = Article::where('status', 'Published')->count();
        $data['articlepublished'] = $articlepublished;

        $articleunpublished = Article::where('status', 'UnPublished')->count();
        $data['articleunpublished'] = $articleunpublished;

        $activity = EmployeeActivity::latest('created_at')->paginate(6);
        $data['activity'] = $activity;

        return view('admin.reports.index')->with($data);
   }

   public function ticketreports()
	{

      $users = User::with('permissions', 'roles')->get();
      $users = $users->each(function ($user) {
        $avgrating1 = Employeerating::where('user_id',$user->id)->where('rating', '1')->count();
        $avgrating2 = Employeerating::where('user_id',$user->id)->where('rating', '2')->count();
        $avgrating3 = Employeerating::where('user_id',$user->id)->where('rating', '3')->count();
        $avgrating4 = Employeerating::where('user_id',$user->id)->where('rating', '4')->count();
        $avgrating5 = Employeerating::where('user_id',$user->id)->where('rating', '5')->count();

        $avgr = ((5*$avgrating5) + (4*$avgrating4) + (3*$avgrating3) + (2*$avgrating2) +
        (1*$avgrating1));
        $avggr = ($avgrating1 + $avgrating2 + $avgrating3 + $avgrating4 + $avgrating5);

        if($avggr == 0){
            $avggr = 1;
            $avg = $avgr/$avggr;
        }else{
            $avg = $avgr/$avggr;
        }

        $rating = $avg;
        $user->rating = $rating;
        $overallcount = Employeerating::where('user_id',$user->id)->count();
        $user->overallcount = $overallcount;
        $comentticketss = Ticket::leftJoin('comments','comments.ticket_id','tickets.id')->where('comments.user_id', $user->id)->distinct('comments.ticket_id')->count();
        $user->comentticketss = $comentticketss;
        return $user;
      });
      $data['users'] = $users;

      $title = Apptitle::first();
      $data['title'] = $title;

      $footertext = Footertext::first();
      $data['footertext'] = $footertext;

      $seopage = Seosetting::first();
      $data['seopage'] = $seopage;

      $post = Pages::all();
      $data['page'] = $post;



      return view('admin.reports.ticketratingreport')->with($data);
  }

   public function employeedetails($id)
   {
      $users = User::find($id);
      $data['users'] = $users;

      $employeeratings = Ticket::select('tickets.*')->leftJoin('comments','comments.ticket_id','tickets.id')
      ->where('comments.user_id', $users->id)->distinct('comments.ticket_id', 'tickets.id')->get();
      $employeeratings = $employeeratings->each(function ($ticket) {
        $avgrating1 = Userrating::where('ticket_id',$ticket->id)->where('ratingstar', '1')->count();
        $avgrating2 = Userrating::where('ticket_id',$ticket->id)->where('ratingstar', '2')->count();
        $avgrating3 = Userrating::where('ticket_id',$ticket->id)->where('ratingstar', '3')->count();
        $avgrating4 = Userrating::where('ticket_id',$ticket->id)->where('ratingstar', '4')->count();
        $avgrating5 = Userrating::where('ticket_id',$ticket->id)->where('ratingstar', '5')->count();

        $ticketdata = Userrating::with('customer')->where('ticket_id',$ticket->id)->get();

        $avgr = ((5*$avgrating5) + (4*$avgrating4) + (3*$avgrating3) + (2*$avgrating2) + (1*$avgrating1));
        $avggr = ($avgrating1 + $avgrating2 + $avgrating3 + $avgrating4 + $avgrating5);

        if($avggr == 0){
            $avggr = 1;
            $avg = $avgr/$avggr;
        }else{
            $avg = $avgr/$avggr;
        }

        $rating = $avg;

        $ticket->rating = $rating;
        $ticket->ticketdata = $ticketdata;
        $viewRoteUrl = fetchticketviewurl($ticket);
        $ticket->viewRoteUrl = $viewRoteUrl;
        return $ticket;
      });
      $data['employeeratings'] = $employeeratings;

      $title = Apptitle::first();
      $data['title'] = $title;

      $footertext = Footertext::first();
      $data['footertext'] = $footertext;

      $seopage = Seosetting::first();
      $data['seopage'] = $seopage;

      $post = Pages::all();
      $data['page'] = $post;

      return view('admin.reports.ratingview')->with($data);
   }

	public function ratingticketdelete($id)
	{
		$ticketratingdelete = Userrating::where('ticket_id', $id)->first();

		$employeeratingdelete = Employeerating::where('urating_id', $ticketratingdelete->id)->get();
		foreach($employeeratingdelete as $employeesrating)
		{
			$employeesrating->delete();
		}
		$ticketratingdelete->delete();

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Agent Rating Report Deleted';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

		return response()->json(['success' => lang('Delete successfully', 'alerts')]);

	}


    public function employeeactivity(Request $request)
    {
        $title = Apptitle::first();
        $data['title'] = $title;

        $footertext = Footertext::first();
        $data['footertext'] = $footertext;

        $seopage = Seosetting::first();
        $data['seopage'] = $seopage;

        $post = Pages::all();
        $data['page'] = $post;

        $activity = EmployeeActivity::latest('created_at')->paginate(20);
        $data['activity'] = $activity;

        $data['jsempactivity'] = EmployeeActivity::with('user')->get();

        return view('admin.reports.employeeacivity')->with($data);
    }
}
