<?php
namespace App\Controller\Admin;
use App\Controller\AppController;
use Cake\I18n\FrozenTime;
/**
 * @property \App\Model\Table\ContactMessagesTable $ContactMessages
 */
class DashboardController extends AppController{
    public function initialize(): void
    {
        parent::initialize();
        $this->viewBuilder()
            ->setLayout('admin')
            ->setLayoutPath('Admin');
        if (!$this->isAdminOrStaff()) {
            throw new \Cake\Http\Exception\ForbiddenException('Staffs only.');
        }
    }
    private function isAdminOrStaff(): bool
    {
        $id = $this->request->getAttribute('identity');
        return (bool)($id && in_array($id->get('role'), ['admin', 'staff'], true));
    }
    public function index()
    {
        $bookingsTable = $this->fetchTable('Bookings');
        $messagesTable = $this->fetchTable('ContactMessages');
        $totalActive = $bookingsTable->find()
            ->where(['archived' => 0])
            ->count();
        $pendingDispatch = $bookingsTable->find()
            ->where([
                'status' => 'Pending',
                'assigned_courier IS' => null,
                'archived' => 0
            ])
            ->count();
        $inTransit = $bookingsTable->find()
            ->where(['status' => 'In Transit', 'archived' => 0])
            ->count();
        $today = FrozenTime::today();
        $urgentOrders = $bookingsTable->find()
            ->where([
                'delivery_deadline <=' => $today->endOfDay(),
                'status NOT IN' => ['Delivered', 'Cancelled'],
                'archived' => 0
            ])
            ->count();
        $transportModes = $bookingsTable->find();
        $modeData = $transportModes
            ->select([
                'mode' => 'mode_of_transport',
                'count' => $transportModes->func()->count('*')
            ])
            ->where(['archived' => 0])
            ->groupBy(['mode_of_transport'])
            ->all();
        $unreadMessagesCount = $messagesTable->find()
            ->where(['is_read' => 0])
            ->count();
        $latestUnreadMessages = $messagesTable->find()
            ->where(['is_read' => 0])
            ->orderBy(['created' => 'DESC'])
            ->limit(5)
            ->all();
        $recentBookings = $bookingsTable->find()
            ->orderBy(['created' => 'DESC'])
            ->limit(10)
            ->all();
        $this->set(compact(
            'totalActive',
            'pendingDispatch',
            'inTransit',
            'urgentOrders',
            'modeData',
            'unreadMessagesCount',
            'latestUnreadMessages',
            'recentBookings'
        ));
    }
}
