<?php
include_once('./_common.php');

// 테마에 cart.php 있으면 include
if(defined('G5_THEME_MSHOP_PATH')) {
    $theme_cart_file = G5_THEME_MSHOP_PATH.'/cart.php';
    if(is_file($theme_cart_file)) {
        include_once($theme_cart_file);
        return;
        unset($theme_cart_file);
    }
}

$g5['title'] = '장바구니';
include_once(G5_MSHOP_PATH.'/_head.php');

$contract_days_expr = "(IFNULL(ct_qty, 0) + (IFNULL(ct_qty_hour, 0) / 24))";
$contract_hours_expr = "((IFNULL(ct_qty, 0) * 24) + IFNULL(ct_qty_hour, 0))";
$cart_ct1_col = sql_fetch(" SHOW COLUMNS FROM {$g5['g5_shop_cart_table']} LIKE 'ct_1' ");
$has_cart_ct1 = (isset($cart_ct1_col['Field']) && $cart_ct1_col['Field'] === 'ct_1');
$ct1_expr = $has_cart_ct1 ? 'IFNULL(ct_1, 0)' : '0';
$cart_ct1_select = $has_cart_ct1 ? 'a.ct_1' : '0 as ct_1';

// $s_cart_id 로 현재 장바구니 자료 쿼리
$sql = " select a.ct_id,
                a.it_id,
                a.it_name,
                a.ct_price,
                a.ct_point,
                a.ct_qty,
                a.ct_qty_hour,
                a.ct_status,
                a.ct_send_cost,
                a.it_sc_type,
                a.ct_install_price,
                {$cart_ct1_select},
                b.it_install_price,
                b.it_10,
                b.ca_id
           from {$g5['g5_shop_cart_table']} a left join {$g5['g5_shop_item_table']} b on ( a.it_id = b.it_id )
          where a.od_id = '$s_cart_id' ";
$sql .= " group by a.it_id ";
$sql .= " order by a.ct_id ";
$result = sql_query($sql);

$cart_count = sql_num_rows($result);
?>

<script src="<?php echo G5_JS_URL; ?>/shop.js"></script>
<script src="<?php echo G5_JS_URL; ?>/shop.override.js"></script>

<style>
    .voucher-info-wrap {
        margin-top: 4px;
    }
    .voucher-info-btn {
        display: inline-block;
        border: 0;
        background: transparent;
        padding: 0;
        line-height: 1;
        color: #4b79c9;
        cursor: pointer;
        font-size: 15px;
    }
    .voucher-info-btn:hover { color: #355ea1; }
    .voucher-calc-layer {
        display: none;
        position: fixed;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        z-index: 9999;
    }
    .voucher-calc-backdrop {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.45);
    }
    .voucher-calc-panel {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        width: 92%;
        max-width: 460px;
        background: #fff;
        border-radius: 10px;
        box-shadow: 0 12px 35px rgba(0, 0, 0, 0.3);
        overflow: hidden;
    }
    .voucher-calc-head {
        padding: 10px 12px;
        background: #f6f8fc;
        border-bottom: 1px solid #e5e9f2;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .voucher-calc-close {
        border: 0;
        background: transparent;
        font-size: 19px;
        line-height: 1;
        padding: 1px 2px;
        cursor: pointer;
        color: #555;
    }
    .voucher-calc-body {
        padding: 12px;
        font-size: 12px;
        line-height: 1.55;
        color: #2f2f2f;
    }
    .voucher-calc-body div {
        margin-bottom: 2px;
    }
    .voucher-calc-body div:last-child {
        margin-bottom: 0;
    }
    .voucher-calc-body .formula {
        font-weight: 600;
        color: #1f1f1f;
    }
</style>

