<?php 
 
/* 
 * This file is part of EC-CUBE 
 * 
 * Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved. 
 * 
 * http://www.ec-cube.co.jp/ 
 * 
 * For the full copyright and license information, please view the LICENSE 
 * file that was distributed with this source code. 
 */ 
 
namespace Customize\Controller\Mypage; 
 
use Carbon\Carbon; 
use Customize\Controller\LM\LmAbstractController; 
use Customize\Event\LmEvents; 
use Customize\Service\CommonService; 
use Customize\Service\FavoriteService; 
use Customize\Service\ImageService; 
use Customize\Service\LmHelper; 
use Customize\Service\MobileDetector as LmMobileDetector; 
use Eccube\Entity\Customer; 
use Customize\Entity\CustomerFavoriteProductTrait; 
use Eccube\Entity\CustomerFavoriteProduct; 
use Eccube\Entity\Product; 
use Eccube\Event\EccubeEvents; 
use Eccube\Event\EventArgs; 
use Customize\Repository\CustomerFavoriteProductRepository; 
use Eccube\Form\Type\Front\CustomerLoginType; 
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; 
use Symfony\Component\Routing\Annotation\Route; 
use Customize\Service\CustomerService; 
use Customize\Service\OrderService; 
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; 
use Customize\Controller\ApiController; 
use Knp\Component\Pager\PaginatorInterface; 
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; 
use Lm\Service\Store\FileStoreService; 
use Symfony\Component\HttpFoundation\StreamedResponse; 
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils; 
use Lm\Engine\Zaiko\Entity\SkuExtended; 
use Lm\Entity\GoodsColor; 
use Lm\Entity\GoodsPrice; 
use Lm\Service\Coupon\Coupon; 
class MypageController extends LmAbstractController 
{ 
    protected $CommonService; 
    protected $CustomerService; 
    protected $OrderService; 
 
    /** 
     * @var CustomerFavoriteProductRepository 
     */ 
    protected $customerFavoriteProductRepository; 
 
    protected $CFIMG_URL = "https://img0.land-mark.biz/ut_img"; 
 
    /** 
     * @var LmMobileDetector 
     */ 
    private $mobileDetector; 
 
    /** 
     * @var FavoriteService 
     */ 
    private $favoriteService; 
 
    public function __construct( 
        CustomerFavoriteProductRepository $customerFavoriteProductRepository, 
        CommonService   $commonService, 
        LmHelper        $lmHelper, 
        CustomerService $CustomerService, 
        OrderService    $OrderService, 
        LmMobileDetector       $mobileDetector, 
        FavoriteService $favoriteService 
    ) 
    { 
        // 
        parent::__construct($commonService, $lmHelper); 
 
        $this->customerFavoriteProductRepository = $customerFavoriteProductRepository; 
 
        $this->CommonService = $commonService; 
        $this->CustomerService = $CustomerService; 
        $this->OrderService = $OrderService; 
        $this->mPayment = $lmHelper->getPaymentTypeList(); 
        $this->DOW = $lmHelper->getDayOfWeek(); 
        $this->mobileDetector = $mobileDetector; 
        $this->favoriteService = $favoriteService; 
    } 
 
