<?php

namespace App\Http\Controllers\Admin;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;

class SystemController extends Controller
{
    public function index(Request $request, array $params = []): void
    {
        $basePath = $this->app->basePath();

        $info = [
            'php_version'     => PHP_VERSION,
            'php_ok'          => version_compare(PHP_VERSION, '8.1.0', '>='),
            'extensions'      => $this->checkExtensions(),
            'writable_dirs'   => $this->checkWritableDirs($basePath),
            'db_status'       => $this->checkDatabase(),
            'installed'       => $this->app->isInstalled(),
            'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
            'active_theme'    => \App\Models\Setting::get('active_theme', 'default'),
            'disk_free'       => @disk_free_space('/'),
            'disk_total'      => @disk_total_space('/'),
        ];

        $this->renderAdmin('system/index', [
            'pageTitle' => 'System Status',
            'info'      => $info,
            'auth'      => $this->auth(),
        ]);
    }

    // ─────────────────────────────────────────────────────────
    // Private helpers
    // ─────────────────────────────────────────────────────────

    /**
     * Check required and optional PHP extensions.
     */
    private function checkExtensions(): array
    {
        $required = [
            'pdo'       => 'PDO (database access)',
            'pdo_mysql' => 'PDO MySQL driver',
            'json'      => 'JSON (settings, homepage sections)',
            'mbstring'  => 'Multibyte strings',
            'fileinfo'  => 'File info (upload MIME detection)',
        ];

        $optional = [
            'gd'        => 'GD (image processing)',
            'imagick'   => 'Imagick (ImageMagick image processing)',
            'intl'      => 'Intl (internationalization)',
            'zip'       => 'ZIP',
            'curl'      => 'cURL',
        ];

        $result = [];

        foreach ($required as $ext => $label) {
            $result[] = [
                'name'     => $ext,
                'label'    => $label,
                'loaded'   => extension_loaded($ext),
                'required' => true,
            ];
        }

        foreach ($optional as $ext => $label) {
            $result[] = [
                'name'     => $ext,
                'label'    => $label,
                'loaded'   => extension_loaded($ext),
                'required' => false,
            ];
        }

        return $result;
    }

    /**
     * Check whether key directories exist and are writable.
     */
    private function checkWritableDirs(string $basePath): array
    {
        $dirs = [
            'storage/'           => $basePath . '/storage',
            'storage/logs/'      => $basePath . '/storage/logs',
            'storage/cache/'     => $basePath . '/storage/cache',
            'storage/sessions/'  => $basePath . '/storage/sessions',
            'public/uploads/'    => $basePath . '/public/uploads',
            'public/uploads/blog/'    => $basePath . '/public/uploads/blog',
            'public/uploads/gallery/' => $basePath . '/public/uploads/gallery',
        ];

        $result = [];
        foreach ($dirs as $label => $path) {
            $result[] = [
                'label'    => $label,
                'path'     => $path,
                'exists'   => is_dir($path),
                'writable' => is_dir($path) && is_writable($path),
            ];
        }

        return $result;
    }

    /**
     * Check the database connection and report table count.
     */
    private function checkDatabase(): array
    {
        if (!$this->app->hasService('database')) {
            return [
                'ok'          => false,
                'message'     => 'Database service not initialised.',
                'table_count' => 0,
            ];
        }

        try {
            $db     = $this->app->db();
            $tables = $db->fetchAll(
                "SELECT TABLE_NAME
                 FROM information_schema.TABLES
                 WHERE TABLE_SCHEMA = DATABASE()
                   AND TABLE_NAME LIKE 'iw_%'"
            );

            return [
                'ok'          => true,
                'message'     => 'Connected',
                'table_count' => count($tables),
            ];
        } catch (\Exception $e) {
            return [
                'ok'          => false,
                'message'     => 'Connection error: ' . $e->getMessage(),
                'table_count' => 0,
            ];
        }
    }
}
