<?php
/**
 * Doc コンテンツタイプ
 */
require_once 'Zend/Db.php';
require_once 'Zend/Db/Table.php';
require_once 'Platy/CType.php';
require_once 'Platy/SystemDB.php';
require_once 'Platy/Form.php';

class Platy_CType_Doc extends Platy_CType
{
    function __construct($id = 0)
    {
        parent::__construct($id);
    }
    
    public function install() { return true; }
    
    public function uninstall() { return true; }
    
    /**
     * Form入力値のチェック
     */
    private function validate(&$errors)
    {
        $errors = array();
        $title = $_POST['title'];
        $summary = $_POST['summary'];
        if ($title == '') {
            $errors[] = "タイトルが未入力です";
        }
        if ($summary == '') {
            $errors[] = "概要が未入力です";
        }
        // startDate
        // TODO
        
        // endDate
        // TODO
        
        if (!count($errors)) {
            return true;
        }
        return false;
    }
    
    private function showForm($p, $mode = '')
    {
        global $manager;
        
        //echo 'startDate:' . $p['startDate'] . "<br />\n";
        //echo 'endDate:' . $p['endDate'] . "<br />\n";
        $p['startDate_date'] = substr($p['startDate'],  0, 10);
        $p['startDate_time'] = substr($p['startDate'], 11,  8);
        $p['endDate_date'] = substr($p['endDate'],  0, 10);
        $p['endDate_time'] = substr($p['endDate'], 11,  8);
        
        //addJS('js/prototype.js');
        //addJS('js/tabMaker.js');
?>
<form name="f" method="post" action="">
<table class="form_table">
<tr><th>name</th>
<td>
<input type="text" name="c_name" size="60" value="<?php echo $p['name'] ?>" />
<p class="hint">半角英数字。空欄にするとコンテンツIdになります。</p>
</td></tr>
<tr><th>タイトル<?php Platy_Form::form_required() ?></th>
<td><input type="text" name="title" size="60" value="<?php echo $p['title'] ?>" style="font-size:large;font-weight:bold;" /></td></tr>
<tr><td colspan="2">

<div class="tabheader">
<ul>
<li class="open" id="head1">
<a href="javascript:jstab_seltab('box', 'head', 10, 1)">概要</a>
</li>
<li class="close" id="head2">
<a href="javascript:jstab_seltab('box', 'head', 10, 2)">詳細</a>
</li>
</ul><!-- /tabheader -->

<div class="tabbody">
<div style="visibility: visible;" id="box1">
<?php Platy_Form::editor('summary', $p['summary'], 16) ?>
</div>
<div style="visibility: hidden; position: absolute;" id="box2">
<?php Platy_Form::editor('description', $p['description'], 16) ?>
</div>
</div><!-- /tabbody -->

</td></tr>

<tr><th>公開期間</th>
<td>開始日時
<input type="text" id="startDate_date" name="startDate_date" size="16" value="<?php echo $p['startDate_date'] ?>" />
<script type="text/javascript">
/*<[CDATA[*/
var dpck	= new DatePicker({
  relative	: 'startDate_date',
  language	: 'ja',
  keepFieldEmpty : true,
  disableFutureDate : false,
  enableCloseEffect : false,
  enableShowEffect : false,
});
  dpck.setDateFormat([ "yyyy", "mm", "dd" ], "-");
/*]]>*/
</script>
<input type="text" name="startDate_time" size="16" value="<?php echo $p['startDate_time'] ?>" />
&nbsp;～&nbsp;
終了日時
<input type="text" id="endDate_date" name="endDate_date" size="15" value="<?php echo $p['endDate_date'] ?>" />
<script type="text/javascript">
/*<[CDATA[*/
var dpck2	= new DatePicker({
  relative	: 'endDate_date',
  language	: 'ja',
  keepFieldEmpty : true,
  disableFutureDate : false,
  enableCloseEffect : false,
  enableShowEffect : false,
});
  dpck2.setDateFormat([ "yyyy", "mm", "dd" ], "-");
/*]]>*/
</script>
<input type="text" name="endDate_time" size="16" value="<?php echo $p['endDate_time'] ?>" />
</td></tr>
<tr><th>ステータス</th><td>
<?php Platy_Form::Manage_ContentStatus($this->id, $p['status']) ?>
</td></tr>
<?php
    if ($mode == 'add') {
        $manager->raiseEvent('AddContentFormExtras');
    }
    else if ($mode == 'edit') {
        $manager->raiseEvent('EditContentFormExtras');
    }
?>
<tr><th></th><td>
<input type="hidden" name="ContentType" value="Doc" />
<input type="submit" name="submit_content" /></td></tr>
</table>
</form>
<?php
    }
    