    /** 
     * マイページ 
     * 
     * @Route("/mypage/", name="mypage", methods={"GET"}) 
     * @Template("Mypage/index.twig") 
     */ 
    public function index(Request $request) 
    { 
        $Customer = $this->getUser(); 
        if(!$Customer) { 
            return $this->redirectToRoute('mypage_login'); 
        } 
 
        $lmCustomerId = $Customer->getLmCustomerId(); 
 
        #LMカスタマーを取得 
        $lmCustomer = $this->CustomerService->GetLandMarkCustomerId($lmCustomerId); 
        $mailDisp = 0; 
        if (strlen($lmCustomer['customer_mail']) > 25 and isset($lmCustomer["customer_mail"]) and $lmCustomer["customer_mail"] != "" and preg_match("/@/", $lmCustomer["customer_mail"])) { 
            $mailDisp = 1; 
        } 
 
        $data = $this->OrderService->getDispCount ($lmCustomerId); 
        // Coupon logic using vendor/lm/engine-coupon functions 
        $coupons = []; 
        $customerBangou = $lmCustomer['customer_bangou'] ?? null; 
        $customerId = $lmCustomer['customer_id'] ?? null; 
         
        if ($customerBangou) { 
            // Initialize coupon engine (no PDO needed - uses SqlService internally) 
 
            $couponEngine = new Coupon(); 
            // Get all available coupons for the customer 
            $availableCoupons = $couponEngine->getAvailableCouponList($customerBangou, $customerId, new \DateTime()); 
            // Process each coupon according to requirements 
            foreach ($availableCoupons as $campaign) { 
                $couponData = [ 
                    'id' => $campaign->getCouponCampaignId(), 
                    'title' => $campaign->getCouponCampaignTitle() ?: 'クーポン', 
                    'coupon_campaign_display_name' => $campaign->getCouponCampaignDisplayName() ?: 'クーポン', 
                    'description' => $campaign->getCouponCampaignComment() ?: '', 
                    'code' => $campaign->getCouponCampaignCode() ?: '', 
                    'target' => $campaign->getCouponCampaignTarget(), 
                    'discount_amount' => $campaign->getCouponCampaignDiscount(), 
                    'price' => $campaign->getCouponCampaignPrice(), 
                    'expires_at' => $campaign->getCouponCampaignEndDate(), 
                    'start_date' => $campaign->getCouponCampaignStartDate(), 
                    'type' => $this->getCouponType($campaign->getCouponCampaignTarget(), $lmCustomer), 
                    'status' => $this->getCouponStatus($campaign->getCouponCampaignEndDate()) 
                ]; 
                 
                $coupons[] = $couponData; 
            } 
             
            // Sort by expiration date (ascending - closest to expiration first) - Requirement 0 
            usort($coupons, function($a, $b) { 
                $dateA = new \DateTime($a['expires_at']); 
                $dateB = new \DateTime($b['expires_at']); 
                return $dateA <=> $dateB; 
            }); 
 
            // Filter coupons based on user's order status 
            $hasOrders = false; 
            if ($History = $this->OrderService->getHistory($lmCustomerId)) { 
                $hasOrders = count($History) > 0; 
            } 
            $coupons = array_values(array_filter($coupons, function ($c) use ($hasOrders, $lmCustomer) { 
                if (isset($c['type']) && $c['type'] === 'newsletter' && $lmCustomer['customer_melmaga'] == 1) { 
                    return true; 
                } 
             
                if (isset($c['type']) && $c['type'] === 'first_purchase' && !$hasOrders) { 
                    return true; 
                } 
 
                if (isset($c['type']) && $c['type'] === 'customer_feedback_without_photo') { 
                    return true; 
                } 
 
                if (isset($c['type']) && $c['type'] === 'customer_feedback_with_photo') { 
                    return true; 
                } 
 
                if (isset($c['type']) && $c['type'] === 'for_all_customer') { 
                    return true; 
                } 
 
                if (isset($c['type']) && $c['type'] === 'spot_mail') { 
                    return true; 
                } 
             
                return false; 
            })); 
        } 
 
 
 
        $main_h1 = null; 
        $category_h1 = null; 
        $h1_comment = null; 
        $common_header_contents_all = ''; 
        $common_header_contents = null; 
        $recentviews = []; 
        $custom_menu = null; 
        $custom_frequently_searched_word = null; 
        // ビュー(テンプレート)へデータを渡す 
        return [ 
            'lmCustomer' => $lmCustomer, 
            'CFIMG_URL' => $this->CFIMG_URL, 
            'data' => $data, 
            'main_h1' => $main_h1, 
            'mailDisp' => $mailDisp, 
            'category_h1' => $category_h1, 
            'h1_comment' => $h1_comment, 
            'common_header_contents_all' => $common_header_contents_all, 
            'common_header_contents' => $common_header_contents, 
            'recentviews' => $recentviews, 
            'custom_menu' => $custom_menu, 
            'custom_frequently_searched_word' => $custom_frequently_searched_word, 
            'BreadCrumbs' => [], 
            'coupons' => $coupons, 
 
        ]; 
    } 
 
 
    /** 
     * お気に入り商品を表示する. 
     * 
     * @Route("/mypage/favorite/", name="mypage_favorite", methods={"GET"}) 
     * @Template("Mypage/favorite.twig") 
     */ 
    public function favorite(Request $request, PaginatorInterface $paginator) 
    { 
        $sort = $request->get('s', 1); 
        $itemStart = $request->get('no', 0); 
        $pageLimit = 10; 
 
        $Customer = $this->getUser(); 
        if(!$Customer) { 
            throw new AccessDeniedHttpException("Err1 このページは表示できません。"); 
        } 
        $lmCustomerId = $Customer->getLmCustomerId(); 
        #LMカスタマーを取得 
        $lmCustomer = $this->CustomerService->GetLandMarkCustomerId($lmCustomerId); 
        $mailDisp = 0; 
        if (strlen($lmCustomer['customer_mail']) > 25 and isset($lmCustomer["customer_mail"]) and $lmCustomer["customer_mail"] != "" and preg_match("/@/", $lmCustomer["customer_mail"])) { 
            $mailDisp = 1; 
        } 
 
        $main_h1 = null; 
        $category_h1 = null; 
        $h1_comment = null; 
        $common_header_contents_all = ''; 
        $common_header_contents = null; 
        $recentviews = []; 
        $custom_menu = null; 
        $custom_frequently_searched_word = null; 
        $data=[]; 
        $BreadCrumbs = [ 
            1 => $this->__getBreadCrumbs_MyPageTop(), 
        ]; 
        $data = $this->favoriteService->getFavoriteList ($sort, $lmCustomerId, $itemStart, $pageLimit); 
        $totalItem = $this->favoriteService->getTotalFavorites ($lmCustomerId); 
 
        return [ 
            'lmCustomer' => $lmCustomer, 
            'CFIMG_URL' => $this->CFIMG_URL, 
            'sort' => $sort, 
            'mailDisp' => $mailDisp, 
            'data' => $data, 
            'main_h1' => $main_h1, 
            'category_h1' => $category_h1, 
            'h1_comment' => $h1_comment, 
            'common_header_contents_all' => $common_header_contents_all, 
            'common_header_contents' => $common_header_contents, 
            'recentviews' => $recentviews, 
            'custom_menu' => $custom_menu, 
            'custom_frequently_searched_word' => $custom_frequently_searched_word, 
            'BreadCrumbs' => $BreadCrumbs, 
            'totalItem' => $totalItem, 
            'itemStart' => $itemStart + 1, 
            'itemEnd' => ($itemStart + $pageLimit) > $totalItem ? $totalItem : $itemStart + $pageLimit, 
            'currentPage' => (int)$itemStart/10 + 1, 
            'totalPage' => ceil($totalItem/10), 
        ]; 
    } 
 
