<?php

use Acms\Services\Category\CategoryRepository;
use Acms\Services\Facades\Application as App;
use Acms\Services\Facades\Category;

class ACMS_POST_Category_Index_Sort extends ACMS_POST
{
    public function post()
    {
        if (!Category::canUpdate(BID)) {
            AcmsLogger::warning('権限がないため、指定されたカテゴリーの並び順変更に失敗しました');
            die403();
        }
        if (isset($_POST['checks']) && is_array($_POST['checks']) && count($_POST['checks']) > 0) {
            /** @var CategoryRepository $repository */
            $repository = App::make('category.repository');
            $blogId = BID;
            $reorderedIds = [];
            foreach ($_POST['checks'] as $rawCategoryId) {
                $categoryId = idval($rawCategoryId);
                if ($categoryId <= 0) {
                    continue;
                }
                if ($blogId !== ACMS_RAM::categoryBlog($categoryId)) {
                    continue;
                }
                $toSort = idval($this->Post->get('sort-' . $categoryId));
                if ($toSort < 1) {
                    continue;
                }
                if (!$repository->reorderSibling($categoryId, $toSort, $blogId)) {
                    continue;
                }
                $reorderedIds[] = $categoryId;
            }
            AcmsLogger::info('指定されたカテゴリーの並び順を変更', [
                'targetCIDs' => implode(',', $reorderedIds),
            ]);
        }
        Cache::flush('temp');

        return $this->Post;
    }
}
