<?php

namespace App\Controllers\SuperAdmin;

use App\Controllers\BaseController;
use App\Models\ReportedSystemModel;
use App\Models\RegisteredSystemModel;
use App\Models\AdminModel;
use App\Models\LicenseKeyModel;

class ReportedSystems extends BaseController
{
    public function index()
    {
        $adminModel = new AdminModel();
        $licenseModel = new LicenseKeyModel();
        $registeredSystemModel = new RegisteredSystemModel();
        
        $licenses = $licenseModel->orderBy('created_at', 'DESC')->findAll();
        
        $selectedLicenseId = $this->request->getGet('license_id');
        $reportedSystems = [];
        $registeredSystems = [];
        $selectedLicense = null;
        
        if ($selectedLicenseId) {
            $selectedLicense = $licenseModel->find($selectedLicenseId);
            
            if ($selectedLicense) {
                $reportedSystemModel = new ReportedSystemModel();
                $reportedSystems = $reportedSystemModel
                    ->where('license_id', $selectedLicenseId)
                    ->orderBy('last_seen_at', 'DESC')
                    ->findAll();
                    
                $registeredSystems = $registeredSystemModel
                    ->where('license_id', $selectedLicenseId)
                    ->orderBy('last_seen_at', 'DESC')
                    ->findAll();
            }
        }
        
        return view('superadmin/reported_systems', [
            'licenses' => $licenses,
            'selectedLicenseId' => $selectedLicenseId,
            'selectedLicense' => $selectedLicense,
            'reportedSystems' => $reportedSystems,
            'registeredSystems' => $registeredSystems,
        ]);
    }
}