    /** 
     * @Route("/mypage/add_favorite/{goods_id}/", name="mypage_add_favorite", methods={"GET"}) 
     * @Template("Mypage/favorite.twig") 
     */ 
    public function addFavorite(Request $request) 
    { 
        $customer = $this->getUser(); 
        if (!$customer) { 
            return $this->redirect($this->generateUrl('mypage_login')); 
        } 
 
        $goodsId = $request->get('goods_id'); 
        $goods = $this->favoriteService->getGoodsById($goodsId); 
        if (empty($goods)) { 
            $this->favoriteService->setFavoriteFlashMessage("商品が見つかりません。もう一度はじめからやり直してください。"); 
        } else { 
            $isFavoriteGoods = $this->favoriteService->isFavoriteGoods($goodsId, $customer->getLmCustomerId()); 
            if ($isFavoriteGoods) { 
                $this->favoriteService->setFavoriteFlashMessage("既にお気に入りリストに登録されています。"); 
            } else { 
                $this->favoriteService->addFavorite([ 
                    'mylist_customer' => $customer->getLmCustomerId(), 
                    'mylist_goods' => $goodsId, 
                    'mylist_comment' => null, 
                    'mylist_rank' => null, 
                    'mylist_date' => Carbon::now(), 
                ]); 
                $this->favoriteService->setFavoriteFlashGoods($goods); 
 
                // 
                $event = new EventArgs([ 
                    'goods_id' => $goodsId, 
                ], $request); 
                $this->eventDispatcher->dispatch($event, LmEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE); 
            } 
        } 
 
        return $this->redirect($this->generateUrl('mypage_favorite')); 
    } 
    /** 
     * お気に入り商品を削除する. 
     * 
     * @Route("/mypage/favorite/{id}/comment/", name="mypage_favorite_comment", methods={"POST"}, requirements={"id" = "\\d+"}) 
     * @Template("Mypage/favorite_print.twig") 
     */ 
    public function comment(Request $request, $id) 
    { 
        if (!$request->isXmlHttpRequest()) { 
            throw new BadRequestHttpException(); 
        } 
        $this->isTokenValid(); 
        $Customer = $this->getUser(); 
        $lmCustomerId = $Customer->getLmCustomerId(); 
        log_info('お気に入りコメント開始', [$lmCustomerId, $id]); 
 
        if ($id) { 
            $result = $this->favoriteService->addComment($id, $request->get('comment'), $request->get('rank')); 
            if ($result) { 
                return $this->json(['success' => true]); 
            } 
        } 
        return $this->json(['success' => false]); 
    } 
 
    /** 
     * お気に入り商品を削除する. 
     * 
     * @Route("/mypage/favorite/print/", name="mypage_favorite_print", methods={"GET"}) 
     * @Template("Mypage/favorite_print.twig") 
     */ 
    public function favorite_print(Request $request) 
    { 
        $sort = $request->get('s', 1); 
 
        $Customer = $this->getUser(); 
        if(!$Customer) { 
            throw new AccessDeniedHttpException("Err1 このページは表示できません。"); 
        } 
        $lmCustomerId = $Customer->getLmCustomerId(); 
        #LMカスタマーを取得 
        $lmCustomer = $this->CustomerService->GetLandMarkCustomerId($lmCustomerId); 
 
        $FavoriteProducts = $this->favoriteService->getFavoriteList ($sort, $lmCustomerId, 0, 0); 
 
        $BreadCrumbs = [ 
            1 => $this->__getBreadCrumbs_MyPageTop(), 
        ]; 
        return [ 
            'lmCustomer' => $lmCustomer, 
            'CFIMG_URL' => $this->CFIMG_URL, 
            'FavoriteProducts' => $FavoriteProducts, 
            'BreadCrumbs' => $BreadCrumbs, 
        ]; 
    } 
 
    /** 
     * お気に入り商品を削除する. 
     * 
     * @Route("/mypage/favorite/{id}/delete", name="mypage_favorite_delete", methods={"DELETE"}, requirements={"id" = "\d+"}) 
     * @param Request $request 
     * @param $id 
     * @return \Symfony\Component\HttpFoundation\RedirectResponse 
     */ 
    public function delete(Request $request, $id) 
    { 
        $this->isTokenValid(); 
 
        $Customer = $this->getUser(); 
 
        log_info('お気に入り商品削除開始', [$Customer->getLmCustomerId(), $id]); 
 
        $this->favoriteService->deleteFavorite ($id); 
 
        // 
        $event = new EventArgs([ 
            'goods_id' => $id, 
        ], $request); 
        $this->eventDispatcher->dispatch($event, LmEvents::FRONT_PRODUCT_FAVORITE_DELETE_COMPLETE); 
 
        log_info('お気に入り商品削除完了', [$Customer->getLmCustomerId(), $id]); 
 
        return $this->redirect($this->generateUrl('mypage_favorite')); 
    } 
 