<div id="sod_bsk">

    <form name="frmcartlist" id="sod_bsk_list" class="2017_renewal_itemform" method="post" action="<?php echo $cart_action_url; ?>">

    <?php if($cart_count) { ?>
    <div id="sod_chk">
        <label for="ct_all" class="sound_only">상품 전체</label>
        <input type="checkbox" name="ct_all" value="1" id="ct_all" checked>
        전체상품 선택
    </div>
    <?php } ?>

    <ul class="sod_list">
        <?php
        $tot_point = 0;
        $tot_sell_price = 0;
        $it_send_cost = 0;

        for ($i=0; $row=sql_fetch_array($result); $i++)
        {
            // 합계금액 계산
                        $sql = " select SUM((((ct_price + io_price) * {$contract_hours_expr}) + {$ct1_expr})) as price_base,
                                                        SUM(ct_point * {$contract_days_expr}) as point,
                                                        SUM({$contract_days_expr}) as qty,
                                                        SUM({$contract_hours_expr}) as qty_hours
                        from {$g5['g5_shop_cart_table']}
                        where it_id = '{$row['it_id']}'
                          and od_id = '$s_cart_id' ";
            $sum = sql_fetch($sql);

            if ($i==0) { // 계속쇼핑
                $continue_ca_id = $row['ca_id'];
            }

            $a1 = '<a href="./item.php?it_id='.$row['it_id'].'"><strong>';
            $a2 = '</strong></a>';
            $image_width = 80;
            $image_height = 80;
            $image = get_it_image($row['it_id'], $image_width, $image_height);

            $it_name = $a1 . stripslashes($row['it_name']) . $a2;
            $it_options = print_item_options($row['it_id'], $s_cart_id);
            if($it_options) {
                $mod_options = '<button type="button" id="mod_opt_'.$row['it_id'].'" class="mod_btn mod_options">선택사항수정</button>';
               // $it_name .= ;
            }

            // 배송비
            switch($row['ct_send_cost'])
            {
                case 1:
                    $ct_send_cost = '착불';
                    break;
                case 2:
                    $ct_send_cost = '무료';
                    break;
                default:
                    $ct_send_cost = '선불';
                    break;
            }

            // 조건부무료
            if($row['it_sc_type'] == 2) {
                $sendcost = get_item_sendcost($row['it_id'], $sum['price_base'], $sum['qty'], $s_cart_id);

                if($sendcost == 0)
                    $ct_send_cost = '무료';
            }

            $point      = $sum['point'];
            $base_price = (int)round((float)$sum['price_base']);
            $install_price = (int)apms_install_price_by_hours($row, (int)$sum['qty_hours']);
            $sell_price = $base_price + $install_price;
            $contract_hours = (int)$sum['qty_hours'];
            $unit_price = (int)$row['ct_price'];
            $extra_amount = $base_price - ($unit_price * $contract_hours);
        ?>

        <li class="sod_li">
            <input type="hidden" name="it_id[<?php echo $i; ?>]"    value="<?php echo $row['it_id']; ?>">
            <input type="hidden" name="it_name[<?php echo $i; ?>]"  value="<?php echo get_text($row['it_name']); ?>">

            <div class="li_name">
                <span class="li_chk">
                    <label for="ct_chk_<?php echo $i; ?>" class="sound_only">상품선택</label>
                    <input type="checkbox" name="ct_chk[<?php echo $i; ?>]" value="1" id="ct_chk_<?php echo $i; ?>" checked data-sell-price="<?php echo (int)$sell_price; ?>">
                </span>
                <?php echo $it_name; ?>

            </div>
            <div class="li_op_wr">
                <div class="total_img"><?php echo $image; ?></div>
                <div class="sod_opt"><?php echo $it_options; ?></div>
                <div class="li_mod"><?php echo $mod_options; ?></div>
            </div>
            <div class="li_prqty">
                <span class="prqty_price li_prqty_sp"><span>이용권 금액 </span><?php echo number_format($base_price); ?></span>
                <span class="prqty_qty li_prqty_sp"><span>주문기간 </span><?php echo function_exists('apms_contract_hours_text') ? apms_contract_hours_text($contract_hours) : number_format($sum['qty']); ?></span>
                <span class="prqty_sc li_prqty_sp voucher-info-wrap">
                    <button type="button" class="voucher-info-btn" title="이용권 금액 계산식 보기"
                        data-license-price="<?php echo (int)$base_price; ?>"
                        data-unit-price="<?php echo (int)$unit_price; ?>"
                        data-contract-hours="<?php echo (int)$contract_hours; ?>"
                        data-extra-price="<?php echo (int)$extra_amount; ?>">
                        <i class="fa fa-info-circle" aria-hidden="true"></i>
                    </button>
                </span>
                <span class="prqty_sc li_prqty_sp"><span>개통비/설치비 </span><?php echo number_format($install_price); ?></span>
                <span class="prqty_sc li_prqty_sp"><span>배송비 </span><?php echo $ct_send_cost; ?></span>
                <span class="total_point li_prqty_sp"><span>적립포인트 </span><strong><?php echo number_format($sum['point']); ?></strong></span>
            </div>
             <div class="total_price total_span"><span>소계 </span><strong><?php echo number_format($sell_price); ?></strong> Point</div>


        </li>

        <?php
            $tot_point      += $point;
            $tot_sell_price += $sell_price;
        } // for 끝

        if ($i == 0) {
            echo '<li class="empty_list">장바구니에 담긴 상품이 없습니다.</li>';
        } else {
            // 배송비 계산
            $send_cost = get_sendcost($s_cart_id, 0);
        }
        ?>
    </ul>

    <div class="btn_del_wr">
        <button type="button" onclick="return form_check('seldelete');" class="btn01">선택삭제</button>
        <button type="button" onclick="return form_check('alldelete');" class="btn01">비우기</button>
    </div>


    <?php if ($i == 0) { ?>
    <div class="go_shopping"><a href="<?php echo G5_SHOP_URL; ?>/" class="btn01">쇼핑 계속하기</a></div>
    <?php } else { ?>
    <div class="sod_ta_wr">
    <?php
    $tot_price = $tot_sell_price + $send_cost; // 총계 = 주문상품금액합계 + 배송비
    if ($tot_price > 0 || $send_cost > 0) {
    ?>
    <dl id="m_sod_bsk_tot">
        <?php if ($send_cost > 0) { // 배송비가 0 보다 크다면 (있다면) ?>
        <dt class="sod_bsk_dvr">배송비</dt>
        <dd class="sod_bsk_dvr"><strong><?php echo number_format($send_cost); ?> Point</strong></dd>
        <?php } ?>

        <?php if ($tot_price > 0) { ?>
        <dt>포인트</dt>
        <dd><strong><?php echo number_format($tot_point); ?> Point</strong></dd>
        <dt class="sod_bsk_cnt">총계</dt>
        <dd class="sod_bsk_cnt"><strong id="m_cart_selected_total"><?php echo number_format($tot_price); ?></strong> Point</dd>
        <?php } ?>
    </dl>
    <?php } ?>

    <div id="sod_bsk_act" class="btn_confirm">

        <input type="hidden" name="url" value="<?php echo G5_SHOP_URL; ?>/orderform.php">
        <input type="hidden" name="act" value="">
        <input type="hidden" name="records" value="<?php echo $i; ?>">
        <button type="button" onclick="return form_check('buy');" class="btn_submit">주문하기</button>

        <?php if ($naverpay_button_js) { ?>
        <div class="naverpay-cart"><?php echo $naverpay_request_js.$naverpay_button_js; ?></div>
        <?php } ?>
    </div>
    <?php } ?>


    </div>
    </form>

