<?php
namespace App\Controllers;

use Config\Database;

class Dashboard extends BaseController
{
    public function index()
    {
        $db = Database::connect();

        // Existing counts (not used in view anymore but kept for future)
        $counts = [
            'students' => 0,
            'receipts' => 0,
            'pending' => 0,
        ];

        // Metrics for the attachment-style dashboard cards
        $metrics = [
            'pendingApplications'   => 0,
            'activeStudents'        => 0,
            'activeStaffs'          => 0,
            'totalBooks'            => 0,
            'dailyVisitorLogs'      => 0,
            'dailyPhoneLogs'        => 0,
            'dailyEnquiries'        => 0,
            'dailyPostalExchanges'  => 0,
        ];

        // Calculate pending applications
        try {
            $metrics['pendingApplications'] = $db->table('applications')->where('status', 'Pending')->countAllResults();
        } catch (\Throwable $e) {
            // ignore if table missing
        }

        // Calculate active students
        try {
            $counts['students'] = $db->table('students')->countAllResults();
            $metrics['activeStudents'] = $counts['students'];
        } catch (\Throwable $e) {
            // ignore if table missing
        }

        // Calculate active staff (users with active status)
        try {
            $metrics['activeStaffs'] = $db->table('users')->where('status', 'active')->countAllResults();
        } catch (\Throwable $e) {
            // ignore if table missing
        }

        // Calculate total books (receipts count as a proxy for books bought)
        try {
            $counts['receipts'] = $db->table('receipts')->countAllResults();
            $metrics['totalBooks'] = $counts['receipts'];
        } catch (\Throwable $e) {
            // ignore if table missing
        }

        // Other metrics are placeholders until their tables exist
        return view('dashboard/index', [
            'title'   => 'Dashboard',
            'counts'  => $counts,
            'metrics' => $metrics,
        ]);
    }
}

