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

class DbShopOrder extends Zend_Db_Table {
    protected function _setupTableName()
    {
        $this->_name = 'Platy_Shop_Order';
    }
}
class DbShopOrderProduct extends Zend_Db_Table {
    protected function _setupTableName()
    {
        $this->_name = 'Platy_Shop_Order_Product';
    }
}

class ShopController extends Zend_Controller_Action
{
    private $contents;
    
    public function preDispatch()
    {
        global $manager, $breadcrumb;
        
        $manager->module = 'Shop';
        $breadcrumb->add('ホーム', BASE_URL);
        $breadcrumb->add('ショップ', BASE_URL . 'Shop/');
    }
    
    public function indexAction()
    {
        global $db, $config, $breadcrumb;
        
        ob_start();
        
        echo '<h2>ショップ</h2>' . "\n";
        
        $contents = ob_get_contents();
        
        $sql = "SELECT id, name, title, summary, description FROM Platy_Content_Base WHERE type='Product'";
        $rows = $db->fetchAll($sql);
        
        foreach ($rows as $row) {
            
            $id = $row['id'];
            $sql2 = "SELECT image, selling_price, special_price FROM Platy_Content_Product WHERE id={$id}";
            $row2 = $db->fetchRow($sql2);
            
            echo '<div class="content">' . "\n";
            echo '<div class="title">';
            echo '<a href="' . BASE_URL . 'Shop/detailproduct/id/' . $row['id'] . '">';
            echo $row['title'];
            echo '</a>';
            echo '</div>' . "\n";
            
            echo '<div class="main">' . "\n";
            echo '<table><tr><td>';            
            echo '<image src="' . BASE_URL . 'media/Product/' . $row2['image'] . '">';
            echo '</td><td>';
            
            echo $row['summary'] . "<br />\n";
            echo '<strong>' . Platy_Util::cnv_currency($row2['selling_price']) . "</strong><br />\n";
            echo '<strong>' . Platy_Util::cnv_currency($row2['special_price']) . "</strong><br />\n";
            
            $id = $row['id'];
            echo '<form method="post" action="' . BASE_URL . 'Shop/addtocart/' . '">';
            echo '<input type="hidden" name="id" value="' . $id . '" />';
            echo '<input type="submit" value="カートに入れる">';
            echo '</form>';
            
            echo '</td></tr></table>' . "\n";
            echo '</div>' . "\n";
            
            echo '<div class="footer">' . '</div>' . "\n";
            echo '</div>', "\n";
        
        }
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * 商品一覧
     */
    public function listproductAction()
    {
    }
    
    /**
     * 商品の詳細
     */
    public function detailproductAction()
    {
        global $db, $config;
        
        ob_start();
        
        // id/[id]
        $request = $this->getRequest();
        $id = $request->getParam('id');
        
        $sql = "SELECT id, name, title, summary, description FROM Platy_Content_Base WHERE type='Product' AND id={$id}";
        $row = $db->fetchRow($sql);
        
        $sql2 = "SELECT image, selling_price, special_price FROM Platy_Content_Product WHERE id={$id}";
        $row2 = $db->fetchRow($sql2);


        echo '<div class="content">' . "\n";
        echo '<div class="title">';
        echo '<a href="' . BASE_URL . 'Shop/detailproduct/id/' . $row['id'] . '">';
        echo $row['title'];
        echo '</a>';
        echo '</div>' . "\n";
        
        echo '<div class="main">' . "\n";
        echo '<table><tr><td>';            
        echo '<image src="' . BASE_URL . 'media/Product/' . $row2['image'] . '">';
        echo '</td><td>';
        
        if ($row['description'] == '') {
            echo $row['summary'] . "<br />\n";
        }
        else {
            echo $row['description'] . "<br />\n";
        }
        
        echo '<strong>' . Platy_Util::cnv_currency($row2['selling_price']) . "</strong><br />\n";
        echo '<strong>' . Platy_Util::cnv_currency($row2['special_price']) . "</strong><br />\n";
        
        $id = $row['id'];
        echo '<form method="post" action="' . BASE_URL . 'Shop/addtocart/' . '">';
        echo '<input type="hidden" name="id" value="' . $id . '" />';
        echo '<input type="submit" value="カートに入れる">';
        echo '</form>';
        
        echo '</td></tr></table>' . "\n";
        echo '</div>' . "\n";
        
        echo '<div class="footer">' . '</div>' . "\n";
        echo '</div>', "\n";
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * カートに追加する
     */
    public function addtocartAction()
    {
        global $MyCart;
        
        $id = intval($_POST['id']);
        if (isset($_POST['qty'])) {
            $qty = intval($_POST['qty']);
        }
        else {
            $qty = 1;
        }
        $MyCart->add($id, $qty);
        
        $this->_redirect('Shop/cart/');
    }
    
    /**
     * カートから削除する
     */
    public function deletefromcartAction()
    {
        global $MyCart;
        
        // index/[index]
        $request = $this->getRequest();
        $index = $request->getParam('index');
        
        $MyCart->delete($index);
        $this->_redirect('Shop/cart/');
    }
    
    /**
     * カートの中身を表示する
     */
    public function cartAction()
    {
        global $db, $config, $MyCart;
        
        ob_start();
        
        echo '<h3>ショッピングカート</h3>' . "\n";
        
        $items = $MyCart->items();
        //var_dump($items);
        
        $total = 0;
        echo '<form method="post" action="' . BASE_URL . 'Shop/updatecart/">' . "\n";
        echo '<table class="list_table">' . "\n";
        echo '<th>id</th><th colspan="2">商品</th><th>単価</th><th>数量</th><th>小計</th>' . "\n";
        for ($i = 0; $i < count($items); $i++) {
            $val = $items[$i];
            echo '<tr>' . "\n";
            echo '<td>';
            echo $val['productId'];
            echo '</td>';
            echo '<td>';
            echo '<img src="' . BASE_URL . 'media/Product/Thumbnail/' . $val['image'] . '">';
            echo '</td>';
            echo '<td>';
            echo '<a href="' . BASE_URL . 'Shop/detailproduct/id/' . $val['itemId'] . '">';
            echo '<strong>' . $val['title'] . '</strong>' . "<br />\n";
            //echo $val['option_string'];
            echo '</a>';
            echo '</td>';
            echo '<td class="right">' . Platy_Util::cnv_currency($val['price']) . '</td>';
            echo '<td>';
            echo '<input type="text" name="qty[]" value="' . $val['qty'] . '" size="2">' . "<br />\n";
            echo '<a href="' . BASE_URL . 'Shop/deletefromcart/index/' . $val['index'] . '">' . '削除' . '</a>';
            echo '<input type="hidden" name="id[]" value="' . $val['index'] . '" />' . "\n";
            echo '</td>';
            $subtotal = $val['price'] * $val['qty'];
            $total += $subtotal;
            echo '<td class="right">' . Platy_Util::cnv_currency($subtotal) . '</td>';
            echo '</tr>' . "\n";
        }
        echo '<tr><td colspan="5">合計</td><td><strong>' . Platy_Util::cnv_currency($total) . '</strong></td></tr>' . "\n";
        echo '</table>' . "\n";
        echo '<input type="submit" name="update" value="カートを更新する" />' . "\n";
        echo '</form>';
        
        echo '<a href="' . BASE_URL . 'Shop/order/">注文する</a><br />' . "\n";
        echo '<a href="' . BASE_URL . 'Shop/">買い物を続ける</a><br />' . "\n";

        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * カートの更新
     */
    public function updatecartAction()
    {
        global $MyCart;
        for ($i = 0; $i < count($_POST['id']); $i++) {
            $id = intval($_POST['id'][$i]);
            $qty = intval($_POST['qty'][$i]);
            //echo $id . "|" . $qty . "<br />\n";
            if ($qty <= 0) {
                $MyCart->delete($id);
            }
            else {
                $MyCart->update($id, $qty);
            }
        }
        $this->_redirect('Shop/cart/');
    }
    
    public function noRouteAction()
    {
        //$this->_redirect('/');
        echo "noRouteAction";
    }
    
    /**
     * 個人情報の入力チェック
     */
    private function validateOrder()
    {
    }
    
    /**
     * 注文入力のチェック
     */
    public function orderValidation(&$error)
    {
        global $db, $config;
        
        if (h($_POST['fullname']) == '') {
            $error[] = "お名前が未入力です";
        }
        if (h($_POST['email']) == '') {
            $error[] = "Eメールアドレスが未入力です";
        }
        if (count($error)) {
            return false;
        }
        return true;
    }
    
    /**
     * 注文,個人情報入力
     */
    public function orderAction()
    {
        global $db, $config, $MyCart;
        $error = array();
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            
            $fullname = h(e($_POST['fullname']));
            $email = h(e($_POST['email']));
            $postcode = h(e($_POST['postcode']));
            $state = h(e($_POST['state']));
            $city = h(e($_POST['city']));
            $street = h(e($_POST['street']));
            $phone = h($_POST['phone']);
            $delivery = h($_POST['delivery']);
            $delivery_fullname = h(e($_POST['delivery_fullname']));
            $delivery_email = h(e($_POST['delivery_email']));
            $delivery_postcode = h(e($_POST['delivery_postcode']));
            $delivery_state = h(e($_POST['delivery_state']));
            $delivery_city = h(e($_POST['delivery_city']));
            $delivery_street = h(e($_POST['delivery_street']));
            $delivery_phone = h($_POST['delivery_phone']);
            
            if ($this->orderValidation($error) == true) {
                // 注文確認画面表示
                ob_start();
                
                echo '<h2>注文内容の確認</h2>' . "\n";
                $this->CartSummary();
                
                echo '<table class="form_table">' . "\n";
                echo '<tr><th>お名前</th><td>';
                echo $fullname;
                echo '</td></tr>' . "\n";
                echo '<tr><th>Eメールアドレス</th><td>';
                echo $email;
                echo '</td></tr>' . "\n";
                echo '<tr><th>郵便番号</th><td>';
                echo $postcode;
                echo '</td></tr>' . "\n";
                echo '<tr><th>都道府県</th><td>';
                echo $state;
                echo '</td></tr>' . "\n";
                echo '<tr><th>市区町村</th><td>';
                echo $city;
                echo '</td></tr>' . "\n";
                echo '<tr><th>番地</th><td>';
                echo $street;
                echo '</td></tr>' . "\n";
                
                
                echo '<tr><th>電話番号</th><td>';
                echo $phone;
                echo '</td></tr>' . "\n";
                
                echo '</table>' . "\n";
                
                echo '<form method="post" action="' . BASE_URL . 'Shop/orderComplete/">' . "\n";
                echo '<input type="hidden" name="fullname" value="' . $fullname . '" />' . "\n";
                echo '<input type="hidden" name="email" value="' . $email . '" />' . "\n";
                echo '<input type="hidden" name="postcode" value="' . $postcode . '" />' . "\n";
                echo '<input type="hidden" name="state" value="' . $state . '" />' . "\n";
                echo '<input type="hidden" name="city" value="' . $city . '" />' . "\n";
                echo '<input type="hidden" name="street" value="' . $street . '" />' . "\n";
                echo '<input type="hidden" name="phone" value="' . $phone . '" />' . "\n";
                
                echo '<input type="hidden" name="delivery" value="' . $delivery . '" />' . "\n";
                echo '<input type="hidden" name="delivery_fullname" value="' . $delivery_fullname . '" />' . "\n";
                echo '<input type="hidden" name="delivery_email" value="' . $delivery_email . '" />' . "\n";
                echo '<input type="hidden" name="delivery_postcode" value="' . $delivery_postcode . '" />' . "\n";
                echo '<input type="hidden" name="delivery_state" value="' . $delivery_state . '" />' . "\n";
                echo '<input type="hidden" name="delivery_city" value="' . $delivery_city . '" />' . "\n";
                echo '<input type="hidden" name="delivery_street" value="' . $delivery_street . '" />' . "\n";
                echo '<input type="hidden" name="delivery_phone" value="' . $delivery_phone . '" />' . "\n";
                
                echo '<input type="submit" value="注文を確定する" />' . "\n";
                echo '</form>' . "\n";
                
                $this->contents = ob_get_contents();
                ob_end_clean();
                
                $this->view();
                
                return;
            }
        }
        else {
            $fullname = '';
            $email = '';
            $postcode = '';
            $state = '';
            $city = '';
            $street = '';
            $phone = '';
        }
        
        ob_start();
        
        echo '<h3>お客様情報の入力</h3>' . "\n";
        
        $items = $MyCart->items();
        //var_dump($MyCart);
        
        if (count($error)) {
            $msg  = '入力内容にエラーがあります。以下の項目を修正してください。' . "\n";
            $msg .= '<ul><li>' . implode('</li><li>', $error) . '</li></ul>' . "\n";
            MsgBox($msg, "", "WARNING");
        }
        
        echo '<form method="post" action="">' . "\n";
        
        echo '<table class="form_table">' . "\n";
        echo '<tr><th>お名前 *</th>';
        echo '<td><input type="text" name="fullname" value="' . $fullname . '" size="32" />' . "</td></tr>\n";
        echo '<tr><th>Eメールアドレス *</th>';
        echo '<td><input type="text" name="email" value="' . $email . '" size="64" />' . "</td></tr>\n";
        echo '<tr><th>郵便番号 *</th>';
        echo '<td><input type="text" name="postcode" value="' . $postcode . '" size="8" />' . "</td></tr>\n";
        echo '<tr><th>都道府県 *</th>';
        echo '<td><input type="text" name="state" value="' . $state . '" size="64" />' . "</td></tr>\n";
        echo '<tr><th>市区町村 *</th>';
        echo '<td><input type="text" name="city" value="' . $city . '" size="64" />' . "</td></tr>\n";
        echo '<tr><th>番地 *</th>';
        echo '<td><input type="text" name="street" value="' . $street . '" size="64" />' . "</td></tr>\n";
        echo '<tr><th>電話番号 *</th>';
        echo '<td><input type="text" name="phone" value="' . $phone . '" size="16" />' . "</td></tr>\n";
        
        // 配送先の指定
        echo '<tr><th>配送先</th>';
        echo '<td><input type="checkbox" name="delivery" />';
        echo '配送先を指定する' . "</td></tr>\n";
        
        echo '<tr><th>配送先のお名前</th>';
        echo '<td><input type="text" name="delivery_name" value="' . $delivery_name . '" size="32" />' . "</td></tr>\n";
        echo '<tr><th>配送先の郵便番号</th>';
        echo '<td><input type="text" name="delivery_postcode" value="' . $delivery_postcode . '" size="8" />' . "</td></tr>\n";
        echo '<tr><th>配送先の都道府県</th>';
        echo '<td><input type="text" name="delivery_state" value="' . $delivery_address . '" size="64" />' . "</td></tr>\n";
        echo '<tr><th>配送先の市区町村</th>';
        echo '<td><input type="text" name="delivery_city" value="' . $delivery_city . '" size="64" />' . "</td></tr>\n";
        echo '<tr><th>配送先の番地</th>';
        echo '<td><input type="text" name="delivery_street" value="' . $delivery_street . '" size="64" />' . "</td></tr>\n";
        echo '<tr><th>配送先の電話番号:</th>';
        echo '<td><input type="text" name="delivery_phone" value="' . $delivery_phone . '" size="16" />' . "</td></tr>\n";
        
        echo '<tr><th></th>';
        echo '<td><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 ordercompleteAction()
    {
        global $db, $config, $MyCart;
        
        $fullname = h($_POST['fullname']);
        $email = h($_POST['email']);
        $postcode = h($_POST['postcode']);
        $state = h($_POST['state']);
        $city = h($_POST['city']);
        $street = h($_POST['street']);
        $phone = h($_POST['phone']);
        
        $delivery = intval($_POST['delivery']);
        $delivery_fullname = h($_POST['delivery_fullname']);
        $delivery_postcode = h($_POST['delivery_postcode']);
        $delivery_state = h($_POST['delivery_state']);
        $delivery_city = h($_POST['delivery_city']);
        $delivery_street = h($_POST['delivery_street']);
        $delivery_phone = h($_POST['delivery_phone']);
        //$payment = intval($_POST['payment']);
        //$shipping = intval($_POST['shipping']);
        
        $ShopOrder = new DbShopOrder();
        $order = $ShopOrder->createRow();
        $order->fullname = $fullname;
        $order->email = $email;
        $order->postcode = $postcode;
        $order->state = $state;
        $order->city = $city;
        $order->street = $street;
        $order->phone = $phone;
        $order->delivery = $delivery;
        if ($delivery == 1) {
            $order->delivery_fullname = $delivery_fullname;
            $order->delivery_postcode = $delivery_postcode;
            $order->delivery_state = $delivery_state;
            $order->delivery_city = $delivery_city;
            $order->delivery_street = $delivery_street;
            $order->delivery_phone = $delivery_phone;
        }
        $order->created = date('Y-m-d H:i:s');
        $order->modified = date('Y-m-d H:i:s');
        $order->save();
        $orderId = $order->id;
        
        $total = 0;
        $items = $MyCart->items();
        foreach ($items as $key => $val) {
            $subtotal = $val['price'] * $val['qty'];
            $total += $subtotal;
            $ShopOrderProduct = new DbShopOrderProduct();
            $item = $ShopOrderProduct->createRow();
            $item->orderId = $orderId;
            $item->productId = $val['productId'];
            $item->price = $val['price'];
            $item->qty = $val['qty'];
            $item->subtotal = $subtotal;
            $item->save();
            $itemId = $item->id; // get id
        }
        $order->total = $total;
        $order->save();
        
        // メール送信
        // TODO
        
        $MyCart->clear();
        
        ob_start();
        
        echo '<h3>注文完了</h3>' . "\n";
        echo '当店をご利用いただきまして誠にありがとうございました。<br />' . "\n";
        echo 'ただいまお客様のメールアドレスに、ご注文内容を送信しました。<br />' . "\n";
        echo '今後ともよろしくお願い申し上げます。<br />' . "\n";
        
        $this->contents = ob_get_contents();
        ob_end_clean();
        
        $this->view();
    }
    
    /**
     * カートの中身を表示する
     */
    public function CartSummary() {
        global $db, $config, $MyCart;

        $items = $MyCart->items();
        //var_dump($MyCart);
        
        $total = 0;
        echo '<table class="list_table">' . "\n";
        echo '<th>id</th><th colspan="2">商品</th><th>単価</th><th>数量</th><th>小計</th>' . "\n";
        for ($i = 0; $i < count($items); $i++) {
            $val = $items[$i];
            echo '<tr>' . "\n";
            echo '<td>';
            echo $val['itemId'];
            echo '</td>';
            echo '<td>';
            echo '<img src="' . BASE_URL . 'media/Shop/' . $val['image'] . '" width="48" height="48">';
            echo '</td>';
            echo '<td>';
            echo '<a href="' . BASE_URL . 'Shop/detailproduct/id/' . $val['itemId'] . '">';
            echo '<strong>' . $val['title'] . '</strong>' . "<br />\n";
            //echo $val['option_string'];
            echo '</a>';
            echo '</td>';
            echo '<td class="right">' . Platy_Util::cnv_currency($val['price']) . '</td>';
            echo '<td>';
            echo $val['qty'];
            echo '</td>';
            
            $subtotal = $val['price'] * $val['qty'];
            $total += $subtotal;
            echo '<td class="right">' . Platy_Util::cnv_currency($subtotal) . '</td>';
            echo '</tr>' . "\n";
        }
        echo '<tr><td colspan="5">合計</td><td><strong>' . Platy_Util::cnv_currency($total) . '</strong></td></tr>' . "\n";
        echo '</table>' . "\n";
    }
    
    /**
     * 表示
     */
    private function view()
    {
        global $breadcrumb, $config;
        
        Zend_Loader::loadClass('Zend_View');
        $view = new Zend_View();
        $view->setScriptPath(APP_PATH . 'views');
        $view->config = $config;
        $view->contents = $this->contents;
        $view->breadcrumb = $breadcrumb->getContents();
        $view->sidebar = buildSidebar();
        echo $view->render('page.php');
    }
}
?>