<?php

use Acms\Services\Blog\BlogRepository;
use Acms\Services\Facades\Application;

class ACMS_POST_Blog_Index_Status extends ACMS_POST
{
    public function post()
    {
        $this->Post->reset(true);
        $status = $this->Post->get('batchStatus');
        $this->Post->setMethod('blog', 'isOperable', Blog::canBulkChangeStatus(BID, strval($status)));
        $this->Post->setMethod('batchStatus', 'in', ['open', 'close', 'secret']);
        $this->Post->setMethod('checks', 'required');
        $this->Post->validate(new ACMS_Validator());

        if ($this->Post->isValidAll()) {
            $blogRepository = Application::make('blog.repository');
            assert($blogRepository instanceof BlogRepository);
            $aryBid = [];
            foreach ($this->Post->getArray('checks') as $bid) {
                if (!($bid = idval($bid))) {
                    continue;
                }
                if (
                    ACMS_RAM::blogLeft(SBID) > ACMS_RAM::blogRight($bid)
                    || ACMS_RAM::blogRight(SBID) < ACMS_RAM::blogRight($bid)
                ) {
                    continue;
                }

                $aryStatus = [];
                switch ($status) {
                    case 'close':
                        $aryStatus[] = 'secret';
                        break;
                    case 'secret':
                        $aryStatus[] = 'open';
                        break;
                    case 'open':
                    default:
                        break;
                }

                if (
                    count($aryStatus) > 0
                    && $blogRepository->hasDescendantWithStatusIn($bid, $aryStatus)
                ) {
                    continue;
                }

                $blogRepository->updateStatusBulk([$bid], strval($status));

                Cache::flush('temp');

                $this->Post->set('success', 'status');

                $aryBid[] = $bid;
            }
            if ($status === 'open') {
                $status = '公開';
            }
            if ($status === 'close') {
                $status = '非公開';
            }
            if ($status === 'secret') {
                $status = 'シークレット';
            }

            AcmsLogger::info('指定されたブログのステータスを「' . $status . '」に変更しました', [
                'targetBIDs' => implode(',', $aryBid),
            ]);
        } else {
            $this->Post->set('error', 'status_1');
        }

        return $this->Post;
    }
}
