<?php
require_once 'Zend/Controller/Action.php';

require_once 'Platy/Util.php';

require_once 'Platy/Form.php';

class MemberController extends Zend_Controller_Action
{
    public function indexAction()
    {
        global $Me;
        
        if ($Me->isLoggedIn() == false) {
            $this->_redirect('/Member/login/');
        }
        else {
            $this->_redirect('/Member/viewProfile/');
        }
    }

    public function noRouteAction()
    {
        //$this->_redirect('/');
        echo "noRouteAction";
    }
    
    /**
     * login
     */
    public function loginAction()
    {
        global $db, $config, $Me;
        
        ob_start();

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $email = h(e($_POST['email']));
            $password = h($_POST['password']);
            $hashed_password = sha1($password);
            $sql = "SELECT id FROM Platy_Member WHERE email='{$email}' AND password='{$hashed_password}'";
            $row = $db->fetchRow($sql);
            if (is_array($row)) {
                $id = $row['id'];
                
                // 最終ログイン日時を更新する
                $last_login_date = date('Y-m-d H:i:s');
                $sql = "UPDATE Platy_Member SET last_login='{$last_login_date}' WHERE id={$id}";
                $db->query($sql);

                $Me = new Platy_Member($id);
                $_SESSION[SESS_KEY]['Me'] = $Me;
                $last_login = date('Y-m-d H:i:s');
                $sql = "UPDATE Platy_Member SET last_login='{$last_login}' WHERE id={$id}";
                $db->query($sql);
            }
        }
        else {
            $email = '';
            $password = '';
        }
        
        echo '<h2>ログイン</h2>' . "\n";
        echo '<form method="post" action="">' . "\n";
        echo 'Eメールアドレス:<br />' . "\n";
        echo '<input type="text" name="email" value="' . $email . '" size="60" /><br />' . "\n";
        echo 'パスワード:<br />' . "\n";
        echo '<input type="password" name="password" value="' . $password . '" size="60" /><br />' . "\n";
        echo '<input type="submit" value="ログイン" />' . "\n";
        echo '</form>' . "\n";
        
        echo '<a href="' . BASE_URL . 'Member/register/">Register</a><br />' . "\n";
        echo '<a href="' . BASE_URL . 'Member/lostPassword/">パスワードを忘れましたか？</a><br />' . "\n";
        
        $contents = ob_get_contents();
        ob_end_clean();
        