    /** 
     * マイページ / 購入履歴・再注文(名入れ無し) 
     * 
     * @Route("/mypage/history/", name="mypage/history", methods={"GET"}) 
     * @Template("Mypage/history.twig") 
     */ 
    public function history(Request $request) 
    { 
        $mSiteType = $this->lmHelper->getSiteTypeList(); 
 
        /** 
         * @var Customer $Customer 
         */ 
        $Customer = $this->getUser(); 
        $lmCustomerId = $Customer->getLmCustomerId(); 
 
        #LMカスタマーを取得 
        $lmCustomer = $this->CustomerService->GetLandMarkCustomerId($lmCustomerId); 
 
        // 会員のメール表示切替用 
        $mailDisp = 0; 
        if (strlen($lmCustomer['customer_mail']) > 25 and isset($lmCustomer["customer_mail"]) and $lmCustomer["customer_mail"] != "" and preg_match("/@/", $lmCustomer["customer_mail"])) { 
            $mailDisp = 1; 
        } 
        // メモ欄: LM成り代わりログイン時のみ表示 sessionについて確認必要 
        $memoDisp = 0; 
        if (isset($_SESSION["landmark_fax_login"]) and $_SESSION["landmark_fax_login"] != "") { 
            $memoDisp = 1; 
        } 
 
        // 購入履歴一覧の取得 
        $orderList=[]; 
        $goodsList=[]; 
        if( $History = $this->OrderService->getHistory($lmCustomerId) ){ 
            $no = count($History); 
            foreach($History as $v){ 
                $shipping_infos = []; 
                 
                if ($v['has_sendsheet'] == 1) { 
                    $shipping_infos = $this->OrderService->getShippingInfo($v['oh_id']); 
                } 
                 
                // Get campaign discount items from OrderItems 
                $campaignDiscounts = $this->OrderService->getCampaignDiscountItems($v['oh_id']); 
 
                $orderList[] = [ 
                    'no'=> $no, 
                    'order'=>$v['oh_shubetsu'].'-'.$v['oh_id'], 
                    'date'=>$v['oh_date'], 
                    'payment'=>$this->mPayment[$v['oh_payment']], 
                    'new_kakunin_id'=>$v['new_kakunin_id'], 
                    'oh_id'=>$v['oh_id'], 
                    'oh_torikeshi'=>$v['oh_torikeshi'], 
                    'koguchi'=>$v['koguchi'], 
                    'oh_coupon_discount'=>$v['oh_coupon_discount'], 
                    'oh_discount'=>$v['oh_discount'], 
                    'oh_campaign_discount'=>$v['oh_campaign_discount'], 
                    'oh_campaign_description'=>$v['oh_campaign_description'], 
                    'campaign_discounts'=>$campaignDiscounts, 
                    'oh_sendcharge'=>$v['oh_sendcharge'], 
                    'oh_sendcharge_service'=>$v['oh_sendcharge_service'], 
                    'oh_daibiki'=>$v['oh_daibiki'], 
                    'oh_daibiki_service'=>$v['oh_daibiki_service'], 
                    'oh_atobarai'=>$v['oh_atobarai'], 
                    'oh_atobarai_service'=>$v['oh_atobarai_service'], 
                    'oh_sumary'=>$v['oh_sumary'], 
                    'oh_zeus_linkpoint_flg'=>$v['oh_zeus_linkpoint_flg'], 
                    'has_sendsheet'=>$v['has_sendsheet'], 
                    'spr_pdate'=>$v['spr_pdate'], 
                    'shipping_infos'=> $shipping_infos, 
                ]; 
                $goodsList[$no] = $this->OrderService->getHistoryGoods($v['oh_id']); 
                $no = $no-1; 
            } 
        } 
        $orderCnt = count($History); 
        $page = $request->query->get('page', 1);     // ?pageの指定がない場合は1ページ目とする 
        $itemsPerPage=10; 
        $max_paging_links = 10; 
        if ($this->mobileDetector->isMobile()) { 
            $max_paging_links = 4; 
        } 
        $pager = LmHelper::paging($page, $orderList, $itemsPerPage, $max_paging_links); 
        $page_offset = $pager['page_offset']; 
        $orderList = array_slice($orderList, $page_offset, $itemsPerPage); 
 
        $pager['anKaishi'] = $pager['total_count']-$page_offset; 
        $anOwari = $pager['anKaishi'] - $itemsPerPage +1; 
        if ($anOwari < 1) { 
            $anOwari = 1; 
        } 
        $pager['anOwari'] = $anOwari; 
 
        $main_h1 = null; 
        $category_h1 = null; 
        $h1_comment = null; 
        $common_header_contents_all = ''; 
        $common_header_contents = null; 
        $recentviews = []; 
        $custom_menu = null; 
        $custom_frequently_searched_word = null; 
        $data=[]; 
        $review = []; 
        $BreadCrumbs = [ 
            1 => $this->__getBreadCrumbs_MyPageTop(), 
        ]; 
 
        $countAllOrder = []; 
        if ($this->mobileDetector->isMobile()) { 
            $countAllOrder = $this->OrderService->getDispCount($lmCustomerId); 
        } 
 
        if(count($goodsList) > 0){ 
            $this->checkOutOfStock($goodsList); 
        } 
        // ビュー(テンプレート)へデータを渡す 
        return [ 
            'lmCustomerId' => $lmCustomerId, 
            'lmCustomer' => $lmCustomer, 
            'orderCnt' => $orderCnt, 
            'orderList' => $orderList, 
            'goodsList' => $goodsList, 
            'mPayment' => $this->mPayment,   // TODO: Don't do that. 
            'mSiteType' => $mSiteType, // TODO: Don't do that. 
            'mailDisp' => $mailDisp, 
            'memoDisp' => $memoDisp, 
            'pager' => $pager, 
            'data' => $data, 
            'main_h1' => $main_h1, 
            'category_h1' => $category_h1, 
            'h1_comment' => $h1_comment, 
            'common_header_contents_all' => $common_header_contents_all, 
            'common_header_contents' => $common_header_contents, 
            'recentviews' => $recentviews, 
            'custom_menu' => $custom_menu, 
            'custom_frequently_searched_word' => $custom_frequently_searched_word, 
            'review' => $review, 
            'BreadCrumbs' => $BreadCrumbs, 
            'countAllOrder' => $countAllOrder 
        ]; 
    } 
 
    private function checkOutOfStock(&$goodsList, $isHistory = true){ 
        foreach($goodsList as &$goods){ 
            foreach($goods as &$item){ 
                foreach($item as &$child){ 
                    if(!$isHistory){ 
                        $child = &$child['goods']; 
                    } 
                    foreach($child as &$childItem){ 
                        $sku = SkuExtended::getInstance(null, null, $childItem['gcl_id'], $childItem['gp_id']); 
                        if ($sku->isNoDisplay() || $sku->getGclDisplayStatus() === GoodsColor::DISPLAY_STATUS_UNAVAILABLE || $sku->getGpDisplay() === GoodsPrice::DISPLAY_HIDDEN) { 
                            $childItem['is_out_of_stock'] = true; 
                        }else{ 
                            $childItem['is_out_of_stock'] = false; 
                        } 
                    } 
                } 
            } 
        } 
    } 
 