</div>

<div id="voucherCalcLayer" class="voucher-calc-layer" aria-hidden="true">
    <div class="voucher-calc-backdrop"></div>
    <div class="voucher-calc-panel" role="dialog" aria-modal="true" aria-label="이용권 금액 계산식">
        <div class="voucher-calc-head">
            <strong>이용권 금액 계산식</strong>
            <button type="button" class="voucher-calc-close" aria-label="닫기">&times;</button>
        </div>
        <div class="voucher-calc-body" id="voucherCalcDetail"></div>
    </div>
</div>

<script>
$(function() {
    var close_btn_idx;

    function updateCheckedOrderTotal() {
        var sum = 0;
        $("input[name^=ct_chk]:checked").each(function() {
            var rowPrice = parseInt($(this).attr('data-sell-price'), 10);
            if (!isNaN(rowPrice)) sum += rowPrice;
        });

        var $total = $('#m_cart_selected_total');
        if ($total.length) {
            $total.text(number_format(String(sum)));
        }
    }

    // 선택사항수정
    $(".mod_options").click(function() {
        var it_id = $(this).attr("id").replace("mod_opt_", "");
        var $this = $(this);
        close_btn_idx = $(".mod_options").index($(this));

        $.post(
            "./cartoption.php",
            { it_id: it_id },
            function(data) {
                $("#mod_option_frm").remove();
                $this.after("<div id=\"mod_option_frm\"></div>");
                $("#mod_option_frm").html(data);
                price_calculate();
            }
        );
    });

    // 모두선택
    $("input[name=ct_all]").click(function() {
        if($(this).is(":checked"))
            $("input[name^=ct_chk]").prop("checked", true);
        else
            $("input[name^=ct_chk]").prop("checked", false);

        updateCheckedOrderTotal();
    });

    $(document).on('change', "input[name^=ct_chk]", function() {
        var totalCount = $("input[name^=ct_chk]").length;
        var checkedCount = $("input[name^=ct_chk]:checked").length;
        $("input[name=ct_all]").prop("checked", totalCount > 0 && totalCount === checkedCount);
        updateCheckedOrderTotal();
    });

    // 옵션수정 닫기
    $(document).on("click", "#mod_option_close", function() {
        $("#mod_option_frm").remove();
        $("#win_mask, .window").hide();
        $(".mod_options").eq(close_btn_idx).focus();
    });
    $("#win_mask").click(function () {
        $("#mod_option_frm").remove();
        $("#win_mask").hide();
        $(".mod_options").eq(close_btn_idx).focus();
    });

    updateCheckedOrderTotal();

});

