<?php

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

class ACMS_POST_Blog_Index_Parent extends ACMS_POST
{
    public function post()
    {
        $blogRepository = Application::make('blog.repository');
        assert($blogRepository instanceof BlogRepository);

        if (!Blog::canManageStructure(BID)) {
            die403();
        }
        $toPid = idval($this->Post->get('parent'));
        if ($toPid === 0) {
            die500();
        }
        /** @var int|null $sessionUserBlogId */
        $sessionUserBlogId = SBID;
        if ($sessionUserBlogId === null) {
            die403();
        }
        if (!isBlogAncestor($toPid, $sessionUserBlogId, true)) {
            die403();
        }
        $checks = $_POST['checks'] ?? null;
        if (is_array($checks) && count($checks) > 0) {
            $aryBid = [];
            foreach ($checks as $bid) {
                $bid = idval($bid);
                if ($bid === 0) {
                    continue;
                }
                if (isBlogAncestor($toPid, $bid, true)) {
                    continue;
                }
                if (!$blogRepository->changeParent($bid, $toPid)) {
                    continue;
                }

                Cache::flush('temp');
                ACMS_RAM::blog($bid, null);
                $this->Post->set('success', 'parent');

                $aryBid[] = $bid;
            }
            AcmsLogger::info('指定されたブログの親ブログIDを「' . $toPid . '」に変更', [
                'targetBIDs' => implode(',', $aryBid),
            ]);
        } else {
            $this->Post->set('error', 'parent_1');
        }

        return $this->Post;
    }
}