    /** 
     * マイページ / 購入履歴・再注文(名入れ有り) 
     * 
     * @param Request $request 
     * @param ImageService $imageService 
     * @Route("/mypage/mhistory/", name="mypage/mhistory", methods={"GET"}) 
     * @Template("Mypage/mhistory.twig") 
     * @return array 
     */ 
    public function mhistory(Request $request, ImageService $imageService) 
    { 
        $Customer = $this->getUser(); 
        $lmCustomerId = $Customer->getLmCustomerId(); 
 
        #LMカスタマーを取得 
        $lmCustomer = $this->CustomerService->GetLandMarkCustomerId($lmCustomerId); 
 
        // 会員のメール表示切替用 
        $mailDisp = 0; 
        if (strlen($lmCustomer['customer_mail']) > 25 and isset($lmCustomer["customer_mail"]) and $lmCustomer["customer_mail"] != "" and preg_match("/@/", $lmCustomer["customer_mail"])) { 
            $mailDisp = 1; 
        } 
        // メモ欄: LM成り代わりログイン時のみ表示 sessionについて確認必要 
        $memoDisp = 0; 
        if (isset($_SESSION["landmark_fax_login"]) and $_SESSION["landmark_fax_login"] != "") { 
            $memoDisp = 1; 
        } 
 
        // 購入履歴一覧の取得 
        $orderList=[]; 
        $goodsList=[]; 
        if( $History = $this->OrderService->getMhistory($lmCustomerId) ){ 
            $no = count($History); 
            foreach($History as $v){ 
                $img="/kanri_img/images/new_kakunin_img/" . $v['oh_id'] . ".jpg"; 
                // $sslimageType = "kakunin"; 
                // $file_headers = @get_headers($img); 
                // if($file_headers[0] != 'HTTP/1.1 403 Forbidden' or strpos( $file_headers[0],"OK" )){ 
                //     list($width, $height) = @getimagesize($img); 
                // } 
                // if (empty($width)) { 
                //     $img="/kanri_img/images/kakunin_img/" . $v['oh_id'] . ".jpg"; 
                //     $sslimageType = "oldkakunin"; 
                //     $file_headers = @get_headers($img); 
                //     if($file_headers[0] != 'HTTP/1.1 403 Forbidden' or strpos( $file_headers[0],"OK" )){ 
                //         list($width, $height) = @getimagesize($img); 
                //     } 
                // } 
                $shipping_infos = []; 
                 
                if ($v['has_sendsheet'] == 1) { 
                    $shipping_infos = $this->OrderService->getShippingInfo($v['oh_id']); 
                } 
                // Get campaign discount items from OrderItems 
                $campaignDiscounts = $this->OrderService->getCampaignDiscountItems($v['oh_id']); 
 
                $orderList[] = [ 
                    'no'=> $no, 
                    'order'=>$v['oh_shubetsu'].'-'.$v['oh_id'], 
                    'date'=>$v['oh_date'], 
                    'payment'=>$this->mPayment[$v['oh_payment']], 
                    'new_kakunin_id'=>$v['new_kakunin_id'], 
                    'oh_id'=>$v['oh_id'], 
                    'oh_torikeshi'=>$v['oh_torikeshi'], 
                    'koguchi'=>$v['koguchi'], 
                    'oh_coupon_discount'=>$v['oh_coupon_discount'], 
                    'oh_discount'=>$v['oh_discount'], 
                    'oh_campaign_discount'=>$v['oh_campaign_discount'], 
                    'oh_campaign_description'=>$v['oh_campaign_description'], 
                    'campaign_discounts'=>$campaignDiscounts, 
                    'oh_sendcharge'=>$v['oh_sendcharge'], 
                    'oh_sendcharge_service'=>$v['oh_sendcharge_service'], 
                    'oh_daibiki'=>$v['oh_daibiki'], 
                    'oh_daibiki_service'=>$v['oh_daibiki_service'], 
                    'oh_atobarai'=>$v['oh_atobarai'], 
                    'oh_atobarai_service'=>$v['oh_atobarai_service'], 
                    'oh_sumary'=>$v['oh_sumary'], 
                    'oh_wrapping'=>$v['oh_wrapping'], 
                    'oh_zeus_linkpoint_flg'=>$v['oh_zeus_linkpoint_flg'], 
                    'has_sendsheet'=>$v['has_sendsheet'], 
                    'spr_pdate'=>$v['spr_pdate'], 
                    'shipping_infos'=> $shipping_infos, 
                ]; 
                $goodsList[$no] = $this->OrderService->getMhistoryGoods($v['oh_id']); 
                $no = $no-1; 
            } 
        } 
        if(count($goodsList) > 0){ 
            $this->checkOutOfStock($goodsList, false); 
        } 
        // ページング 
        $orderCnt = count($History); 
        $page = $request->query->get('page', 1);     // ?pageの指定がない場合は1ページ目とする 
        $itemsPerPage=5; 
        $max_paging_links = 10; 
        if ($this->mobileDetector->isMobile()) { 
            $max_paging_links = 4; 
        } 
        $pager = LmHelper::paging($page, $orderList, $itemsPerPage, $max_paging_links); 
        $page_offset = $pager['page_offset']; 
        $orderList = array_slice($orderList, $page_offset, $itemsPerPage); 
        // 画像の処理は重いため、ページング処理後のデータ分のみ処理 
        $orderList = array_map(function ($order) use ($imageService) { 
            // 
            $sslimageType = ImageService::IMAGE_TYPE_KAKUNIN; 
            if (!list($width, $height) = $imageService->getImageSizeById($order['oh_id'], $sslimageType)) { 
                // 
                $sslimageType = ImageService::IMAGE_TYPE_KAKUNIN_OLD; 
                list($width, $height) = $imageService->getImageSizeById($order['oh_id'], $sslimageType); 
            } 
            // 
            return array_merge($order, [ 
                'kakuninImgW'=>$width, 
                'kakuninImgH'=>$height, 
                'sslimageType'=>$sslimageType, 
            ]); 
        }, $orderList); 
 
        $pager['anKaishi'] = $pager['total_count']-$page_offset; 
        $anOwari = $pager['anKaishi'] - $itemsPerPage +1; 
        if ($anOwari < 1) { 
            $anOwari = 1; 
        } 
        $pager['anOwari'] = $anOwari; 
        //var_dump($goodsList); 
        // ビュー(テンプレート)へデータを渡す 
 
 
        $main_h1 = null; 
        $category_h1 = null; 
        $h1_comment = null; 
        $common_header_contents_all = ''; 
        $common_header_contents = null; 
        $recentviews = []; 
        $custom_menu = null; 
        $custom_frequently_searched_word = null; 
        $data=[]; 
        $BreadCrumbs = [ 
            1 => $this->__getBreadCrumbs_MyPageTop(), 
        ]; 
 
        $countAllOrder = []; 
        if ($this->mobileDetector->isMobile()) { 
            $countAllOrder = $this->OrderService->getDispCount($lmCustomerId); 
        } 
 
        return [ 
            'lmCustomerId' => $lmCustomerId, 
            'lmCustomer' => $lmCustomer, 
            'orderCnt' => $orderCnt, 
            'orderList' => $orderList, 
            'goodsList' => $goodsList, 
            'mPayment' => $this->mPayment, 
            'mailDisp' => $mailDisp, 
            'memoDisp' => $memoDisp, 
            'pager' => $pager, 
            'data' => $data, 
            'main_h1' => $main_h1, 
            'category_h1' => $category_h1, 
            'h1_comment' => $h1_comment, 
            'common_header_contents_all' => $common_header_contents_all, 
            'common_header_contents' => $common_header_contents, 
            'recentviews' => $recentviews, 
            'custom_menu' => $custom_menu, 
            'custom_frequently_searched_word' => $custom_frequently_searched_word, 
            'BreadCrumbs' => $BreadCrumbs, 
            'countAllOrder' => $countAllOrder, 
        ]; 
    } 
 
 
    /** 
     * マイページ / サンプル貸出し履歴 
     * 
     * @Route("/mypage/chistory/", name="mypage/chistory", methods={"GET"}) 
     * @Template("Mypage/chistory.twig") 
     */ 
    public function chistory(Request $request) 
    { 
        $Customer = $this->getUser(); 
        $lmCustomerId = $Customer->getLmCustomerId(); 
 
        #LMカスタマーを取得 
        $lmCustomer = $this->CustomerService->GetLandMarkCustomerId($lmCustomerId); 
 
        // 会員のメール表示切替用 
        $mailDisp = 0; 
        if (strlen($lmCustomer['customer_mail']) > 25 and isset($lmCustomer["customer_mail"]) and $lmCustomer["customer_mail"] != "" and preg_match("/@/", $lmCustomer["customer_mail"])) { 
            $mailDisp = 1; 
        } 
 
        // 購入履歴一覧の取得 
        $orderList=[]; 
        $goodsList=[]; 
        if( $History = $this->OrderService->getChistory($lmCustomerId) ){ 
            $no = count($History); 
            foreach($History as $v){ 
                $sendsheet = $this->OrderService->getOrderByOrderIdAndCustomerId($lmCustomerId, $v['oh_id']); 
                $shipping_infos = []; 
                 
                if ($sendsheet['has_sendsheet'] == 1) { 
                    $shipping_infos = $this->OrderService->getShippingInfo($v['oh_id']); 
                } 
                $orderList[] = [ 
                    'no'=> $no, 
                    'order'=>$v['oh_shubetsu'].'-'.$v['oh_id'], 
                    'date'=>$v['oh_date'], 
                    'oh_id'=>$v['oh_id'], 
                    'oh_catalog_id'=>$v['oh_catalog_id'], 
                    'order_catalog_list' => $v['order_catalog_list'], 
                    'oh_type'=>$v['oh_type'], 
                    'has_sendsheet'=>$sendsheet['has_sendsheet'], 
                    'spr_pdate'=>$sendsheet['spr_pdate'], 
                    'shipping_infos'=> $shipping_infos, 
                ]; 
                $catalogList = []; 
                $catalog = null; 
                if(!is_null($v['order_catalog_list']) and !empty($v['order_catalog_list'])){ 
                    // 昔の希望カタログリスト 
                    $catalog = $v['order_catalog_list']; 
                }elseif(!is_null($v['oh_catalog_id']) and !empty($v['oh_catalog_id'])){ 
                    // 現在の希望カタログリスト 
                    $tmp = $this->OrderService->getChistoryCatalog($v['oh_catalog_id']); 
                    foreach($tmp as $data){ 
                        $catalogList[] = $data['catalog_title']; 
                    } 
                    $catalogTitles = implode("\n",$catalogList); 
                    $catalog = $catalogTitles; 
                } 
                // サンプル希望商品 
                $goods = $this->OrderService->getChistoryGoods($v['oh_id']); 
                if ($this->mobileDetector->isMobile()) { 
                    $goods = $this->OrderService->formatGoodsForSP($v['oh_id'], $goods); 
                } 
                $goodsList[$no] =[ 
                    'catalog_title' => $catalog, 
                    'goods' => $goods, 
                ]; 
                $no = $no-1; 
            } 
        } 
        $orderCnt = count($orderList); 
 
        // ページング 
        $orderCnt = count($History); 
        $page = $request->query->get('page', 1);     // ?pageの指定がない場合は1ページ目とする 
        $itemsPerPage=10; 
        $pager = LmHelper::paging($page, $orderList, $itemsPerPage); 
        $page_offset = $pager['page_offset']; 
        $orderList = array_slice($orderList, $page_offset, $itemsPerPage); 
 
        $pager['anKaishi'] = $pager['total_count']-$page_offset; 
        $anOwari = $pager['anKaishi'] - $itemsPerPage +1; 
        if ($anOwari < 1) { 
            $anOwari = 1; 
        } 
        $pager['anOwari'] = $anOwari; 
 
        $main_h1 = null; 
        $category_h1 = null; 
        $h1_comment = null; 
        $common_header_contents_all = ''; 
        $common_header_contents = null; 
        $recentviews = []; 
        $custom_menu = null; 
        $custom_frequently_searched_word = null; 
        $data=[]; 
        $BreadCrumbs = [ 
            1 => $this->__getBreadCrumbs_MyPageTop(), 
        ]; 
 
        // ビュー(テンプレート)へデータを渡す 
        return [ 
            'lmCustomerId' => $lmCustomerId, 
            'lmCustomer' => $lmCustomer, 
            'orderCnt' => $orderCnt, 
            'orderList' => $orderList, 
            'goodsList' => $goodsList, 
            'mailDisp' => $mailDisp, 
            'mailDisp' => $mailDisp, 
            'pager' => $pager, 
            'data' => $data, 
            'main_h1' => $main_h1, 
            'category_h1' => $category_h1, 
            'h1_comment' => $h1_comment, 
            'common_header_contents_all' => $common_header_contents_all, 
            'common_header_contents' => $common_header_contents, 
            'recentviews' => $recentviews, 
            'custom_menu' => $custom_menu, 
            'custom_frequently_searched_word' => $custom_frequently_searched_word, 
            'BreadCrumbs' => $BreadCrumbs, 
        ]; 
    } 
 
