<?php
/**
 * メンバー管理
 */
require_once 'Zend/Controller/Action.php';

class Manage_MemberController extends Zend_Controller_Action
{
    private $contents;
    
    public function preDispatch()
    {
        global $Me, $currentManage, $breadcrumb;
        
        if ($Me->isAdmin() == false) {
            $this->_redirect('/Manage/Login/');
        }
        $currentManage = 'Member';
        $breadcrumb->add('管理', BASE_URL . 'Manage/');
        $breadcrumb->add('メンバー', BASE_URL . 'Manage/Member/');
    }
    
    public function indexAction()
    {
        //echo 'Manage_MemberController indexAction';
        $this->listMemberAction();
    }

    public function noRouteAction()
    {
        //$this->_redirect('/');
        echo "noRouteAction";
    }
    
    /**
     * メンバー一覧
     */
    public function listMemberAction()
    {
        global $db;
        
        ob_start();

        $sql = "SELECT id, username, email, status, last_login FROM Platy_Member";
        $rows = $db->fetchAll($sql);
        
        echo '<h2>メンバー一覧</h2>' . "\n";
        echo '<table class="list_table">' . "\n";
        echo '<th>id</th><th>username</th><th>email</th><th>status</th><th>role</th><th>last_login</th><th>action</th>' . "\n";
        foreach ($rows as $row) {
            if ($i % 2 == 0) { echo '<tr class="even">'; }
            else { echo '<tr class="odd">'; }
            
            echo '<td>' . $row['id'] . '</td>' . "\n";
            echo '<td>' . $row['username'] . '</td>' . "\n";
            echo '<td>' . $row['email'] . '</td>' . "\n";
            echo '<td>' . $row['status'] . '</td>' . "\n";
            
            echo '<td>';
            
            $sql2 = "SELECT r.name FROM Platy_ACL_Member_to_Role m2r, Platy_ACL_Role r WHERE m2r.roleId=r.id AND m2r.memberId={$row['id']}";
            $rows2 = $db->fetchAll($sql2);
            //var_dump($rows2);
            foreach ($rows2 as $row2) {
                echo $row2['name'] . "<br />\n";
            }
            echo '</td>' . "\n";
            
            echo '<td>' . $row['last_login'] . '</td>' . "\n";
            echo '<td>';
            if ($row['id'] == 1 && DEMO) {
            }
            else {
                echo '<a href="' . BASE_URL . 'Manage/Member/editMember/id/' . $row['id'] . '">';
                echo '<img src="' . BASE_URL . 'media/system/edit.png" alt="edit" />';
                echo '編集</a>' . "\n";
                echo '&nbsp;';
                echo '<a href="' . BASE_URL . 'Manage/Member/deleteMember/id/' . $row['id'] . '">';
                echo '<img src="' . BASE_URL . 'media/system/editdelete.png" alt="delete" />';
                echo '削除</a>' . "\n";
            }
            echo '</td>' . "\n";
            echo '</tr>' . "\n";
        }
        echo '</table>' . "\n";
        
        echo '<a href="' . BASE_URL . 'Manage/Member/addMember/">';
        echo '<img src="' . BASE_URL . 'media/system/edit_add.png" alt="add" />';
        echo 'メンバーの登録</a>' . "\n";
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * メンバーの登録
     */
    public function addMemberAction()
    {
        global $db, $config;
        
        $have_roles = array();
        
        ob_start();
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            
            // validation
            // TODO
            
            $username = h(e($_POST['username']));
            $email = h(e($_POST['email']));
            $password = h(e($_POST['password']));
            $hashed_password = sha1($password);
            $roles = $_POST['role'];
            $have_roles = $_POST['role'];
            
            $sql = "INSERT INTO Platy_Member(username, email, password, status) VALUES("
                 . "'{$username}','{$email}','{$hashed_password}','active');";
            $db->query($sql);
            $id = $db->lastInsertId();
            for ($i = 0; $i < count($have_roles); $i++) {
                $sql = "INSERT INTO Platy_ACL_Member_to_Role(memberId, roleId) VALUES({$id}, {$roles[$i]})";
                //echo $sql . "<br />\n";
                $db->query($sql);
            }
        }
        else {
            $username = '';
            $email = '';
            $password = '';
        }
        
        echo '<h2>メンバーの登録</h2>' . "\n";
        echo '<form method="post">' . "\n";
        echo '<table class="form_table">' . "\n";
        echo '<tr><th>username</th><td>';
        echo '<input type="text" name="username" value="' . $username . '" size="60" />' . "</td></tr>\n";
        echo '<tr><th>email</th><td>';
        echo '<input type="text" name="email" value="' . $email . '" size="60" />' . "</td></tr>\n";
        echo '<tr><th>password</th><td>';
        echo '<input type="password" name="password" value="' . $password . '" size="60" />' . "</td></tr>\n";
        echo '<tr><th>role</th><td>';
        
        $sql = "SELECT id, name FROM Platy_ACL_Role";
        $rows = $db->fetchAll($sql);
        foreach ($rows as $row) {
            echo '<input type="checkbox" name="role[]" value="' . $row['id'] . '"';
            if (in_array($row['id'], $have_roles)) {
                echo ' checked="true"';
            }
            echo ' />' . $row['name'] . "&nbsp;&nbsp;\n";
        }
        echo "</td></tr>\n";
        echo '<tr><th></th><td>';
        echo '<input type="submit" value="登録する" />' . "</td></tr>\n";
        echo '</table>' . "\n";
        echo '</form>' . "\n";
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * メンバーの編集
     */
    public function editmemberAction()
    {
        global $db;
        
        $have_roles = array();
        
        ob_start();

        // id/[id]
        $request = $this->getRequest();
        $id = $request->getParam('id');
        
        if ($id == 1 && DEMO) { die(); }
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            
            // validation
            // TODO
            
            $username = h($_POST['username']);
            $email = h($_POST['email']);
            $password = h($_POST['password']);
            $roles = $_POST['role'];
            $have_roles = $_POST['role'];
            
            $table = new DBMember();
            if ($password == "") {
                $data = array(
                    'username'   => $username,
                    'email'      => $email
                );
            }
            else {
                $data = array(
                    'username'   => $username,
                    'email'      => $email,
                    'password'   => sha1($password)
                );
            }
            $where = $table->getAdapter()->quoteInto('id = ?', $id);
            $table->update($data, $where);
            
            $sql = "DELETE FROM Platy_ACL_Member_to_Role WHERE memberId={$id}";
            $db->query($sql);
            for ($i = 0; $i < count($have_roles); $i++) {
                $sql = "INSERT INTO Platy_ACL_Member_to_Role(memberId, roleId) VALUES({$id}, {$roles[$i]})";
                //echo $sql . "<br />\n";
                $db->query($sql);
            }
        }
        else {
            $table = new DBMember();
            $row = $table->fetchRow("id = {$id}");
            $username = $row->username;
            $email = $row->email;
            $password = '';
            $sql = "SELECT roleId FROM Platy_ACL_Member_to_Role WHERE memberId={$id}";
            $rows = $db->fetchAll($sql);
            foreach ($rows as $row) {
                $have_roles[] = $row['roleId'];
            }
        }
        echo '<h2>メンバーの編集</h2>' . "\n";
        echo '<form method="post">' . "\n";
        echo '<table class="form_table">' . "\n";
        echo '<tr><th>id</th><td>' . $id . "</td></tr>\n";
        echo '<tr><th>username</th><td>';
        echo '<input type="text" name="username" value="' . $username . '" size="60" />' . "</td></tr>\n";
        echo '<tr><th>email</th><td>';
        echo '<input type="text" name="email" value="' . $email . '" size="60" />' . "</td></tr>\n";
        echo '<tr><th>password</th><td>';
        echo '<input type="password" name="password" value="' . $password . '" size="60" />';
        echo ' <p class="hint">パスワードを変更しない場合は、何も入力しないでください' . "</p>\n";
        echo "</td></tr>\n";
        echo '<tr><th>role</th><td>';
        
        $sql = "SELECT id, name FROM Platy_ACL_Role";
        $rows = $db->fetchAll($sql);
        foreach ($rows as $row) {
            echo '<input type="checkbox" name="role[]" value="' . $row['id'] . '"';
            if (in_array($row['id'], $have_roles)) {
                echo ' checked="true"';
            }
            echo ' />' . $row['name'] . "&nbsp;&nbsp;\n";
        }
        echo "</td></tr>\n";
        echo '<tr><th></th><td>';
        echo '<input type="submit" value="更新する" />' . "</td></tr>\n";
        echo '</table>' . "\n";
        echo '</form>' . "\n";
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * メンバーの削除
     */
    public function deleteMemberAction()
    {
        global $db;
        // id/[id]

        $request = $this->getRequest();
        $id = $request->getParam('id');
        
        // id==1は管理者なので削除できない
        if ($id == 1) {
            return false;
        }
        $sql = "DELETE FROM Platy_Member WHERE id={$id}";
        $db->query($sql);
        
        $this->_redirect('/Manage/Member/');
    }
    
    /**
     * パスワードを忘れました
     */
    public function lostPasswordAction()
    {
        global $db, $config;
        
        $have_roles = array();
        
        ob_start();
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            
        }
        else {
        }
        
        echo '<h2>パスワードを忘れましたか？</h2>' . "\n";

        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * 表示
     */
    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');
    }
}
?>