<?php
namespace PortalPeopleStatis\modules\SatisfyManager\controllers;

// No Yii2 Controller inheritance
use PortalPeopleStatis\modules\SatisfyManager\forms\PackageForm;
use PortalPeopleStatis\modules\SatisfyManager\services\NotificationService;
use Yiisoft\Yii\ViewRenderer\ViewRenderer;
use Yiisoft\Validator\Validator;

class PackageController
{
    public $validator;
    public $notificationService;
    private $viewRenderer;

    function __construct(ViewRenderer $viewRenderer)
    {
        $this->validator = new Validator();
        $this->notificationService = new NotificationService();
        $this->viewRenderer = $viewRenderer;
    }

    function actionIndex()
    {
        $packageRepository = new \PortalPeopleStatis\modules\SatisfyManager\repositories\PackageRepository(
            new \Yiisoft\Db\Connection(/* DB config here */)
        );
        $packages = $packageRepository->findAll();
        return $this->viewRenderer->render('package/index', ['packages' => $packages]);
    }

    function actionCreate()
    {
        $form = new PackageForm();
        $message = '';
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $form->setName($_POST['name'] ?? '');
            $form->setVersion($_POST['version'] ?? '');
            $form->setRepoUrl($_POST['repoUrl'] ?? '');
            $result = $this->validator->validate($form);
            if ($result->isValid()) {
                $packageRepository = new \PortalPeopleStatis\modules\SatisfyManager\repositories\PackageRepository(
                    new \Yiisoft\Db\Connection(/* DB config here */)
                );
                $package = new \PortalPeopleStatis\modules\SatisfyManager\models\Package([
                    'name' => $form->getName(),
                    'version' => $form->getVersion(),
                    'repoUrl' => $form->getRepoUrl(),
                ]);
                $packageRepository->save($package);
                $this->notificationService->sendEmail(
                    'New Package Created',
                    'Package: ' . $form->getName() . ' Version: ' . $form->getVersion() . ' Repo: ' . $form->getRepoUrl(),
                    'admin@example.com'
                );
                $message = 'Package created and email sent!';
            } else {
                $message = implode(' ', $result->getErrorMessages());
            }
        }
        return $this->viewRenderer->render('package/create', ['form' => $form, 'message' => $message]);
    }

    function actionUpdate($id)
    {
        // TODO: Update package
        return $this->viewRenderer->render('package/update', ['id' => $id]);
    }
}