    /** 
     * 納品書の表示 
     * @Route("/mypage/nouhinsho", name="nouhinsho", methods={"GET", "POST"}) 
     * @Template("Mypage/nouhinsho.twig") 
     */ 
    public function nouhinsho(Request $request) 
    { 
       //顧客情報取得 
        $Customer = $this->getUser(); 
        $lmCustomerId = $Customer->getLmCustomerId(); 
 
        $dirPath = "backoffice-data/paper_data/nouhinsho_data/"; 
        $s3 = new FileStoreService(env('S3_LM_DOC'), $dirPath); 
 
        $orderId = $request->query->get('id'); 
 
        $code = md5(serialize($orderId)); 
        $params = [ 
            'dcl_type' => 'deliverynote', 
            'dcl_oh' => $orderId, 
            'dcl_customer' => $lmCustomerId, 
            'dcl_code' => $code, 
            'dcl_cdate' => date('Y-m-d H:i:s'), 
        ]; 
 
        $message = "ダウンロードエラー"; 
 
        $order = $this->OrderService->getOrderByOrderIdAndCustomerId($lmCustomerId, $orderId); 
 
        if (!$order['oh_id']) { 
            return [ 
                'msg' => $message, 
            ]; 
        } 
 
        if (!$order['has_sendsheet']) { 
            return [ 
                'msg' => 'この注文は納品書を発行していません。', 
            ]; 
        } 
 
        //DB(document_create_list_table)へデータ追加 & insertデータID取得 
        $newId = $this->OrderService->insertDocumentCreateList($params); 
 
        if($newId){ 
            //backoffice側でデータ作成=>s3へアップ 
            $backURL=$this->eccubeConfig['S_BACK_URL']; 
            $certFilename=$this->eccubeConfig['S_BACK_CERT_FILENAME']; 
            $backURL=str_replace("backoffice","",$backURL); 
            $url="{$backURL}/getfrompc/document_download.php"; 
            //POSTデータを作成 
            $params = array( 
                "ID"        => $newId, 
                "OH"        => $orderId, 
                "CODE"        => $code, 
            ); 
 
            $curl = curl_init(); 
            curl_setopt($curl, CURLOPT_URL, $url); 
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
            curl_setopt($curl, CURLOPT_POST, true); 
            curl_setopt($curl, CURLOPT_POSTFIELDS, $params); 
            if (!empty($certFilename)) { 
                curl_setopt($curl, CURLOPT_SSLCERT, $certFilename); 
                curl_setopt($curl, CURLOPT_USERAGENT, 'curl/7.52.1'); 
            } 
            if($response = curl_exec($curl)){ 
                $line = explode(":",$response); 
 
                if($line[0] = "OK"){ 
                    //ファイル名 
                    $Filename = $line[1]; 
                    echo $Filename; 
 
                    if($s3->isObjectExists($Filename) !== false){ 
                        $content=env('S3_LM_DOC_PATH') ."/".$dirPath.$Filename; 
                        header('Content-Type: application/pdf'); 
                        readfile($content); 
                        exit; 
                    } 
 
                } 
            } 
            curl_close($curl); 
        } 
 
        return [ 
            'msg' => $message, 
        ]; 
    } 
 
