<?php

namespace App\Services\Install;

/**
 * Step 2 of the installer. Checks write access to every path the app
 * needs post-install, and surfaces exact chmod fix commands for failures
 * (per 08-installation-workflow.md §Step 2).
 */
class FolderPermissionChecker
{
    private function paths(): array
    {
        return [
            'writable/'                    => WRITEPATH,
            'writable/uploads/'            => WRITEPATH . 'uploads',
            'writable/cache/'              => WRITEPATH . 'cache',
            'writable/logs/'               => WRITEPATH . 'logs',
            'writable/session/'            => WRITEPATH . 'session',
            'public/assets/uploads/'       => FCPATH . 'assets/uploads',
            '.env location'                => ROOTPATH,
        ];
    }

    public function check(): array
    {
        $results = [];

        foreach ($this->paths() as $label => $path) {
            if (! is_dir($path)) {
                @mkdir($path, 0755, true);
            }

            $writable = is_dir($path) && is_writable($path);

            $results[] = [
                'label'       => $label,
                'path'        => $path,
                'passed'      => $writable,
                'fix_command' => $writable ? null : "chmod -R 755 {$path} && chown -R www-data:www-data {$path}",
            ];
        }

        return $results;
    }

    public function allPassed(): bool
    {
        foreach ($this->check() as $row) {
            if (! $row['passed']) {
                return false;
            }
        }
        return true;
    }
}