    public function add()
    {
        $p['name'] = '';
        $p['title'] = '';
        $p['summary'] = '';
        $p['description'] = '';
        $p['startDate'] = '';
        $p['endDate'] = '';
        
        echo '<h3>Docを作成</h3>' . "\n";
        $this->showForm($p, 'add');
    }
    
    public function saveAdd($parentId)
    {
        global $db, $Me, $maneger;
        
        $p['name'] = h($_POST['c_name']);
        $p['title'] = h($_POST['title']);
        //$summary = h($_POST['summary']);
        //$description = h($_POST['description']);
        $p['summary'] = $_POST['summary'];
        $p['description'] = $_POST['description'];
        $p['startDate'] = h($_POST['startDate_date'] . ' ' . $_POST['startDate_time']);
        $p['endDate'] = h($_POST['endDate_date'] . ' ' . $_POST['endDate_time']);
        $p['status'] = h($_POST['status']);
        $p['created'] = date('Y-m-d H:i:s');
        $p['modified'] = $p['created'];
        
        $errors = array();
        if ($this->validate($errors) == true) {
        
            $db->beginTransaction();

            try {
                // add to Content
                $table = new DbContentBase();
                $data = array(
                    'type'    => 'Doc',
                    'name'    => $p['name'],
                    'title'   => $p['title'],
                    'summary' => $p['summary'],
                    'description' => $p['description'],
                    'startDate' => $p['startDate'],
                    'endDate' => $p['endDate'],
                    'created' => $p['created'],
                    'modified' => $p['modified'],
                    'owner' => $Me->id,
                    'status' => $p['status']
                );
                //var_dump($data);
                $table->insert($data);
                
                $id = $db->lastInsertId();
                
                // もし$name==''ならば、$nameを{$id}に変更する
                if ($p['name'] == '') {
                    $c_name = $id;
                    $data = array('name' => $c_name);
                    $where = $table->getAdapter()->quoteInto('id = ?', $id);
                    $table->update($data, $where);
                }
                
                // add to Node
                $row = array (
                    'id'         => $id,
                    'parentId'   => $parentId
                );
                $table = 'Platy_Content_Node';
                $rows_affected = $db->insert($table, $row);
                
                $db->commit();
                
                $this->id = $id;    //+++
            }
            catch (Exception $e) {
                $profiler = $db->getProfiler();
                $query = $profiler->getLastQueryProfile();
                echo $query->getQuery();
                echo $e->getMessage();
                $db->rollBack();
            }
            return true;
        }
        else {
            echo '<h3>Docを作成</h3>' . "\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");
            }
            $this->showForm($p, 'add');
        }
    }
    
    public function edit($nodeId)
    {
        $p['name'] = $this->name;
        $p['title'] = $this->title;
        $p['summary'] = $this->summary;
        $p['description'] = $this->description;
        $p['created'] = $this->created;
        $p['modified'] = $this->modified;
        $p['startDate'] = $this->startDate;
        $p['endDate'] = $this->endDate;
        
        echo '<h3>Docを編集</h3>' . "\n";
        $this->showForm($p, 'edit');
    }
    
    public function saveEdit($nodeId)
    {
        global $db, $Me;
        
        $p['name'] = h($_POST['c_name']);
        $p['title'] = h($_POST['title']);
        //$p['summary'] = h($_POST['summary']);
        //$p['description'] = h($_POST['description']);
        $p['summary'] = $_POST['summary'];
        $p['description'] = $_POST['description'];
        $p['status'] = h($_POST['status']);
        $p['modified'] = date('Y-m-d H:i:s');
        $p['startDate'] = h($_POST['startDate_date'] . ' ' . $_POST['startDate_time']);
        $p['endDate'] = h($_POST['endDate_date'] . ' ' . $_POST['endDate_time']);
        
        $errors = array();
        if ($this->validate($errors) == true) {
        
            $db->beginTransaction();
            
            try {
                // update Content
                $table = new DbContentBase();
                
                if ($name == '') {
                    $name = $this->id;
                }
                
                $data = array(
                    'name'    => $p['name'],
                    'title'   => $p['title'],
                    'summary' => $p['summary'],
                    'description' => $p['description'],
                    'modified' => $p['modified'],
                    'startDate' => $p['startDate'],
                    'endDate' => $p['endDate'],
                    'status' => $p['status']
                );
                $where = $table->getAdapter()->quoteInto('id = ?', $this->id);
                $table->update($data, $where);
                
                $db->commit();
            }
            catch (Exception $e) {
                echo $e->getMessage();
                $db->rollBack();
            }
            return true;
        }
        else {
            echo '<h3>Docを編集</h3>' . "\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");
            }
            $this->showForm($p, 'edit');
        }
    }
    
    public function delete()
    {
        return true;
    }
    
    public function view($mode) {
        switch ($mode) {
        case 'description':
            return $this->view_description();
        default:
            return $this->view_summary();
        }
    }
    
    private function view_summary()
    {
        global $manager, $config;
        
        $a = array('pre'=>'', 'post'=>'', 'title'=> '', 'icons'=>'', 'main'=>'', 'header'=>'', 'footer'=>'');
        
        $link = getURLFromId($this->id);
        
        $a['title'] = '<a href="' . $link . '">' . $this->title . '</a>';
        
        ob_start();
        $manager->raiseEvent('PostContentTitle');
        $a['icons'] = ob_get_contents();
        ob_end_clean();
        
        ob_start();
        if ($config['S_CONTENT_AUTHOR'] == 1) {
            echo 'by&nbsp;';
            echo Platy_Util::getUsername($this->owner);
            echo '&nbsp;';
        }
        if ($config['S_CONTENT_DATE'] == 1) {
            echo 'at&nbsp;' . $this->modified;
            echo "&nbsp;";
        }
        $a['header'] = ob_get_contents();
        ob_end_clean();
        
        ob_start();
        echo $manager->parseCVar($this->summary);
        if (strlen($this->description) > 0) {
            echo '<div class="rightbox">';
            echo '<a href="' . $link . '">';
            echo 'もっと読む...';
            echo '</a>';
            echo '</div>';
        }
        $a['main'] = ob_get_contents();
        ob_end_clean();
        
        ob_start();
        $manager->raiseEvent('PostContentFooter');
        $a['footer'] = ob_get_contents();
        ob_end_clean();
        
        //ob_start();
        //$manager->raiseEvent('PostContent');
        //$a['post'] = ob_get_contents();
        //ob_end_clean();
        
        return $a;
    }
    
    private function view_description()
    {
        global $manager, $config;
        
        $a = array('pre'=>'', 'post'=>'', 'title'=> '', 'icons'=>'', 'main'=>'', 'header'=>'', 'footer'=>'');
        
        $link = getURLFromId($this->id);
        
        $a['title'] = $this->title;
        
        ob_start();
        $manager->raiseEvent('PostContentTitle');
        $a['icons'] = ob_get_contents();
        ob_end_clean();
        
        ob_start();
        if ($config['S_CONTENT_AUTHOR'] == 1) {
            echo 'by&nbsp;';
            echo Platy_Util::getUsername($this->owner);
            echo '&nbsp;';
        }
        if ($config['S_CONTENT_DATE'] == 1) {
            echo 'at&nbsp;' . $this->modified;
            echo "&nbsp;";
        }
        $a['header'] = ob_get_contents();
        ob_end_clean();
        
        ob_start();
        if (strlen($this->description) > 0) {
            echo $manager->parseCVar($this->description);
        }
        else {
            echo $manager->parseCVar($this->summary);
        }
        $a['main'] = ob_get_contents();
        ob_end_clean();
        
        ob_start();
        $manager->raiseEvent('PostContentFooter');
        $a['footer'] = ob_get_contents();
        ob_end_clean();
        
        ob_start();
        $manager->raiseEvent('PostContent');
        $a['post'] = ob_get_contents();
        ob_end_clean();
        
        return $a;
    }
    
    public function browse() {
        global $manager, $config;
        
        echo '<table class="form_table">' . "\n";
        echo '<tr><th>id</th><td>';
        echo $this->id;
        echo '</td></tr>' . "\n";
        echo '<tr><th>title</th><td>';
        echo $this->title;
        echo '</td></tr>' . "\n";
        echo '<tr><th>summary</th><td>';
        echo $this->summary;
        echo '</td></tr>' . "\n";
        echo '<tr><th>description</th><td>';
        echo $this->description;
        echo '</td></tr>' . "\n";
        echo '<tr><th>created</th><td>';
        echo $this->created;
        echo '</td></tr>' . "\n";
        echo '<tr><th>modified</th><td>';
        echo $this->modified;
        echo '</td></tr>' . "\n";
        echo '<tr><th>owner</th><td>';
        echo Platy_Util::getUsername($this->owner);
        echo '</td></tr>' . "\n";
        echo '<tr><th>status</th><td>';
        echo $this->status;
        echo '</td></tr>' . "\n";
        echo '</table>' . "\n";
        
        echo '<p><a href="javascript:history.back()">前のページにもどる</a></p>' . "\n";
    }
    
    public function getSummary()
    {
        return 'Document';
    }
    
    public function getVersion()
    {
        return '0.0.0';
    }
    
    public function getAuthor()
    {
        return 'Teruki Hosokawa';
    }
}
?>