<?php
/**
 * ロール管理
 */
require_once 'Zend/Controller/Action.php';

class Manage_RoleController extends Zend_Controller_Action
{
    private $contents;
    
    public function preDispatch()
    {
        global $Me, $currentManage, $breadcrumb;
        
        if ($Me->isAdmin() == false) {
            $this->_redirect('/Manage/Login/');
        }
        $currentManage = 'Role';
        $breadcrumb->add('管理', BASE_URL . 'Manage/');
        $breadcrumb->add('ロール', BASE_URL . 'Manage/Role/');
    }
    
    public function indexAction()
    {
        $this->_redirect('/Manage/Role/listRole/');
    }
    
    public function noRouteAction()
    {
        //$this->_redirect('/');
        echo "noRouteAction";
    }
    
    /**
     * ロール一覧
     */
    public function listroleAction()
    {
        global $db;
        
        ob_start();

        $sql = "SELECT id, name, summary FROM Platy_ACL_Role";
        $rows = $db->fetchAll($sql);
        
        echo '<h2>Role一覧</h2>' . "\n";
        echo '<table class="list_table">' . "\n";
        echo '<th>id</th><th>name</th><th>summary</th><th>action</th>' . "\n";
        for ($i = 0; $i < count($rows); $i++) {
            $row = $rows[$i];
            
            if ($i % 2 == 0) { echo '<tr class="even">'; }
            else { echo '<tr class="odd">'; }
            
            echo '<td>' . $row['id'] . '</td>' . "\n";
            echo '<td>' . $row['name'] . '</td>' . "\n";
            echo '<td>' . $row['summary'] . '</td>' . "\n";
            echo '<td>';
            echo '<a href="' . BASE_URL . 'Manage/Role/editRole/id/' . $row['id'] . '">';
            echo '<img src="' . BASE_URL . 'media/system/pencil.png" alt="edit" />';
            echo 'edit</a>' . "\n";

            echo '<a href="' . BASE_URL . 'Manage/Role/deleteRole/id/' . $row['id'] . '">';
            echo '<img src="' . BASE_URL . 'media/system/delete.png" alt="delete" />';
            echo 'delete</a>' . "\n";
            echo '</td>' . "\n";
            echo '</tr>' . "\n";
        }
        echo '</table>' . "\n";
        
        echo '<a href="' . BASE_URL . 'Manage/Role/addRole/">Roleの追加</a>' . "<br />\n";
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * ロールの登録
     */
    public function addroleAction()
    {
        global $db;
        $have_privileges = array();
        
        ob_start();
        
        $error = array();
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            
            $name = h(e($_POST['name']));
            $summary = h(e($_POST['summary']));
            $privilege = $_POST['privilege'];
            $have_privilege = $privilege;
            
            if ($name == '') {
                $error[] = 'nameが未入力です';
            }
            if (!count($errors)) {
                $sql = "SELECT id FROM Platy_ACL_Role WHERE name='{$name}'";
                $row = $db->fetchRow($sql);
                if ($row != false) {
                    $errors[] = 'nameがすでにあります';
                }
            }
            
            if (!count($errors)) {
                $sql = "INSERT INTO Platy_ACL_Role(name,summary) VALUES('{$name}','{$summary}')";
                echo $sql . "<br />\n";
                $db->query($sql);
                $id = $db->lastInsertId();
                
                for ($i = 0; $i < count($privilege); $i++) {
                    $sql = "INSERT INTO Platy_ACL_Role_to_Privilege(roleId, privilegeId) VALUES({$id}, {$privilege[$i]})";
                    //echo $sql . "<br />\n";
                    $db->query($sql);
                }
                $this->_redirect('/Member/Role/listRole/');
            }
        }
        else {
            $name = '';
            $summary = '';
        }
        
        echo '<h2>ロールの登録</h2>' . "\n";
        
        echo '<form method="post" action="">' . "\n";
        echo '<table class="form_table">' . "\n";
        echo '<tr><th>name</th><td>';
        echo '<input type="text" name="name" value="' . $name . '" size="60" />';
        echo '</td></tr>' . "\n";
        
        echo '<tr><th>summary</th><td>';
        echo '<textarea name="summary" rows="3" cols="60">' . $summary . '</textarea>';
        echo '</td></tr>' . "\n";
        
        echo '<tr><th>権限</th><td>';
        
        $sql = "SELECT id, name, summary FROM Platy_ACL_Privilege";
        $rows = $db->fetchAll($sql);
        foreach ($rows as $row) {
            echo '<input type="checkbox" name="privilege[]" value="' . $row['id'] . '"';
            if (in_array($row['id'], $have_privileges)) {
                echo ' checked="true"';
            }
            echo ' />' . $row['name'] . "<br />\n";
        }
        echo '</td></tr>' . "\n";
        
        echo '<tr><th></th><td>';
        echo '<input type="submit" value="登録する" />';
        echo '</td></tr>' . "\n";

        echo '</table>' . "\n";
        echo '</from>' . "\n";
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * Roleの編集と権限の割り当て
     */
    public function editroleAction()
    {
        global $db;
        
        ob_start();
        
        // id/[id]
        $request = $this->getRequest();
        $id = $request->getParam('id');
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $name = h(e($_POST['name']));
            $summary = h(e($_POST['summary']));
            $sql = "UPDATE Platy_ACL_Role SET name='{$name}', summary='{$summary}' WHERE id={$id}";
            $db->query($sql);
            
            $privilege = $_POST['privilege'];
            //var_dump($privilege);
            
            $sql = "DELETE FROM Platy_ACL_Role_to_Privilege WHERE roleId={$id}";
            $db->query($sql);
            for ($i = 0; $i < count($privilege); $i++) {
                $sql = "INSERT INTO Platy_ACL_Role_to_Privilege(roleId, privilegeId) VALUES({$id}, {$privilege[$i]})";
                //echo $sql . "<br />\n";
                $db->query($sql);
            }
        }
        else {
            $sql = "SELECT name, summary FROM Platy_ACL_Role WHERE id={$id}";
            $row = $db->fetchRow($sql);
            $name = $row['name'];
            $summary = $row['summary'];
        }
        
        echo '<h2>ロールの編集</h2>' . "\n";
        
        echo '<form method="post" action="">' . "\n";
        echo '<table class="form_table">' . "\n";
        echo '<tr><th>name</th><td>';
        echo '<input type="text" name="name" value="' . $name . '" size="60" />';
        echo '</td></tr>' . "\n";

        echo '<tr><th>summary</th><td>';
        echo '<textarea name="summary" rows="3" cols="60">' . $summary . '</textarea>';
        echo '</td></tr>' . "\n";

        echo '<tr><th>権限</th><td>';
        
        $sql = "SELECT privilegeId FROM Platy_ACL_Role_to_Privilege WHERE roleId={$id}";
        $rows = $db->fetchAll($sql);
        $have_privileges = array();
        foreach ($rows as $row) {
            $have_privileges[] = $row['privilegeId'];
        }
        
        $sql = "SELECT id, name, summary FROM Platy_ACL_Privilege";
        $rows = $db->fetchAll($sql);
        
        for ($i = 0; $i < count($rows); $i++) {
            $row = $rows[$i];
            echo '<input type="checkbox" name="privilege[]" value="' . $row['id'] . '"';
            if (in_array($row['id'], $have_privileges)) {
                echo ' checked="true"';
            }
            echo ' />' . $row['name'] . "<br />\n";
        }
        echo '</td></tr>' . "\n";
        
        echo '<tr><th></th><td>';
        echo '<input type="submit" value="更新する" />';
        echo '</td></tr>' . "\n";

        echo '</table>' . "\n";
        echo '</from>' . "\n";
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * Roleの削除
     */
    public function deleteRoleAction()
    {
        global $db;
        
        // id/[id]
        $request = $this->getRequest();
        $id = intval($request->getParam('id'));
        
        $db->beginTransaction();
        try {
            // Platy_ACL_Roleから削除
            $sql = "DELETE FROM Platy_ACL_Role WHERE id={$id}";
            $db->query($sql);
            
            // Platy_ACL_Role_to_Privilegeから削除
            $sql = "DELETE FROM Platy_ACL_Role_to_Privilege WHERE roleId={$id}";
            $db->query($sql);
            
            // Platy_ACL_Member_to_Roleから削除
            $sql = "DELETE FROM Platy_ACL_Member_to_Role WHERE roleId={$id}";
            $db->query($sql);
            
            $db->commit();
        }
        catch (Exception $e) {
            $db->rollBack();
            //echo $e->getMessage();
        }
        
        $this->_redirect('/Manage/Role/listRole/');
    }
    
    /**
     * 権限一覧
     */
    public function listPrivilegeAction()
    {
        global $db;
        
        ob_start();

        $sql = "SELECT id, name, summary FROM Platy_ACL_Privilege";
        $rows = $db->fetchAll($sql);
        
        echo '<h2>権限一覧</h2>' . "\n";
        echo '<table class="list_table">' . "\n";
        echo '<th>id</th><th>name</th><th>summary</th><th>action</th>' . "\n";
        for ($i = 0; $i < count($rows); $i++) {
            $row = $rows[$i];
            
            if ($i % 2 == 0) { echo '<tr class="even">'; }
            else { echo '<tr class="odd">'; }
            
            echo '<td>' . $row['id'] . '</td>' . "\n";
            echo '<td>' . $row['name'] . '</td>' . "\n";
            echo '<td>' . $row['summary'] . '</td>' . "\n";
            echo '<td>';
            echo '<a href="' . BASE_URL . 'Manage/Role/editPrivilege/id/' . $row['id'] . '">';
            echo '<img src="' . BASE_URL . 'media/system/pencil.png" alt="edit" />';
            echo 'edit</a>' . "\n";

            echo '<a href="' . BASE_URL . 'Manage/Role/deletePrivilege/id/' . $row['id'] . '">';
            echo '<img src="' . BASE_URL . 'media/system/delete.png" alt="delete" />';
            echo 'delete</a>' . "\n";
            echo '</td>' . "\n";
            echo '</tr>' . "\n";
        }
        echo '</table>' . "\n";
        
        echo '<a href="' . BASE_URL . 'Manage/Role/addPrivilege/">権限の追加</a>' . "\n";
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * 権限の登録
     */
    public function addPrivilegeAction()
    {
        global $db;
        
        ob_start();
        
        $error = array();
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            
            $name = h(e($_POST['name']));
            $summary = h(e($_POST['summary']));
            
            if ($name == '') {
                $error[] = 'nameが未入力です';
            }
            if (!count($errors)) {
                $sql = "SELECT id FROM Platy_ACL_Privilege WHERE name='{$name}'";
                $row = $db->fetchRow($sql);
                if ($row != false) {
                    $errors[] = 'nameがすでにあります';
                }
            }
            
            if (!count($errors)) {
                $sql = "INSERT INTO Platy_ACL_Privilege(name, summary) VALUES('{$name}','{$summary}')";
                $db->query($sql);
                $this->_redirect('/Manager/Role/listPrivilege/');
            }
            
        }
        else {
            $name = '';
            $summary = '';
        }
        
        echo '<h2>権限の登録</h2>' . "\n";
        
        echo '<form method="post" action="">' . "\n";
        echo '<table class="form_table">' . "\n";
        echo '<tr><th>name</th><td>';
        echo '<input type="text" name="name" value="' . $name . '" size="60" />';
        echo '</td></tr>' . "\n";
        
        echo '<tr><th>summary</th><td>';
        echo '<textarea name="summary" rows="3" cols="60">' . $summary . '</textarea>';
        echo '</td></tr>' . "\n";
        
        echo '<tr><th></th><td>';
        echo '<input type="submit" value="登録する" />';
        echo '</td></tr>' . "\n";
        
        echo '</table>' . "\n";
        echo '</from>' . "\n";
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * 権限の編集
     */
    public function editPrivilegeAction()
    {
        global $db;
        
        ob_start();
        
        // id/[id]
        $request = $this->getRequest();
        $id = $request->getParam('id');
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $name = h(e($_POST['name']));
            $summary = h(e($_POST['summary']));
            $sql = "UPDATE Platy_ACL_Privilege SET name='{$name}', summary='{$summary}' WHERE id={$id}";
            $db->query($sql);
        }
        else {
            $sql = "SELECT name, summary FROM Platy_ACL_Privilege WHERE id={$id}";
            $row = $db->fetchRow($sql);
            $name = $row['name'];
            $summary = $row['summary'];
        }
        
        echo '<h2>権限の編集</h2>' . "\n";
        
        echo '<form method="post" action="">' . "\n";
        echo '<table class="form_table">' . "\n";
        echo '<tr><th>name</th><td>';
        echo '<input type="text" name="name" value="' . $name . '" size="60" />';
        echo '</td></tr>' . "\n";
        
        echo '<tr><th>summary</th><td>';
        echo '<textarea name="summary" rows="3" cols="60">' . $summary . '</textarea>';
        echo '</td></tr>' . "\n";
        
        echo '<tr><th></th><td>';
        echo '<input type="submit" value="更新する" />';
        echo '</td></tr>' . "\n";
        
        echo '</table>' . "\n";
        echo '</from>' . "\n";
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * 権限の削除
     */
    public function deletePrivilegeAction()
    {
        global $db;
        
        // id/[id]
        $request = $this->getRequest();
        $id = intval($request->getParam('id'));
        
        $db->beginTransaction();
        try {
            // Platy_ACL_Privilegeから削除
            $sql = "DELETE FROM Platy_ACL_Privilege WHERE id={$id}";
            $db->query($sql);
            
            // Platy_ACL_Role_to_Privilegeから削除
            $sql = "DELETE FROM Platy_ACL_Role_to_Privilege WHERE privilegeId={$id}";
            $db->query($sql);
            
            $db->commit();
        }
        catch (Exception $e) {
            //$db->rollBack();
            echo $e->getMessage();
        }
        
        $this->_redirect('/Manage/Role/listPrivilege/');
    }
    
    public function buildSidebar()
    {
        ob_start();
        
        echo '<div class="widget">' . "\n";
        echo '<div class="title">メニュー</div>' . "\n";
        echo '<div class="main">' . "\n";
        
        echo '<ul>' . "\n";
        echo '<li>';
        echo '<a href="' . BASE_URL . 'Manage/Role/listRole/">ロール</a>';
        echo '</li>' . "\n";
        echo '<li>';
        echo '<a href="' . BASE_URL . 'Manage/Role/listPrivilege/">権限</a>';
        echo '</li>' . "\n";

        echo '</ul>' . "\n";
        echo '</div>' . "\n";
        echo '</div>' . "<!-- /widget -->\n";
        
        $sidebar = ob_get_contents();
        ob_end_clean();
        
        return $sidebar;
    }
    
    /**
     * 表示
     */
    private function view()
    {
        global $breadcrumb;
        
        Zend_Loader::loadClass('Zend_View');
        $view = new Zend_View();
        $view->setScriptPath(APP_PATH . 'Manage/views');
        $view->contents = $this->contents;
        $view->breadcrumb = $breadcrumb->getContents();
        $view->sidebar = $this->buildSidebar();
        echo $view->render('page.php');
    }
}
?>