<?php
/**
 * Product コンテンツタイプ
 */
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';
require_once 'Platy/ImageHelper.php';

class DbContentProduct extends Zend_Db_Table {
    protected function _setupTableName()
    {
        $this->_name = 'Platy_Content_Product';
    }
}

class Platy_CType_Product extends Platy_CType
{
    public $image;
    public $selling_price;
    public $cost_price;
    public $special_price;
    public $featured;
    public $featured_text;
    public $weight;
    public $stock;
    public $url;
    
    function __construct($id = 0) {
        global $db;
        
        parent::__construct($id);
        
        $this->image = '';
        $this->selling_price = 0;
        $this->cost_price = 0;
        $this->special_price = 0;
        $this->featured = 0;
        $this->featured_text = '';
        $this->weight = 0.0;
        $this->stock = 0;
        $this->url = '';
        
        if ($id > 0) {
            $table = new DbContentProduct();
            $row = $table->fetchRow('id = ' . $id);
            $this->image = $row->image;
            $this->selling_price = $row->selling_price;
            $this->cost_price = $row->cost_price;
            $this->special_price = $row->special_price;
            $this->featured = $row->featured;
            $this->featured_text = $row->featured_text;
            $this->weight = $row->weight;
            $this->stock = $row->stock;
            $this->url = $row->url;
        }
    }
    
    public function install() {
        global $db;
        $sql = "CREATE TABLE Platy_Content_Product ("
               . "id            integer PRIMARY KEY,"
               . "image         varchar(255),"
               . "selling_price int DEFAULT 0,"
               . "cost_price    int DEFAULT 0,"
               . "special_price int DEFAULT 0,"
               . "featured      int DEFAULT 0,"
               . "featured_text text,"
               . "weight        double DEFAULT 0.0,"
               . "stock         int DEFAULT 0,"
               . "url           varchar(255));";
        try {
            $result = $db->query($sql);
        }
        catch (Exception $e) {
            $profiler = $db->getProfiler();
            $query = $profiler->getLastQueryProfile();
            echo $query->getQuery();
            echo $e->getMessage();
            return false;
        }
        @mkdir(BASE_PATH . 'media/Product/');
        @mkdir(BASE_PATH . 'media/Product/Thumbnail/');
        @mkdir(BASE_PATH . 'media/Product/Small/');
        
        return true;
    }
    
    public function uninstall() {
        global $db;
        $sql = "DROP TABLE Platy_Content_Product;";
        $db->query($sql);
        /**
         * rmdir()は空ディレクトリでないと削除できない。
         * すべての画像を削除しておく必要がある
         */
        // TODO
        
        @rmdir(BASE_PATH . 'media/Product/Thumbnail/');
        @rmdir(BASE_PATH . 'media/Product/Small/');
        @rmdir(BASE_PATH . 'media/Product/');
        
        return true;
    }
    
    private function validate(&$errors)
    {
        $errors = array();
        $title = $_POST['title'];
        $summary = $_POST['summary'];
        if ($title == '') {
            $errors[] = "タイトルが未入力です";
        }
        if ($summary == '') {
            $errors[] = "概要が未入力です";
        }
        if (!count($errors)) {
            return true;
        }
        return false;
    }
    
