<?php
/**
 * app/controllers/admin/composer.php
 *
 * This is the composer controller. Its only very effective when using composer for autoloading.
 *
 * @version 3.0
 * @author  Joey Kimsey <Joey@thetempusproject.com>
 * @link    https://TheTempusProject.com
 * @license https://opensource.org/licenses/MIT [MIT LICENSE]
 */
namespace TheTempusProject\Controllers\Admin;

use TheTempusProject\Houdini\Classes\Views;
use TheTempusProject\Houdini\Classes\Issues;
use TheTempusProject\Classes\AdminController;
use TheTempusProject\Classes\Installer;

class Composer extends AdminController {
    public function __construct() {
        parent::__construct();
        self::$title = 'Admin - Composer Dependencies';
    }

    public function index() {
        $installer = new Installer;

        // Files
        $composerJson = $installer->getComposerJson();
        if ( empty( $composerJson ) ) {
            return Issues::add( 'error', 'Composer json is missing.' );
        }
        $composerLock = $installer->getComposerLock();
        if ( empty( $composerLock ) ) {
            return Issues::add( 'error', 'Composer lock file is missing.' );
        }

        // Required Packages
        $requiredPackages = $composerJson[ 'require' ];
        foreach ( $requiredPackages as $name => $version ) {
            $versionsRequired[ strtolower( $name ) ] = $version;
        }

        // Installed Packages
        $installedPackages = $composerLock[ 'packages' ];
        foreach ( $installedPackages as $package ) {
            $name = strtolower( $package[ 'name' ] );
            $versionsInstalled[ $name ] = $package;
        }

        // Versioning
        foreach ( $versionsInstalled as $package ) {
            $name = strtolower( $package[ 'name' ] );
            if ( !empty( $versionsRequired[ $name ] ) ) {
                $versionsInstalled[ $name ][ 'requiredVersion' ] = $versionsRequired[ $name ];
            } else {
                $versionsInstalled[ $name ][ 'requiredVersion' ] = 'sub-dependency';
            }
            $out[] = (object) $versionsInstalled[ $name ];
        }

        Views::view( 'admin.modules.dependencies', $out );
    }
}
