<?php
/**
 * Shopモジュールの管理
 */
require_once 'Platy/Form.php';
require_once 'Zend/Controller/Action.php';
require_once 'Zend/Db.php';
require_once 'Zend/Db/Table.php';

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

class Manage_ShopController extends Zend_Controller_Action
{
    public function preDispatch()
    {
        global $Me;
        if ($Me->isAdmin() == false) {
            $this->_redirect('/Manage/Login/');
        }
    }
    
    public function indexAction()
    {
        $this->listorderAction();
    }
    
    public function configAction()
    {
        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 . 'Manage/views');
        $view->contents = $contents;
        $view->sidebar = $this->buildSidebar();
        echo $view->render('page.php');
    }
    
    public function noRouteAction()
    {
        //$this->_redirect('/');
        echo "noRouteAction";
    }
    
    /**
     * 商品一覧
     */
    public function listproductAction()
    {
        global $db, $config;
        
        ob_start();
        
        echo '<h2>ショップ管理</h2>' . "\n";
        echo '<h3>商品一覧</h3>' . "\n";
        
        $sql = "SELECT id, name, title, summary, description, image, price, modified FROM Platy_Shop_Item";
        $rows = $db->fetchAll($sql);
        
        echo '<table class="list_table">' . "\n";
        echo '<th>id</th><th>name</th><th>title</th><th>image</th><th>price</th><th>modified</th><th>action</th>' . "\n";
        for ($i = 0; $i < count($rows); $i++) {
            if ($i % 2 == 0) { echo '<tr class="even">'; }
            else { echo '<tr class="odd">'; }

            echo '<td>' . $rows[$i]['id'] . '</td>';
            echo '<td>' . $rows[$i]['name'] . '</td>';
            echo '<td>' . $rows[$i]['title'] . '</td>';
            echo '<td>' . $rows[$i]['image'] . '</td>';
            echo '<td>' . $this->cnv_currency($rows[$i]['price']) . '</td>';
            echo '<td>' . $rows[$i]['modified'] . '</td>';
            echo '<td>';
            echo '<a href="' . BASE_URL . 'Manage/Shop/editItem/id/' . $rows[$i]['id'] . '">編集</a>' . "\n";
            echo '&nbsp;';
            echo '<a href="' . BASE_URL . 'Manage/Shop/deleteItem/id/' . $rows[$i]['id'] . '">削除</a>' . "\n";
            echo '</td>';
            echo '</tr>';
        }
        echo '</table>' . "\n";
        
        echo '<a href="' . BASE_URL . 'Manage/Shop/addItem/">商品の追加</a>' . "\n";
        
        $contents = ob_get_contents();
        ob_end_clean();
        
        Zend_Loader::loadClass('Zend_View');
        $view = new Zend_View();
        $view->setScriptPath(APP_PATH . 'Manage/views');
        $view->contents = $contents;
        $view->sidebar = $this->buildSidebar();
        echo $view->render('page.php');
    }
    
    /**
     * 商品の追加フォームのチェック
     */
    private function validate_addItem(&$error)
    {
        $title = h($_POST['title']);
        $summary = h($_POST['summary']);
        $description = h($_POST['description']);
        $price = intval($_POST['price']);
        if ($title == '') {
            $error[] = '商品名称を入力してください';
        }
        if ($summary == '') {
            $error[] = '商品概要を入力してください';
        }
        if ($price == 0) {
            $error[] = '価格を入力してください';
        }
        if (count($error) > 0) {
            return false;
        }
        return true;
    }
    
    /**
     * 商品の登録
     */
    public function addItemAction()
    {
        global $db, $config;
        $error = array();
        
        ob_start();
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            
            $name = h($_POST['c_name']);
            $title = h($_POST['title']);
            $summary = h($_POST['summary']);
            $description = h($_POST['description']);
            $price = intval($_POST['price']);
            
            if ($this->validate_addItem($error)) {
            
                $uploaddir = BASE_PATH . 'media/Shop/';
                $uploadfile = $uploaddir . basename($_FILES['image']['name']);
                if (!move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
                    echo "Possible file upload attack!\n";
                }
                $image = basename($_FILES['image']['name']);
                $created = date('Y-m-d H:i:s');
                $modified = $created;
                
                $table = new DbShopItem();
                $data = array(
                    'name'    => '',
                    'title'   => $title,
                    'summary' => $summary,
                    'description' => $description,
                    'image' => $image,
                    'price' => $price,
                    'created' => $created,
                    'modified' => $modified
                );
                //var_dump($data);
                $table->insert($data);
                
                $contentId = $db->lastInsertId();
                $name = 'shopitem' . $contentId;
                $data = array('name' => $name);
                $where = $table->getAdapter()->quoteInto('id = ?', $contentId);
                $table->update($data, $where);
            
            }
            
        }
        else {
            $name = '';
            $title = '';
            $summary = '';
            $description = '';
            $price = '';
        }
        
        echo '<h2>ショップ管理</h2>' . "\n";
        echo '<h3>商品の登録</h3>' . "\n";
        
        if (count($error)) {
            $msg  = '入力内容にエラーがあります。以下の項目を修正してください。' . "\n";
            $msg .= '<ul><li>' . implode('</li><li>', $error) . '</li></ul>' . "\n";
            MsgBox($msg, "", "WARNING");
        }
        
        echo '<form method="post" enctype="multipart/form-data">' . "\n";
        echo '<table class="form_table">' . "\n";
        echo "<tr><th>商品名称:";
        Platy_Form::form_required();
        echo "</th>\n";
        echo '<td><input type="text" name="title" size="60" value="' . $title . '" />' . "</td></tr>\n";
        
        echo "<tr><th>商品概要:";
        Platy_Form::form_required();
        echo "</th>\n";
        echo "<td>";
        echo '<textarea name="summary" cols="60" rows="4">';
        echo $summary;
        echo '</textarea>' . "</td></tr>\n";
        echo "<tr><th>商品説明:</th>\n";
        echo "<td>";
        echo '<textarea name="description" cols="60" rows="6">';
        echo $description;
        echo '</textarea>' . "</td></tr>\n";
        
        echo "<tr><th>価格(円):";
        Platy_Form::form_required();
        echo "</th>\n";
        echo '<td><input type="text" name="price" size="20" ' . $price . '" />' . "</td></tr>\n";
        
        echo "<tr><th>画像:";
        Platy_Form::form_required();
        echo "</th>\n";
        echo '<td><input type="file" name="image" size="60" />' . "</td></tr>\n";
        
        echo "<tr><th></th>";
        echo '<td><input type="submit" value="商品を登録する" />' . "</td></tr>\n";
        echo "</table>";
        echo '</form>' . "\n";
        
        $contents = ob_get_contents();
        ob_end_clean();
        
        Zend_Loader::loadClass('Zend_View');
        $view = new Zend_View();
        $view->setScriptPath(APP_PATH . 'Manage/views');
        $view->contents = $contents;
        $view->sidebar = $this->buildSidebar();
        echo $view->render('page.php');
    }
    
    /**
     * 商品の編集
     */
    public function editItemAction()
    {
        global $db, $config;
        
        // id/[id]
        $request = $this->getRequest();
        $id = $request->getParam('id');
        
        ob_start();
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $name = h($_POST['c_name']);
            $title = h($_POST['title']);
            $summary = h($_POST['summary']);
            $description = h($_POST['description']);
            $price = intval($_POST['price']);
            
            //$uploaddir = BASE_PATH . 'media/Shop/';
            //$uploadfile = $uploaddir . basename($_FILES['image']['name']);
            //if (!move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
            //    echo "Possible file upload attack!\n";
            //}
            //$image = basename($_FILES['image']['name']);
            $modified = date('Y-m-d H:i:s');
            
            $sql = "UPDATE Platy_Shop_Item SET "
                 . "name = '{$name}',"
                 . "title = '{$title}',"
                 . "summary = '{$summary}',"
                 . "description = '{$description}',"
                 . "price = {$price},"
                 . "modified = '{$modified}' "
                 . "WHERE id={$id}";
            echo $sql . "<br />\n";
            $db->query($sql);
            
        }
        else {
            $sql = "SELECT name, title, summary, description, price, image, modified FROM Platy_Shop_Item WHERE id={$id}";
            $row = $db->fetchRow($sql);
            
            $name = $row['name'];
            $title = $row['title'];
            $summary = $row['summary'];
            $description = $row['description'];
            $price = $row['price'];
            $modified = $row['modified'];
        }
        
        echo '<h2>ショップ管理</h2>' . "\n";
        echo '<h3>商品の編集</h3>' . "\n";
        echo '<form method="post" enctype="multipart/form-data">' . "\n";
        
        echo "商品コード:<br />\n";
        echo '<input type="text" name="c_name" size="60" value="' . $name . '" />' . "<br />\n";
        echo "商品名称:<br />\n";
        echo '<input type="text" name="title" size="60" value="' . $title . '" />' . "<br />\n";
        
        echo "商品概要:<br />\n";
        echo '<textarea name="summary" cols="60" rows="4">';
        echo $summary;
        echo '</textarea>' . "<br />\n";
        
        echo "商品説明:<br />\n";
        echo '<textarea name="description" cols="60" rows="4">';
        echo $description;
        echo '</textarea>' . "<br />\n";

        echo "価格(円):<br />\n";
        echo '<input type="text" name="price" size="20" value="' . $price . '" />' . "<br />\n";
        
        echo "画像:<br />\n";
        if (strlen($image) > 0) {
            
        }
        echo '<input type="file" name="image" size="60" />' . "<br />\n";

        echo '<input type="submit" value="商品情報の更新" />' . "\n";
        echo '</form>' . "\n";
        
        
        $contents = ob_get_contents();
        ob_end_clean();
        
        Zend_Loader::loadClass('Zend_View');
        $view = new Zend_View();
        $view->setScriptPath(APP_PATH . 'Manage/views');
        $view->contents = $contents;
        $view->sidebar = $this->buildSidebar();
        echo $view->render('page.php');
    }
    
    /**
     * 商品の削除
     */
    public function deleteItemAction()
    {
        global $db;
        
        // id/[id]
        $request = $this->getRequest();
        $id = $request->getParam('id');
        
        $sql = "DELETE FROM Platy_Shop_Item WHERE id={$id}";
        $db->query($sql);
        
        
    }
    
    /**
     * 注文一覧
     */
    public function listorderAction()
    {
        global $db, $config;
        
        ob_start();
        
        echo '<h3>注文一覧</h3>' . "\n";
        
        $sql = "SELECT id, created, fullname, email, state, city, street, total, status, shipping_status, payment_status FROM Platy_Shop_Order ORDER BY created DESC";
        $rows = $db->fetchAll($sql);
        
        echo '<table class="list_table">' . "\n";
        echo '<tr><th>id</th><th>名前</th><th>合計金額</th><th>S注文</th><th>S配送</th><th>S入金</th><th>日時</th><th>action</th></tr>' . "\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 "\n";
            
            echo '<td>' . $row['id'] . '</td>' . "\n";
            echo '<td>' . $row['fullname'] . '</td>' . "\n";
            //echo '<td>' . $row['address'] . '</td>' . "\n";
            echo '<td>' . Platy_Util::cnv_currency($row['total']) . '</td>' . "\n";
            echo '<td>';
            echo $row['status'] . ':';
            if ($row['status'] == 0) { echo '受付'; }
            else if ($row['status'] == 1) { echo '完了'; }
            else if ($row['status'] == 9) { echo 'キャンセル'; }
            echo '</td>' . "\n";
            echo '<td>';
            echo $row['shipping_status'] . ':';
            if ($row['shipping_status'] == 0) { echo '未配送'; }
            else if ($row['shipping_status'] == 1) { echo '配送済'; }
            echo '</td>' . "\n";
            echo '<td>';
            echo $row['payment_status'] . ':';
            if ($row['payment_status'] == 0) { echo '未入金'; }
            else if ($row['payment_status'] == 1) { echo '入金済'; }
            echo '</td>' . "\n";
            echo '<td>' . $row['created'] . '</td>' . "\n";
            echo '<td>' . '<a href="' . BASE_URL . 'Manage/Shop/detailorder/id/' . $row['id'] . '">edit</a>' . '</td>' . "\n";
            echo '</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 . 'Manage/views');
        $view->contents = $contents;
        $view->sidebar = $this->buildSidebar();
        echo $view->render('page.php');
    }
    
    /**
     * 注文の詳細
     */
    public function detailorderAction()
    {
        global $db, $config;
        
        // id/[id]
        $request = $this->getRequest();
        $id = $request->getParam('id');
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $status = intval($_POST['status']);
            $shipping_status = intval($_POST['shipping_status']);
            $payment_status = intval($_POST['payment_status']);
            $sql = "UPDATE Platy_Shop_Order SET status={$status}, shipping_status={$shipping_status}, payment_status={$payment_status} WHERE id={$id}";
            $db->query($sql);
        }
        
        ob_start();
        
        echo '<h3>注文の詳細</h3>' . "\n";
        
        $sql = "SELECT id, created, fullname, email, state, city, street, postcode, total, status, shipping_status, payment_status FROM Platy_Shop_Order WHERE id=" . $id;
        
        $row = $db->fetchRow($sql);
        //var_dump($row);
        $total = $row['total'];
        $status = $row['status'];
        $shipping_status = $row['shipping_status'];
        $payment_status = $row['payment_status'];
        
        echo '<table class="form_table">' . "\n";
        echo '<tr><th>注文Id:</th><td>' . $row['id'] . '</td></tr>' . "\n";
        
        echo '<tr><th>ステータス:</th><td>';
        //echo $status . '|' . $shipping_status . '|' . $payment_status . "<br />\n";
        echo '<form method="post" action="">' . "\n";
        echo '注文ステータス:';
        echo '<select name="status">' . "\n";
        echo '<option value="0"';
        if ($status == 0) { echo ' selected'; }
        echo '>受注</option>' . "\n";
        echo '<option value="1"';
        if ($status == 1) { echo ' selected'; }
        echo '>完了</option>' . "\n";
        echo '<option value="9"';
        if ($status == 9) { echo ' selected'; }
        echo '>キャンセル</option>' . "\n";
        echo '</select>';
        echo '配送ステータス:';
        echo '<select name="shipping_status">' . "\n";
        echo '<option value="0"';
        if ($shipping_status == 0) { echo ' selected'; }
        echo '>未配送</option>' . "\n";
        echo '<option value="1"';
        if ($shipping_status == 1) { echo ' selected'; }
        echo '>配送済</option>' . "\n";
        echo '<option value="2"';
        if ($shipping_status == 2) { echo ' selected'; }
        echo '>配送完了</option>' . "\n";
        echo '</select>';
        echo '入金ステータス:';
        echo '<select name="payment_status">' . "\n";
        echo '<option value="0"';
        if ($payment_status == 0) { echo ' selected'; }
        echo '>未受領</option>' . "\n";
        echo '<option value="1"';
        if ($payment_status == 1) { echo ' selected'; }
        echo '>受領済</option>' . "\n";
        echo '</select>' . "<br />\n";
        echo '<input type="submit" value="ステータスを更新する" />' . "\n";
        echo '</form>' . "\n";
        echo '</td></tr>' . "\n";
        
        echo '<tr><th>注文日時:</th><td>' . $row['created'] . '</td></tr>' . "\n";
        
        echo '<tr><th>商品:</th><td>';
        $sql2 = "SELECT id, orderId, productId, qty, price, subtotal FROM Platy_Shop_Order_Product WHERE orderId=" . $id;
        
        $rows2 = $db->fetchAll($sql2);
        for ($i = 0; $i < count($rows2); $i++) {
            $row2 = $rows2[$i];
            //var_dump($row2);
            $sql3 = "SELECT title FROM Platy_Content_Base WHERE id=" . $row2['productId'];
            $row3 = $db->fetchRow($sql3);
            echo $row3['title'] . '&nbsp;x&nbsp;' . $row2['qty'];
            echo "<br />\n";
            echo Platy_Util::cnv_currency($row2['price']) . '&nbsp;x&nbsp;' . $row2['qty'] . '&nbsp;=&nbsp;' . Platy_Util::cnv_currency($row2['subtotal']);
            echo "<br />\n";
        }
        echo '合計:' . Platy_Util::cnv_currency($total) . "<br />\n";
        echo '</td></tr>' . "\n";
        
        // 注文者情報
        echo '<tr><th>お名前:</th><td>' . $row['fullname'] . '</td></tr>' . "\n";
        echo '<tr><th>郵便番号:</th><td>' . $row['postcode'] . '</td></tr>' . "\n";
        echo '<tr><th>住所:</th><td>';
        echo $row['state'] . "<br />\n";
        echo $row['city'] . "<br />\n";
        echo $row['street'] . "<br />\n";
        echo '</td></tr>' . "\n";
        echo '<tr><th>Eメールアドレス:</th><td>' . $row['email'] . '</td></tr>' . "\n";
        
        // 配送先情報
        // TODO
        
        echo '</table>' , "\n";

        $contents = ob_get_contents();
        ob_end_clean();
        
        Zend_Loader::loadClass('Zend_View');
        $view = new Zend_View();
        $view->setScriptPath(APP_PATH . 'Manage/views');
        $view->contents = $contents;
        $view->sidebar = $this->buildSidebar();
        echo $view->render('page.php');
    }
    
    /**
     * 支払方法
     */
    public function paymentAction()
    {
        global $db, $config;
        
        ob_start();
        
        echo '<h2>支払方法</h2>' . "\n";
        
        
        $contents = ob_get_contents();
        ob_end_clean();
        
        Zend_Loader::loadClass('Zend_View');
        $view = new Zend_View();
        $view->setScriptPath(APP_PATH . 'Manage/views');
        $view->contents = $contents;
        $view->sidebar = $this->buildSidebar();
        echo $view->render('page.php');
    }
    
    /**
     * 配送方法
     */
    public function shippingAction()
    {
        global $db, $config;
        
        ob_start();
        
        echo '<h2>配送方法</h2>' . "\n";
        
        $contents = ob_get_contents();
        ob_end_clean();
        
        Zend_Loader::loadClass('Zend_View');
        $view = new Zend_View();
        $view->setScriptPath(APP_PATH . 'Manage/views');
        $view->contents = $contents;
        $view->sidebar = $this->buildSidebar();
        echo $view->render('page.php');
    }
    
    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><a href="' . BASE_URL . 'Manage/Shop/listItem/">商品管理</a></li>' . "\n";
        echo '<li><a href="' . BASE_URL . 'Manage/Shop/listOrder/">注文管理</a></li>' . "\n";
        echo '<li><a href="' . BASE_URL . 'Manage/Shop/Payment/">支払方法</a></li>' . "\n";
        echo '<li><a href="' . BASE_URL . 'Manage/Shop/Shipping/">配送方法</a></li>' . "\n";
        echo '<li><a href="' . BASE_URL . 'Manage/Shop/Option/">オプション</a></li>' . "\n";
        echo '<li><a href="' . BASE_URL . 'Manage/Shop/config/">ショップ設定</a></li>' . "\n";

        echo '</ul>' . "\n";
        echo '</div>' . "\n";
        echo '</div>' . "<!-- /widget -->\n";
        
        $sidebar = ob_get_contents();
        ob_end_clean();
        
        return $sidebar;
    }
}
?>