<?php

namespace App\Http\Controllers\panel;

use App\Http\Controllers\Controller;
use App\Reply;
use App\Report;
use App\Services\PatronicService;
use App\Services\UpdateService;
use App\Ticket;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class PanelController extends Controller
{
    public function index()
    {
        return $this->loadPanel();
    }

    public function loadPanel()
    {
        if (auth()->user()->isUser()) {
            return $this->loadUserPanel();
        } elseif (auth()->user()->isSuperior()) {
            return $this->loadSuperiorPanel();
        } else {
            abort(403);
        }
    }

    public function loadSuperiorPanel()
    {
        if (auth()->user()->isStaff()) {
            return redirect()->route('panel.tickets.index');
        }
        $allTicketsCount = Ticket::all()->count();
        $unreadTicketsCount = Ticket::countUnread();
        $readTicketsCount = Ticket::countread();
        $repliedTicketsCount = Ticket::countReplied();
        $closedTicketsCount = Ticket::countClosed();
        $tickets = Ticket::latest('updated_at')->take(5)->get();
        $reports = Report::with(['user:id,name', 'ticket:id'])->latest()->take(5)->get();
        $superiorStaffs = Reply::orderByRate()->take(5)->get();
        $update = UpdateService::checkForUpdate();
        $last10DaysDate = Carbon::parse(now())->subDays(9)->startOfDay();
        $ticketsWeeklyDataForChart = [];

        for ($day = 0; $day < 10; $day++) {
            $ticketsWeeklyDataForChart[now()->subDays($day)->format('Y-m-d')] = [
                'date' => now()->subDays($day)->format('Y-m-d'),
                'unread' => 0,
                'read' => 0,
                'replied' => 0,
            ];
        }

        Ticket::select(DB::raw('COUNT(id) AS total,CAST(created_at AS date) as cdate,status'))
            ->where('created_at', '>', $last10DaysDate)
            ->where('status', 'unread')
            ->whereNull('closed_at')
            ->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y%m%d')"))
            ->get()
            ->map(function ($item) use (&$ticketsWeeklyDataForChart) {
                $ticketsWeeklyDataForChart[$item['cdate']]['unread'] = $item['total'];
            });
        Ticket::select(DB::raw('COUNT(id) AS total,CAST(created_at AS date) as cdate,status'))
            ->where('created_at', '>', $last10DaysDate)
            ->where('status', 'read')
            ->whereNull('closed_at')
            ->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y%m%d')"))
            ->get()
            ->map(function ($item) use (&$ticketsWeeklyDataForChart) {
                $ticketsWeeklyDataForChart[$item['cdate']]['read'] = $item['total'];
            });
        Ticket::select(DB::raw('COUNT(id) AS total,CAST(created_at AS date) as cdate,status'))
            ->where('created_at', '>', $last10DaysDate)
            ->where('status', 'replied')
            ->whereNull('closed_at')
            ->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y%m%d')"))
            ->get()
            ->map(function ($item) use (&$ticketsWeeklyDataForChart) {
                $ticketsWeeklyDataForChart[$item['cdate']]['replied'] = $item['total'];
            });
        Ticket::select(DB::raw('COUNT(id) AS total,CAST(created_at AS date) as cdate,status'))
            ->where('created_at', '>', $last10DaysDate)
            ->whereNotNull('closed_at')
            ->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y%m%d')"))
            ->get()
            ->map(function ($item) use (&$ticketsWeeklyDataForChart) {
                $ticketsWeeklyDataForChart[$item['cdate']]['closed'] = $item['total'];
            });

        $ticketsWeeklyDataForChart = array_map(
            function ($item) {
                return [
                    'date' => jdate($item['date'])->format('m/d'),
                    'read' => $item['read'] ?? 0,
                    'unread' => $item['unread'] ?? 0,
                    'replied' => $item['replied'] ?? 0,
                    'closed' => $item['closed'] ?? 0,
                ];
            },
            $ticketsWeeklyDataForChart
        );

        $ticketsWeeklyDataForChart = json_encode(array_values($ticketsWeeklyDataForChart));


        return view('panel.index',
            compact(
                'allTicketsCount',
                'unreadTicketsCount',
                'readTicketsCount',
                'repliedTicketsCount',
                'closedTicketsCount',
                'tickets',
                'superiorStaffs',
                'update',
                'reports',
                'ticketsWeeklyDataForChart'
            )
        );
    }

    public function loadUserPanel()
    {
        $tickets = Ticket::where('user_id', auth()->user()->id)->with('department')->latest('updated_at')->paginate(10);
        return view('panel.user-panel', compact('tickets'));
    }

    public function logout()
    {
        Auth::logout();
        return redirect()->route('main');
    }
}
