<?php

namespace App\Controllers\View;

use CodeIgniter\Controller;

class HealthController extends Controller
{
    private function checkPath(string $label, string $path): array
    {
        return [
            'label'    => $label,
            'path'     => $path,
            'exists'   => is_dir($path),
            'writable' => is_writable($path),
        ];
    }

    public function index()
    {
        $uploadsBase = rtrim(WRITEPATH, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'uploads';
        $paths = [
            'uploads'                 => $uploadsBase,
            'uploads/reimbursements'  => $uploadsBase . DIRECTORY_SEPARATOR . 'reimbursements',
            'uploads/receipts'        => $uploadsBase . DIRECTORY_SEPARATOR . 'receipts',
            'uploads/checks'          => $uploadsBase . DIRECTORY_SEPARATOR . 'checks',
            'uploads/early_dismissal_signatures' => $uploadsBase . DIRECTORY_SEPARATOR . 'early_dismissal_signatures',
        ];

        $pathsStatus = [];
        foreach ($paths as $label => $p) {
            $pathsStatus[] = $this->checkPath($label, $p);
        }

        $db = \Config\Database::connect();
        $dbChecks = [
            'user_preferences_exists' => $db->tableExists('user_preferences'),
            'settings_exists'         => $db->tableExists('settings'),
            'migrations_exists'       => $db->tableExists('migrations'),
        ];

        $dbChecks['user_preferences_has_timezone'] = $dbChecks['user_preferences_exists']
            ? $db->fieldExists('timezone', 'user_preferences')
            : false;

        $dbChecks['settings_has_timezone'] = $dbChecks['settings_exists']
            ? $db->fieldExists('timezone', 'settings')
            : false;

        $okPaths = array_reduce($pathsStatus, function ($carry, $row) {
            return $carry && $row['exists'] && $row['writable'];
        }, true);

        $okDb = true;
        if ($dbChecks['user_preferences_exists'] && !$dbChecks['user_preferences_has_timezone']) {
            $okDb = false;
        }
        if ($dbChecks['settings_exists'] && !$dbChecks['settings_has_timezone']) {
            $okDb = false;
        }

        $ok = $okPaths && $okDb;

        $payload = [
            'ok'          => $ok,
            'paths'       => $pathsStatus,
            'database'    => $dbChecks,
            'write_path'  => WRITEPATH,
            'timestamp'   => date('c'),
        ];

        $status = $ok ? 200 : 503;
        return $this->response->setStatusCode($status)->setJSON($payload);
    }
}
