<?php 

namespace App\Controllers\Superadmin; 

use App\Controllers\BaseController; 
use Config\Database; 

class Dashboard extends BaseController 
{ 
    protected $db; 

    public function __construct() 
    { 
        $this->db = Database::connect(); 
    } 

    public function index() 
    { 
        // ========================== 
        // CARD SUMMARY
        // ========================== 
        $totalUser     = $this->db->table('users')->countAllResults(); 
        $totalActivity = $this->db->table('activity_logs')->countAllResults(); 
        $totalLogin    = $this->db->table('login_logs')->countAllResults(); 

        // ========================== 
        // USER TERBARU (10 User Terakhir)
        // ========================== 
        $latestUsers = $this->db->table('users')
            ->select('id_user, username, nama_lengkap, created_at')
            ->orderBy('id_user', 'DESC')
            ->limit(10)
            ->get()
            ->getResultArray();

        // ========================== 
        // AKTIVITAS USER (10 Terakhir)
        // ========================== 
        $latestActivity = $this->db->table('activity_logs a') 
            ->select("a.timestamp, a.aktivitas, u.username, u.nama_lengkap") 
            ->join('users u', 'u.id_user=a.id_user', 'left') 
            ->orderBy('a.id_log', 'DESC') 
            ->limit(10) 
            ->get() 
            ->getResultArray(); 

        // ========================== 
        // LOGIN USER (10 Terakhir)
        // ========================== 
        $latestLogin = $this->db->table('login_logs l') 
            ->select("l.login_at, l.logout_at, l.ip_address, l.browser, u.username, u.nama_lengkap") 
            ->join('users u', 'u.id_user=l.id_user', 'left') 
            ->orderBy('l.id_login', 'DESC') 
            ->limit(10) 
            ->get() 
            ->getResultArray(); 

        // ========================== 
        // DATA VIEW 
        // ========================== 
        $data = [ 
            'title'           => 'Dashboard Superadmin', 
            'total_user'      => $totalUser, 
            'total_activity'  => $totalActivity, 
            'total_login'     => $totalLogin, 
            'latest_users'    => $latestUsers, 
            'latest_activity' => $latestActivity, 
            'latest_login'    => $latestLogin, 
        ]; 

        return view('superadmin/dashboard', $data); 
    } 
}