<?php

namespace App\Controllers\Admin;

use App\Models\Control\TenantRecordModel;
use Throwable;

/**
 * Basic platform health: control DB connectivity (trivially true if this
 * page loaded at all, but checked explicitly for the status card) and a
 * live connection check against every active tenant's own database —
 * catches the "hotel's DB server is down / credentials rotted" case
 * before a hotel calls in confused. Deliberately synchronous and un-cached:
 * this is an operator manually checking status, not a monitoring feed.
 */
class SystemHealthController extends BaseAdminController
{
    public function index()
    {
        $tenants = (new TenantRecordModel())->where('status', 'active')->findAll();
        $checks  = [];

        foreach ($tenants as $tenant) {
            $checks[] = [
                'tenant' => $tenant,
                'ok'     => $this->canConnect($tenant->db_name),
            ];
        }

        return view('admin/system_health/index', [
            'pageTitle'   => 'System Health',
            'activeNav'   => 'system',
            'controlDbOk' => true, // this request already proves it
            'checks'      => $checks,
            'phpVersion'  => PHP_VERSION,
            'ciVersion'   => \CodeIgniter\CodeIgniter::CI_VERSION,
        ]);
    }

    private function canConnect(string $dbName): bool
    {
        try {
            $connection = service('tenantContext')->buildConnectionFor($dbName);
            $connection->query('SELECT 1');

            return true;
        } catch (Throwable $e) {
            log_message('error', "System health check failed for {$dbName}: " . $e->getMessage());

            return false;
        }
    }
}