    /** 
     * マイページ / 確認書 
     * 
     * @Route("/mypage/kakuninsho", name="mypage/kakuninsho", methods={"GET"}) 
     * @Template("Mypage/kakuninsho.twig") 
     */ 
    public function kakuninsho(Request $request) 
    { 
        $orderId = $request->query->get('id'); 
        $Customer = $this->getUser(); 
        $lmCustomerId = $Customer->getLmCustomerId(); 
 
        $order = $this->OrderService->getOrderByOrderIdAndCustomerId($lmCustomerId, $orderId); 
        $campaignDiscounts = $this->OrderService->getCampaignDiscountItems($orderId); 
 
        if (empty($order)) { 
            throw new NotFoundHttpException(); 
        } 
 
        #LMカスタマーを取得 
        $lmCustomer = $this->CustomerService->GetLandMarkCustomerId($lmCustomerId); 
 
        list($allData,$kakuninData) = $this->OrderService->getKakuninshoLibrary($orderId); 
        list($detailDisplay,$detailData,$goods_cnt) = $this->OrderService->getKakuninshoLibraryGoods($orderId); 
 
        // 名入れ加工の検索 
        list($insObj1,$insObj2,$insObj3,$dispArray) = $this->OrderService->getKakuninNaire($orderId); 
 
        // 裾上げ商品 
        $susoageGoods = $this->OrderService->getSusoageGoods($orderId); 
        $today = date('Y年m月d日'); 
 
        $kakuninDate = ""; 
        $kakuninDate = $kakuninData['new_kakunin_date']."(" . $this->DOW[$kakuninData['new_kakunin_date_week']] . ")"; 
 
        //asort( $detailData ); 
        reset( $detailData ); 
 
        $kakuninImg = ""; 
        $img="/kanri_img/images/new_kakunin_img/" . $orderId . ".jpg"; 
        $file_headers = @get_headers($img); 
        if( 
            isset($file_headers[0]) 
            && ($file_headers[0] != 'HTTP/1.1 403 Forbidden' or strpos( $file_headers[0],"OK" )) 
        ){ 
            $kakuninImg = "/sslimage?type=kakunin&id=" . $orderId . "&x=240"; 
        } else if(!empty($susoageGoods)){ 
            $kakuninImg = "/kanri_img/images/hanger/susoage.jpg"; 
        } else { 
            $kakuninImg = "/images/mypage/blank.gif"; 
        } 
        $BreadCrumbs = [ 
            1 => $this->__getBreadCrumbs_MyPageTop(), 
        ]; 
 
        // ビュー(テンプレート)へデータを渡す 
        return [ 
            'lmCustomerId' => $lmCustomerId, 
            'lmCustomer' => $lmCustomer, 
            'data' => $kakuninData, 
            'kakuninAllData' => $allData, 
            'kakuninDetailDisplay' => $detailDisplay, 
            'kakuninDetailData' => $detailData, 
            'kakuninDate' => $kakuninDate, 
            'insObj1' => $insObj1, 
            'insObj2' => $insObj2, 
            'insObj3' => $insObj3, 
            'dispArray' => $dispArray, 
            'goods_cnt' => $goods_cnt, 
            'susoageGoods' => $susoageGoods, 
            'today' => $today, 
            'orderId' => $orderId, 
            'kakuninImg' => $kakuninImg, 
            'BreadCrumbs' => $BreadCrumbs, 
            'campaignDiscounts' => $campaignDiscounts, 
        ]; 
    } 
 
