<?php

namespace CiextInstaller;

class Upgrade
{

    public function run()
    {
        echo 'Upgrade files' . PHP_EOL;
        $modules_path = 'application/modules';
        $modules = scandir($modules_path);
        foreach ($modules as $module) {
            if ($module == '.' || $module == '..' || !is_dir($modules_path . '/' . $module)) {
                continue;
            }
            foreach (['controllers', 'libraries', 'models'] as $dir) {
                $folder = $modules_path . '/' . $module . '/' . $dir;
                echo 'Folder ' . $folder . ': ' . $this->ucfiles($folder) . ' file(s) changed' . PHP_EOL;
            }
        }

        echo 'Upgraded' . PHP_EOL;
    }

    protected function ucfiles($dir)
    {
        if (!is_dir($dir)) {
            return 0;
        }

        $count = 0;
        $files = scandir($dir);
        foreach ($files as $file) {
            if ($file == '.' || $file == '..') {
                continue;
            }
            
            $source_file = $dir . '/' . $file;
            if (is_dir($source_file)) {
                $count += $this->ucfiles($source_file);
                continue;
            }
            
            if (ucfirst($file) != $file) {
                file_put_contents($dir . '/' . ucfirst($file), file_get_contents($source_file));
                unlink($source_file);
                $count++;
            }
        }
        return $count;
    }

}