        Zend_Loader::loadClass('Zend_View');
        $view = new Zend_View();
        $view->setScriptPath(APP_PATH . 'views');
        $view->contents = $contents;
        $view->config = $config;
        echo $view->render('page.php');
    }
    
    /**
     * logout
     */
    public function logoutAction()
    {
        global $Me;
        $Me = new Platy_Member();
        $_SESSION[SESS_KEY]['Me'] = $Me;
        $this->_redirect('/');
    }
    
    /**
     * メンバー登録
     */
    public function registerAction()
    {
        global $db, $config;
        
        $errors = array();
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $email  = h(e($_POST['email']));
            $email2 = h(e($_POST['email2']));
            $password = h(e($_POST['password']));
            $password2 = h(e($_POST['password2']));
            $captcha = h($_POST['captcha']);
            
            // validation
            if ($email == '') {
                $errors[] = "Eメールアドレスを入力してください";
            }
            if ($password == '') {
                $errors[] = "パスワードを入力してください";
            }
            if ($email != $email2) {
                $errors[] = "Eメールアドレスと確認用Eメールアドレスが一致しません";
            }
            if ($password != $password2) {
                $errors[] = "パスワードと確認用パスワードが一致しません";
            }
            if ($captcha != $_SESSION[SESS_KEY][captcha_keystring]) {
                $errors[] = "画像認証に失敗しました";
            }
            
            // Eメールアドレスが登録済みでないことのチェック
            if ($email != '' && $email2 != '' && $email == $email2) {
                $sql = "SELECT COUNT(*) FROM Platy_Member WHERE email='{$email}'";
                $row = $db->fetchRow($sql);
                if ($row['COUNT(*)'] > 0) {
                    $errors[] = "Eメールアドレスが既に登録されています";
                }
            }
            
            if (!count($errors)) {
                $now = date('Y-m-d H:i:s');
                $actkey = Platy_Util::generateKey();
                $hashed_password = sha1($password);
                
                $sql = "INSERT INTO Platy_Member(email, password, status, created, actkey) VALUES ("
                     . "'{$email}', '{$hashed_password}', 'register', '{$now}', '{$actkey}');";
                $result = $db->query($sql);
                $id = $db->lastInsertId();
                
                echo 'actkey=' . $actkey . "<br />\n";
                
                // send E-Mail
                // TODO
                $mail_subject = $config['S_SITE_NAME'] . ':仮登録完了';
                $mail_to = $email;
                $mail_body = 
                    "仮登録が完了しました。以下のURLをクリックすると、正式登録が完了します。\n" .
                    BASE_FULL_URL . 'Member/activate/id/' . $id . '/actkey/' . $actkey . "\n\n";
                $ret = @mb_send_mail($mail_to, $mail_subject, $mail_body);
                
                //$this->_redirect('/');
                
                ob_start();
                
                echo '<h2>仮登録完了</h2>' . "\n";
                
                echo "仮登録が正常に完了しました。<br />\n";
                echo "仮登録完了のメールを送信しました。メールの内容にあるURLを開くと登録処理が完了します。<br />\n";
                
                // debug
                echo $mail_subject . "<br />\n";
                echo $mail_to . "<br />\n";
                echo $mail_body . "<br />\n";
                
                $contents = ob_get_contents();
                ob_end_clean();
                
                Zend_Loader::loadClass('Zend_View');
                $view = new Zend_View();
                $view->setScriptPath(APP_PATH . 'views');
                $view->contents = $contents;
                $view->config = $config;
                echo $view->render('page.php');
                
                return;
            }
        }
        else {
            $email  = '';
            $email2 = '';
            $password  = '';
            $password2 = '';
        }
        
        ob_start();
        
        echo '<h2>メンバー登録</h2>' . "\n";
        
        $error_msg = '';
        if (count($errors)) {
            $error_msg .= "<ul>\n";
            for ($i = 0; $i < count($errors); $i++) {
                $error_msg .= '<li>' . $errors[$i] . '</li>' . "\n";
            }
            $error_msg .= "</ul>\n";
            MsgBox($error_msg, "", "WARNING");
        }
        
        echo '<form method="post" action="">' . "\n";
        echo '<table class="form_table">' . "\n";
        echo '<tr><td>';
        echo 'Eメールアドレス</td><td>' . "\n";
        echo '<input type="text" name="email" value="' . $email . '" size="60" /></td></tr>' . "\n";
        echo '<tr><td>';
        echo '確認用 Eメールアドレス</td><td>' . "\n";
        echo '<input type="text" name="email2" value="' . $email2 . '" size="60" /></td></tr>' . "\n";
        echo '<tr><td>パスワード</td><td>' . "\n";
        echo '<input type="password" name="password" value="' . $password . '" size="60" /></td></tr>' . "\n";
        echo '<tr><td>確認用 パスワード</td><td>' . "\n";
        echo '<input type="password" name="password2" value="' . $password2 . '" size="60" /></td></tr>' . "\n";
        echo '<tr><td>画像認証</td><td>' . "\n";
        // captcha
        echo '<img src="' . BASE_URL . 'libs/kcaptcha/captcha.php' . '">' . "<br />\n";
        echo '上の画像にある文字列と同じ文字列を入力してください。' . "<br />\n";
        echo '<input type="text" name="captcha" size="10" />' . "\n";
        echo '</td></tr>';
        echo '<tr><td></td><td>';
        echo '<input type="submit" value="メンバー登録する" />' . "\n";
        echo '</td></tr></table>';
        echo '</form>' . "\n";
        
        $contents = ob_get_contents();
        ob_end_clean();
        
        Zend_Loader::loadClass('Zend_View');
        $view = new Zend_View();
        $view->setScriptPath(APP_PATH . 'views');
        $view->contents = $contents;
        $view->config = $config;
        echo $view->render('page.php');

    }
    
    /**
     * 会員の正式登録
     */
    public function activateAction()
    {
        global $db, $config;
        // id/[id]/actkey/[actkey]
        
        $request = $this->getRequest();
        $id = $request->getParam('id');
        $actkey = $request->getParam('actkey');
        
        $sql = "SELECT COUNT(*) FROM Platy_Member WHERE id={$id} AND actkey='{$actkey}' AND status='register'";
        $row = $db->fetchRow($sql);
        if ($row['COUNT(*)'] != 1) {
            
            ob_start();
            
            echo '<h2>メンバー登録</h2>' . "\n";
            echo 'メンバー登録に失敗しました。' . "<br />\n";
            
            $contents = ob_get_contents();
            ob_end_clean();
            
            Zend_Loader::loadClass('Zend_View');
            $view = new Zend_View();
            $view->setScriptPath(APP_PATH . 'views');
            $view->contents = $contents;
            $view->config = $config;
            echo $view->render('page.php');
            return;
        }
        else {
            $sql = "UPDATE Platy_Member SET status='active' WHERE id={$id}";
            $db->query($sql);
        }
        
        ob_start();
        
        echo '<h2>メンバー登録</h2>' . "\n";
        echo 'メンバー登録を完了しました' . "<br />\n";
        
        // debug
        $sql = "SELECT * FROM Platy_Member WHERE id={$id}";
        $row = $db->fetchRow($sql);
        var_dump($row);
        
        $contents = ob_get_contents();
        ob_end_clean();
        
        Zend_Loader::loadClass('Zend_View');
        $view = new Zend_View();
        $view->setScriptPath(APP_PATH . 'views');
        $view->contents = $contents;
        $view->config = $config;
        echo $view->render('page.php');
    }
    
    /**
     * プロフィール編集
     */
    public function editProfileAction()
    {
        global $db, $config, $Me;
        
        $id = $Me->id;
        
        $errors = array();
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            
            $new_email = h(e($_POST['new_email']));
            $new_password = h(e($_POST['new_password']));
            $new_password2 = h(e($_POST['new_password2']));
            $username = h(e($_POST['username']));
            
            $fullname = h(e($_POST['fullname']));
            $postcode = h(e($_POST['postcode']));
            $state = h(e($_POST['state']));
            $city = h(e($_POST['city']));
            $street = h(e($_POST['street']));
            $phone = h(e($_POST['phone']));
            $birth = h(e($_POST['birth']));
            $gender = h($_POST['gender']);
            //var_dump($_POST);
            
            // validation
            // TODO
            
            if (!count($errors)) {
                
                // Member_Profileにデータが無ければ作成する
                $sql = "SELECT id FROM Platy_Member_Profile WHERE id={$id}";
                $row = $db->fetchRow($sql);
                if ($row == false) {
                    $sql = "INSERT INTO Platy_Member_Profile(id) VALUES({$id})";
                    $db->query($sql);
                }
                
                $sql = "UPDATE Platy_Member SET "
                     . "email = '{$new_email}', username='{$username}'";
                $db->query($sql);
                
                if ($new_password != '') {
                    $hashed_new_password = sha1($new_password);
                    $sql = "UPDATE Platy_Member SET password='{$hashed_new_password}' WHERE id={$id}";
                    $db->query($sql);
                }
                
                $sql = "UPDATE Platy_Member_Profile SET "
                     . "fullname='{$fullname}', postcode='{$postcode}', "
                     . "state='{$state}', city='{$city}', street='{$street}',"
                     . "phone='{$phone}',"
                     . "birth='{$birth}' "
                     . "WHERE id={$id}";
                //echo $sql;
                $db->query($sql);
                
                $sql = "SELECT email FROM Platy_Member WHERE id={$id}";
                $row = $db->fetchRow($sql);
                $prev_email = $row['email'];
                
                if ($new_email != $prev_email) {
                    // Eメールアドレスが変更された
                    // 変更前のEメールアドレスに変更内容をメールする
                    // TODO
                    
                    
                    
                }
            }
        }
        else {
            $sql = "SELECT username, email FROM Platy_Member WHERE id={$id}";
            $row = $db->fetchRow($sql);
            $username = $row['username'];
            $new_email = $row['email'];
            $password = '';
            $password2 = '';
            $sql = "SELECT fullname, postcode, state, city, street, phone, birth, gender FROM Platy_Member_Profile WHERE id={$id}";
            //echo $sql;
            $row = $db->fetchRow($sql);
            //var_dump($row);
            $fullname = $row['fullname'];
            $postcode = $row['postcode'];
            $state = $row['state'];
            $city = $row['city'];
            $street = $row['street'];
            $phone = $row['phone'];
            $birth = $row['birth'];
            $gender = $row['gender'];
        }
        
        ob_start();
        
        echo '<h2>プロフィールの編集</h2>' . "\n";
        
        echo '<form method="post" action="">' . "\n";
        echo '<table class="form_table">' . "\n";
        echo '<tr><th>';
        echo 'Eメールアドレス</th><td>' . "\n";
        echo '<input type="text" name="new_email" value="' . $new_email . '" size="60" /></td></tr>' . "\n";
        echo '<tr><th>';
        echo '新しいパスワード</th><td>' . "\n";
        echo '<input type="password" name="new_password" value="' . $new_password . '" size="60" /></td></tr>' . "\n";
        echo '<tr><th>';
        echo '新しいパスワード(確認用)</th><td>' . "\n";
        echo '<input type="password" name="new_password2" value="' . $new_password2 . '" size="60" /></td></tr>' . "\n";
        echo '<tr><th>';
        echo 'ユーザ名</th><td>' . "\n";
        echo '<input type="text" name="username" value="' . $username . '" size="60" /></td></tr>' . "\n";
        
        echo '<tr><th>';
        echo 'お名前</th><td>' . "\n";
        echo '<input type="text" name="fullname" value="' . $fullname . '" size="60" /></td></tr>' . "\n";
        echo '<tr><th>';
        echo '郵便番号</th><td>' . "\n";
        echo '<input type="text" name="postcode" value="' . $postcode . '" size="12" /></td></tr>' . "\n";
        echo '<tr><th>';
        echo '都道府県</th><td>' . "\n";
        Platy_Form::select_state('state', $state);
        echo '</td></tr>' . "\n";
        echo '<tr><th>';
        echo '市区町村</th><td>' . "\n";
        echo '<input type="text" name="city" value="' . $city . '" size="60" /></td></tr>' . "\n";
        echo '<tr><th>';
        echo '番地</th><td>' . "\n";
        echo '<input type="text" name="street" value="' . $street . '" size="60" /></td></tr>' . "\n";
        echo '<tr><th>';
        echo '電話番号</th><td>' . "\n";
        echo '<input type="text" name="phone" value="' . $phone . '" size="20" /></td></tr>' . "\n";
        echo '<tr><th>';
        echo '誕生日</th><td>' . "\n";
        echo '<input type="text" name="birth" value="' . $birth . '" size="20" /></td></tr>' . "\n";
        echo '<tr><th>';
        echo '性別</th><td>' . "\n";
        echo '<input type="text" name="gender" value="' . $gender . '" size="20" /></td></tr>' . "\n";
        echo '<tr><th>';
        echo '顔アイコン</th><td>' . "\n";
        echo '<input type="file" name="icon" value="' . $icon . '" size="60" /></td></tr>' . "\n";
        echo '<tr><th>';
        echo '</th><td>' . "\n";
        echo '<input type="submit" value="プロフィールを更新する" /></td></tr>' . "\n";
        echo '</table>' . "\n";
        
        $contents = ob_get_contents();
        ob_end_clean();
        
        Zend_Loader::loadClass('Zend_View');
        $view = new Zend_View();
        $view->setScriptPath(APP_PATH . 'views');
        $view->contents = $contents;
        $view->config = $config;
        echo $view->render('page.php');
    }
    
    /**
     * プロフィール表示
     */
    public function viewProfileAction()
    {
        global $db, $config;
        
        ob_start();
        $contents = ob_get_contents();
        ob_end_clean();
        
        Zend_Loader::loadClass('Zend_View');
        $view = new Zend_View();
        $view->setScriptPath(APP_PATH . 'views');
        $view->contents = $contents;
        $view->config = $config;
        echo $view->render('page.php');
    }
    
    /**
     * パスワードの再発行
     * 
     */
    public function lostPasswordAction()
    {
        global $db, $config, $Me;
        
        $email = '';
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $email = h($_POST['email']);
            if ($email == '') {
                $errors[] = "Eメールアドレスを入力してください。";
            }
            else {
                $sql = "SELECT id, email FROM Platy_Member WHERE email='{$email}'";
                $row = $db->fetchRow($sql);
                if (is_array($row)) {
                    $new_password = Platy_Util::generateKey(8);
                    $hashed_new_password = sha1($new_password);
                    $sql = "UPDATE Platy_Member SET password='{$hashed_new_password}' WHERE email='{$email}'";
                    $db->query($sql);
                    
                    $to = $email;
                    $subject = 'PlatyCMS:パスワード再発行';
                    $message = 
                        "新しいパスワードをお送りします。\n" .
                        $new_password . "\n";
                    mb_send_mail($to, $subject, $message);
                }
                else {
                    // Eメールアドレスが登録されていない
                    $errors[] = "未登録のEメールアドレスです。";
                }
            }
        }
        
        ob_start();
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && count($errors) == 0) {
            echo '<h2>パスワードを再発行しました</h2>' . "\n";
            echo "あなたのメールボックスに新しいパスワードを送信しました。<br />\n";
            echo "メッセージを受け取ったら、その中にある新しいパスワードでログインしてください。<br />\n";
        }
        else {
            echo '<h2>パスワードを忘れましたか？</h2>' . "\n";
            
            if (count($errors)) {
                $error_msg .= "<ul>\n";
                for ($i = 0; $i < count($errors); $i++) {
                    $error_msg .= '<li>' . $errors[$i] . '</li>' . "\n";
                }
                $error_msg .= "</ul>\n";
                MsgBox($error_msg, "", "WARNING");
            }
            
            echo '<form method="post" action="">' . "\n";
            echo '<table class="form_table">' . "\n";
            echo '<tr><th>';
            echo 'Eメールアドレス</th><td>' . "\n";
            echo '<input type="text" name="email" value="' . $email . '" size="60" /></td></tr>' . "\n";
            echo '<tr><th></th><td>' . "\n";
            echo '<input type="submit" value="パスワードを再発行する" /></td></tr>' . "\n";
            echo '</table>' . "\n";
            echo '</form>' . "\n";
        }
        
        $contents = ob_get_contents();
        ob_end_clean();
        
        Zend_Loader::loadClass('Zend_View');
        $view = new Zend_View();
        $view->setScriptPath(APP_PATH . 'views');
        $view->contents = $contents;
        $view->config = $config;
        echo $view->render('page.php');
    }
}
?>