    private function showForm($p, $mode = '')
    {
        global $manager;
        
        //addJS('js/prototype.js');
        //addJS('js/tabMaker.js');
?>
<form name="f" method="post" action="" enctype="multipart/form-data">
<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>画像<?php Platy_Form::form_required() ?></th>
<td><input type="file" name="image" size="60" /></td></tr>

<tr><th>商品URL</th>
<td>
<input type="text" name="url" size="60" value="<?php echo $p['url'] ?>" />
</td></tr>

<tr><th>価格</th>
<td>
販売価格(円)<?php Platy_Form::form_required() ?>
<input type="text" name="selling_price" size="16" value="<?php echo $p['selling_price'] ?>" />
 / 仕入価格(円)
<input type="text" name="cost_price" size="16" value="<?php echo $p['cost_price'] ?>" />
 / 特別価格(円)
<input type="text" name="special_price" size="16" value="<?php echo $p['special_price'] ?>" />
</td></tr>

<tr><th>おすすめ</th>
<td>
<input type="checkbox" name="featured" />おすすめ商品<br />
<textarea name="featured_text" rows="3" cols="50"><?php echo $p['featured_text'] ?></textarea>
</td></tr>

<tr><th></th>
<td>
在庫数<input type="text" name="stock" size="8" value="<?php echo $p['stock'] ?>" />
 / 重量<input type="text" name="weight" size="16" value="<?php echo $p['weight'] ?>" />
</td></tr>

<tr><th>公開期間</th>
<td>開始日時<input type="text" name="startDate" size="30" value="<?php echo $p['startDate'] ?>" />
<input type="button" value="..." onclick="dateinput(this.form.startDate)" />&nbsp;～&nbsp;
終了日時<input type="text" name="endDate" size="30" value="<?php echo $p['endDate'] ?>" />
<input type="button" value="..." onclick="dateinput(this.form.endDate)" /></td></tr>
<tr><th>ステータス</th><td>
<?php
Platy_Form::Manage_ContentStatus($this->id, $p['status']);
//<select name="status">
//<option value="public">公開</option>
//<option value="pending">提出</option>
//<option value="private">下書き</option>
//</select>
?>
</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="Product" />
<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'] = '';
        
        $p['selling_price'] = '';
        $p['cost_price'] = '';
        $p['special_price'] = '';
        $p['featured'] = 0;
        $p['featured_text'] = '';
        $p['weight'] = '';
        $p['stock'] = '';
        $p['url'] = '';
        
        echo '<h3>Productを作成</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']);
        $p['endDate'] = h($_POST['endDate']);
        $p['status'] = h($_POST['status']);
        $p['created'] = date('Y-m-d H:i:s');
        $p['modified'] = $p['created'];
        
        $image = basename($_FILES['image']['name']);
        $p['selling_price'] = intval($_POST['selling_price']);
        $p['cost_price'] = intval($_POST['cost_price']);
        $p['special_price'] = intval($_POST['special_price']);
        $p['featured'] = intval($_POST['featured']);
        $p['featured_text'] = h($_POST['featured_text']);
        $p['weight'] = floatval($_POST['weight']);
        $p['stock'] = intval($_POST['stock']);
        $p['url'] = h($_POST['url']);
        
        $errors = array();
        if ($this->validate($errors) == true) {
        
            $db->beginTransaction();

            try {
                // add to Content
                $table = new DbContentBase();
                $data = array(
                    'type'    => 'Product',
                    '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();
                echo "new_id=" . $id . "<br />\n";
                
                // add To Product
                $table_product = new DbContentProduct();
                $data = array(
                    'id'       => $id,
                    'image'    => $image,
                    'selling_price' => $p['selling_price'],
                    'cost_price' => $p['cost_price'],
                    'special_price' => $p['special_price'],
                    'featured' => $p['featured'],
                    'featured_text' => $p['featured_text'],
                    'weight' => $p['weight'],
                    'stock' => $p['weight'],
                    'url' => $p['url']
                );
                var_dump($data);
                $table_product->insert($data);
                
                // upload image file
                $uploaddir = BASE_PATH . 'media/Product/';
                $uploadfile = $uploaddir . basename($_FILES['image']['name']);
                if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
                    echo "File is valid, and was successfully uploaded.\n";
                } else {
                    echo "Possible file upload attack!\n";
                }
                $image_helper = new ImageHelper();
                $newfile = BASE_PATH . 'media/Product/Small/' . basename($_FILES['image']['name']);
                $image_helper->resize($uploadfile, $newfile, 240, 180);
                $newfile = BASE_PATH . 'media/Product/Thumbnail/' . basename($_FILES['image']['name']);
                $image_helper->resize($uploadfile, $newfile, 100, 75);
                
                // もし$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>Productを作成</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;
        
        $image = $this->image;
        $p['selling_price'] = '';
        $p['cost_price'] = '';
        $p['special_price'] = '';
        $p['featured'] = 0;
        $p['featured_text'] = '';
        $p['weight'] = '';
        $p['stock'] = '';
        $p['url'] = '';
        
        echo '<h3>Productを編集</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']);
        $p['endDate'] = h($_POST['endDate']);
        $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>Productを編集</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()
    {
        global $db;
        
        @unlink(BASE_PATH . 'media/Product/' . $this->image);
        @unlink(BASE_PATH . 'media/Product/Thumbnail/' . $this->image);
        @unlink(BASE_PATH . 'media/Product/Small/' . $this->image);
        $sql = "DELETE FROM Platy_Content_Product WHERE id={$this->id}";
        echo $sql . "<br />\n";
        $db->query($sql);
        
        return true;
    }
    
    public function view($mode) {
        switch ($mode) {
        case 'description':
            return $this->view_description();
        default:
            return $this->view_summary();
        }
    }
    
    public 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 '<table><tr><td>';
        echo '<image src="' . BASE_URL . 'media/Product/Small/' . $this->image . '">';
        echo '</td><td>';
        
        echo $manager->parseCVar($this->summary);
        if (strlen($this->description) > 0) {
            //echo "<br />\n";
            echo '<div class="rightbox">';
            echo '<a href="' . $link . '">';
            echo 'もっと読む...';
            echo '</a>';
            echo '</div>';
        }
        if ($this->special_price <= 0) {
            echo Platy_Util::cnv_currency($this->selling_price) . "<br />\n";
        }
        else {
            echo Platy_Util::cnv_currency($this->special_price) . "<br />\n";
        }
        
        echo '<form method="post" action="' . BASE_URL . 'Shop/addtocart/' . '">' . "\n";
        echo '<input type="hidden" name="id" value="' . $this->id . '" />' . "\n";
        echo '<input type="submit" value="カートに入れる">' . "\n";
        echo '</form>' . "\n";
        
        echo '</td></tr></table>' . "\n";
        $a['main'] = ob_get_contents();
        ob_end_clean();
        
        echo '</div>' . "\n";
        
        ob_start();
        $manager->raiseEvent('PostContentFooter');
        $a['post'] = ob_get_contents();
        ob_end_clean();
        
        return $a;
    }
    
    public 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();
        echo '<table><tr><td>';
        echo '<image src="' . BASE_URL . 'media/Product/Small/' . $this->image . '">';
        echo '</td><td>';
        
        if (strlen($this->description) > 0) {
            echo $manager->parseCVar($this->description);
        }
        else {
            echo $manager->parseCVar($this->summary);
        }
        
        if ($this->special_price <= 0) {
            echo '<strong>' . Platy_Util::cnv_currency($this->selling_price) . "</strong><br />\n";
        }
        else {
            echo '<strong>' . Platy_Util::cnv_currency($this->special_price) . "</strong><br />\n";
        }
        
        echo '<form method="post" action="' . BASE_URL . 'Shop/addtocart/' . '">' . "\n";
        echo '<input type="hidden" name="id" value="' . $this->id . '" />' . "\n";
        echo '<input type="submit" value="カートに入れる">' . "\n";
        echo '</form>' . "\n";
        
        echo '</td></tr></table>' . "\n";
        
        $a['main'] = ob_get_contents();
        ob_end_clean();
        
        echo '<div class="footer">' . "\n";
        echo '</div>' . "\n";
        
        echo '</div>', "\n";
        
        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 '商品';
    }
    
    public function getVersion()
    {
        return '0.0.0';
    }
    
    public function getAuthor()
    {
        return 'Teruki Hosokawa';
    }
}
?>