<?php

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

class ACMS_POST_Blog_Index_Sort extends ACMS_POST
{
    function post()
    {
        if (!Blog::canManageStructure(BID)) {
            die403();
        }

        $blogRepository = Application::make('blog.repository');
        assert($blogRepository instanceof BlogRepository);

        $checks = $_POST['checks'] ?? null;
        if (is_array($checks) && count($checks) > 0) {
            $aryBid = [];
            foreach ($checks as $bid) {
                $bid = idval($bid);
                if ($bid === 0) {
                    continue;
                }
                $toSort = idval($this->Post->get('sort-' . $bid));
                if ($toSort === 0) {
                    continue;
                }
                if (BID !== ACMS_RAM::blogParent($bid)) {
                    continue;
                }
                if (!$blogRepository->reorderSibling($bid, $toSort)) {
                    continue;
                }

                Cache::flush('temp');
                $this->Post->set('success', 'sort');

                $aryBid[] = $bid;
            }
            AcmsLogger::info('指定されたブログの並び順を変更しました', [
                'targetBIDs' => implode(',', $aryBid),
            ]);
        } else {
            $this->Post->set('error', 'sort_1');
        }
        return $this->Post;
    }
}
