<?php
class ItemsController extends AppController {

  var $name = 'Items';
  var $uses = array('Item', 'ArticleItem');
  var $helpers = array('Html', 'Form');

  function admin_index() {
    $this->pageTitle = '管理画面：記事構成リスト';
    $this->layout = 'admin';
    if (!empty($this->data)) {
      $errors = '';
      $i = 0;
      unset($this->Item->validate['name']['required']);
      unset($this->Item->validate['title']['required']);
      foreach ($this->data['Item'] as $id => $val) {
        $i++;
        $data = array('id' => $id, 'sort_order' => $val['sort_order']);
        $this->Item->set($data);
        if (!$this->Item->save()) {
          $errors = $this->validateErrors($this->Item);
          foreach ($errors as $id => $val) {
            $this->flash('No.' . $i . ' ' . $val, 'error');
          }
        }
      }
      if (!$errors) {
        $this->flash( '並び順を更新しました。', 'success' );
      }
      $this->redirect(array('action' => 'admin_index'));
    }
    $this->Item->recursive = 0;
    $this->set('items', $this->Item->find('all', array('order' => 'sort_order')));
  }

  function admin_add() {
    $this->pageTitle = '管理画面：記事項目の追加';
    $this->layout = 'admin';
    if (!empty($this->data)) {
      $this->Item->create();
      $this->Item->set($this->data);
      if ($this->Item->save()) {
        $this->flash( '記事項目を追加しました。', 'success' );
        $this->redirect(array('action' => 'admin_index'));
      }
    }
    $itemTypes = $this->Item->ItemType->find('list');
    $this->set(compact('itemTypes'));
  }

  function admin_edit($id = null) {
    $this->pageTitle = '管理画面：記事項目の編集';
    $this->layout = 'admin';
    if (!$id && empty($this->data)) {
      $this->flash( '該当する記事項目がありません。', 'error' );
      $this->redirect(array('action' => 'admin_index'));
    }
    if (!empty($this->data)) {
      $this->Item->set($this->data);
      if ($this->Item->save()) {
        $this->flash( '記事項目を更新しました。', 'success' );
        $this->redirect(array('action' => 'admin_index'));
      } else {
      }
    }
    if (empty($this->data)) {
      $this->Item->recursive = 0;
      $this->data = $this->Item->read(null, $id);
      if ($this->ArticleItem->findCount(array('item_id' => $id)) > 0) {
        $this->set('itemtype_mod', false);
        $this->set('search_mod', false);
      } else {
        $this->set('itemtype_mod', true);
        $this->set('search_mod', true);
      }
    }
    $itemTypes = $this->Item->ItemType->find('list');
    $this->set(compact('itemTypes'));
  }

  function admin_delete($id = null) {
    if (!$id) {
      $this->flash( '削除する記事項目を指定してください。', 'error' );
      $this->redirect(array('action' => 'admin_index'));
    }
    if ($this->Item->del($id)) {
      $this->flash( '記事項目を削除しました。', 'success' );
      $this->redirect(array('action' => 'admin_index'));
    }
  }

}
?>