function fsubmit_check(f) {
    if($("input[name^=ct_chk]:checked").length < 1) {
        alert("구매하실 상품을 하나이상 선택해 주십시오.");
        return false;
    }

    return true;
}

function form_check(act) {
    var f = document.frmcartlist;
    var cnt = f.records.value;

    if (act == "buy")
    {
        f.act.value = act;
        f.submit();
    }
    else if (act == "alldelete")
    {
        f.act.value = act;
        f.submit();
    }
    else if (act == "seldelete")
    {
        if($("input[name^=ct_chk]:checked").length < 1) {
            alert("삭제하실 상품을 하나이상 선택해 주십시오.");
            return false;
        }

        f.act.value = act;
        f.submit();
    }

    return true;
}

(function($) {
    function numberFormat(n) {
        var num = parseInt(n, 10);
        if (isNaN(num)) num = 0;
        return num.toLocaleString('ko-KR');
    }
    var voucherInfoDebounceUntil = 0;
    var voucherCloseDebounceUntil = 0;
    // 튜닝 권장 범위: debounce 100~180ms, fade 80~140ms
    var voucherDebounceMs = 120;
    var voucherFadeMs = 90;

    $(document).on('click', '.voucher-info-btn', function() {
        var nowTs = (new Date()).getTime();
        if (nowTs < voucherInfoDebounceUntil) return;
        voucherInfoDebounceUntil = nowTs + voucherDebounceMs;
        var $btn = $(this);
        var licensePrice = parseInt($btn.data('license-price'), 10) || 0;
        var unitPrice = parseInt($btn.data('unit-price'), 10) || 0;
        var contractHours = parseInt($btn.data('contract-hours'), 10) || 0;
        var extraPrice = parseInt($btn.data('extra-price'), 10) || 0;

        var extraText = (extraPrice >= 0 ? '+ ' : '- ') + numberFormat(Math.abs(extraPrice));
        var extraGuide = '';
        if (extraPrice > 0) {
            extraGuide = '옵션/추가금액이 반영되어 금액이 추가되었습니다.';
        } else if (extraPrice < 0) {
            extraGuide = '할인/보정 항목이 반영되어 금액이 차감되었습니다.';
        } else {
            extraGuide = '옵션/추가금액 없이 기본 계산식으로 안내드립니다.';
        }
        var html = ''
            + '<div><strong>이용권 금액 계산 안내</strong></div>'
            + '<div class="formula" style="margin-top:8px;">계산식: (시간단가 × 총 이용시간) + 옵션/추가금액</div>'
            + '<div class="formula">= (' + numberFormat(unitPrice) + ' × ' + numberFormat(contractHours) + ') ' + extraText + ' = ' + numberFormat(licensePrice) + '</div>'
            + '<div style="margin-top:8px; color:#666;">• 시간단가: 1시간 기준 금액</div>'
            + '<div style="color:#666;">• 총 이용시간: 주문기간을 시간으로 환산한 값</div>'
            + '<div style="color:#666;">• 옵션/추가금액: 선택옵션/사용량 과금 등 부가 금액 합계</div>'
            + '<div style="margin-top:8px; color:#4b79c9;">※ ' + extraGuide + '</div>'
            + '<div style="margin-top:6px; color:#888;">예) 100 × 49 + 500 = 5,400</div>';

        $('#voucherCalcDetail').html(html);
        $('#voucherCalcLayer').fadeIn(voucherFadeMs).attr('aria-hidden', 'false');
    });

    $(document).on('click', '.voucher-calc-close, .voucher-calc-backdrop', function() {
        var nowTs = (new Date()).getTime();
        if (nowTs < voucherCloseDebounceUntil) return;
        voucherCloseDebounceUntil = nowTs + voucherDebounceMs;
        $('#voucherCalcLayer').fadeOut(voucherFadeMs).attr('aria-hidden', 'true');
    });

    $(document).on('keydown', function(e) {
        if (e.key === 'Escape') {
            var nowTs = (new Date()).getTime();
            if (nowTs < voucherCloseDebounceUntil) return;
            voucherCloseDebounceUntil = nowTs + voucherDebounceMs;
            $('#voucherCalcLayer').fadeOut(voucherFadeMs).attr('aria-hidden', 'true');
        }
    });
})(jQuery);
</script>

<?php
// 통신판매중개 플랫폼 거래 안내 (상품목록 아래)
if(function_exists('vpnlink_platform_notice')) echo vpnlink_platform_notice('cart', array('compact' => true));

include_once(G5_MSHOP_PATH.'/_tail.php');
?>