    /** 
     * マイページトップのパンくず定義 
     * @return Array マイページトップのパンくず href, label 
     */ 
    private function __getBreadCrumbs_MyPageTop() 
    { 
        return [ 
            'href' => $this->generateUrl('mypage'), 
            'label' => $this->CommonService->GetPagename('mypage'), 
        ]; 
    } 
 
 
    /** 
     * ログイン画面. 
     * 
     * @Route("/mypage/login", name="mypage_login", methods={"GET", "POST"}) 
     * @Template("Mypage/login.twig") 
     */ 
    public function login(Request $request, AuthenticationUtils $utils) 
    { 
        if ($this->isGranted('IS_AUTHENTICATED_FULLY')) { 
            log_info('認証済のためログイン処理をスキップ'); 
 
            return $this->redirectToRoute('mypage'); 
        } 
 
        /* @var $form \Symfony\Component\Form\FormInterface */ 
        $builder = $this->formFactory 
            ->createNamedBuilder('', CustomerLoginType::class); 
 
        $builder->get('login_memory')->setData((bool) $request->getSession()->get('_security.login_memory')); 
 
        if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) { 
            $Customer = $this->getUser(); 
            if ($Customer instanceof Customer) { 
                $builder->get('login_email') 
                    ->setData($Customer->getEmail()); 
            } 
        } 
 
        $event = new EventArgs( 
            [ 
                'builder' => $builder, 
            ], 
            $request 
        ); 
        $this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_MYPAGE_MYPAGE_LOGIN_INITIALIZE); 
 
        $form = $builder->getForm(); 
        $main_h1 = null; 
        $category_h1 = null; 
        $h1_comment = null; 
        $common_header_contents_all = ''; 
        $common_header_contents = null; 
        $recentviews = []; 
        $custom_menu = null; 
        $custom_frequently_searched_word = null; 
        $data=[]; 
        return [ 
            'error' => $utils->getLastAuthenticationError(), 
            'form' => $form->createView(), 
            'data' => $data, 
            'main_h1' => $main_h1, 
            'category_h1' => $category_h1, 
            'h1_comment' => $h1_comment, 
            'common_header_contents_all' => $common_header_contents_all, 
            'common_header_contents' => $common_header_contents, 
            'recentviews' => $recentviews, 
            'custom_menu' => $custom_menu, 
            'custom_frequently_searched_word' => $custom_frequently_searched_word, 
            'BreadCrumbs' => [], 
        ]; 
    } 
    /** 
     * Get coupon type based on target 
     *  
     * @param string $target 
     * @return string 
     */ 
    private function getCouponType($target, $lmCustomer) 
    { 
        switch (true) { 
            case $target === '未購入者': 
                return 'first_purchase'; // 1. 初回限定クーポン 
            case $target === 'メルマガ購読者全員': 
                return 'newsletter'; // 2. メルマガ購読者用クーポン 
            case $target === 'お客様の声に回答したお客様(写真無)': 
                return 'customer_feedback_without_photo'; // 3. お客様の声に回答したお客様(写真無) 
            case $target === 'お客様の声に回答したお客様(写真有)': 
                return 'customer_feedback_with_photo'; // 4. お客様の声に回答したお客様(写真有) 
            case $target === '全員': 
                return 'for_all_customer'; // 5. 全員 
            case preg_match('/^スポットメール:\d+$/u', $target): 
                return 'spot_mail'; // 6. スポットメール 
            default: 
                return 'general'; 
        } 
    } 
 
    /** 
     * Get coupon status based on expiration date 
     *  
     * @param string $expiresAt 
     * @return string 
     */ 
    private function getCouponStatus($expiresAt) 
    { 
        if (!$expiresAt) { 
            return 'unknown'; 
        } 
         
        $expiryDate = new \DateTime($expiresAt); 
        $now = new \DateTime(); 
        $diff = $now->diff($expiryDate); 
         
        if ($expiryDate < $now) { 
            return 'expired'; 
        } elseif ($diff->days <= 3) { 
            return 'expiring_soon'; 
        } else { 
            return 'active'; 
        } 
    } 
}