<?php

namespace App\Controllers\Api;

use CodeIgniter\RESTful\ResourceController;
use App\Models\ReportedSystemModel;
use App\Models\LicenseKeyModel;

class SystemReport extends ResourceController
{
    protected $format = 'json';
    protected ReportedSystemModel $reportedSystemModel;
    protected LicenseKeyModel $licenseModel;

    public function __construct()
    {
        $this->reportedSystemModel = new ReportedSystemModel();
        $this->licenseModel = new LicenseKeyModel();
    }

    public function receiveReport()
    {
        $deployment = config('Deployment');
        
        if (!$deployment->isSuperAdmin()) {
            return $this->failForbidden('This endpoint is only available on Super Admin deployment');
        }

        $apiKey = $this->request->getHeaderLine('X-API-Key') ?? $this->request->getVar('api_key');
        $expectedApiKey = env('license.apiKey', env('superadmin.reportingApiKey', ''));
        
        if (!empty($expectedApiKey) && $apiKey !== $expectedApiKey) {
            return $this->failUnauthorized('Invalid API key');
        }

        $licenseCode = $this->request->getVar('license_code');
        $macHash = $this->request->getVar('mac_hash');
        $hostname = $this->request->getVar('hostname');
        $ipAddress = $this->request->getVar('ip_address');
        $userId = $this->request->getVar('user_id');
        $userName = $this->request->getVar('user_name');
        $adminSource = $this->request->getVar('admin_source') ?? 'unknown';

        if (empty($licenseCode) || empty($macHash)) {
            return $this->fail('License code and MAC hash are required', 400);
        }

        $license = $this->licenseModel->where('license_code', $licenseCode)->first();
        
        if (!$license) {
            return $this->failNotFound('License not found');
        }

        $existing = $this->reportedSystemModel
            ->where('license_id', $license['id'])
            ->where('mac_hash', $macHash)
            ->first();

        $data = [
            'license_id' => $license['id'],
            'mac_hash' => $macHash,
            'hostname' => $hostname,
            'ip_address' => $ipAddress,
            'user_id' => $userId,
            'user_name' => $userName,
            'admin_source' => $adminSource,
            'last_seen_at' => date('Y-m-d H:i:s'),
            'status' => 'active',
        ];

        if ($existing) {
            $this->reportedSystemModel->update($existing['id'], $data);
            $isNew = false;
        } else {
            $data['first_seen_at'] = date('Y-m-d H:i:s');
            $this->reportedSystemModel->insert($data);
            $isNew = true;
        }

        $activeCount = $this->reportedSystemModel
            ->where('license_id', $license['id'])
            ->where('status', 'active')
            ->countAllResults();

        return $this->respond([
            'success' => true,
            'message' => $isNew ? 'System registered' : 'System updated',
            'is_new' => $isNew,
            'active_systems' => $activeCount,
        ]);
    }

    public function getSystemsByLicense()
    {
        $deployment = config('Deployment');
        
        if (!$deployment->isSuperAdmin()) {
            return $this->failForbidden('This endpoint is only available on Super Admin deployment');
        }

        $apiKey = $this->request->getHeaderLine('X-API-Key') ?? $this->request->getVar('api_key');
        $expectedApiKey = env('license.apiKey', env('superadmin.reportingApiKey', ''));
        
        if (!empty($expectedApiKey) && $apiKey !== $expectedApiKey) {
            return $this->failUnauthorized('Invalid API key');
        }

        $licenseCode = $this->request->getVar('license_code');
        
        if (empty($licenseCode)) {
            return $this->fail('License code is required', 400);
        }

        $license = $this->licenseModel->where('license_code', $licenseCode)->first();
        
        if (!$license) {
            return $this->failNotFound('License not found');
        }

        $systems = $this->reportedSystemModel
            ->where('license_id', $license['id'])
            ->orderBy('last_seen_at', 'DESC')
            ->findAll();

        return $this->respond([
            'success' => true,
            'license_code' => $licenseCode,
            'systems' => $systems,
            'total' => count($systems),
            'active' => count(array_filter($systems, fn($s) => $s['status'] === 'active')),
        ]);
    }
}
