<?php
if (!defined("_GNUBOARD_")) exit; // 개별 페이지 접근 불가

if (!defined("_ORDERINQUIRY_")) exit; // 개별 페이지 접근 불가

// 테마에 orderinquiry.sub.php 있으면 include
if(defined('G5_THEME_SHOP_PATH')) {
    $theme_inquiry_file = G5_THEME_SHOP_PATH.'/rcpcinquiryexpire.sub.php';
    if(is_file($theme_inquiry_file)) {
        include_once($theme_inquiry_file);
        unset($theme_inquiry_file);
        return;
    }
}
?>

<!-- 렌탈PC 이용내역 목록 시작 { -->
<?php if (!$limit) { ?>총 <?php echo $cnt; ?> 건<?php } ?>

<?php $member_mb_id_esc = oi_sql(isset($member['mb_id']) ? $member['mb_id'] : ''); ?>

<div class="tbl_head03 tbl_wrap">
    <table>
    <thead>
    <tr>
        <th scope="col">품번</th>
        <th scope="col">서버위치</th>
        <th>PC별명</th>
        <th>PC메모</th>
        <th>PC사양</th>
        <th scope="col">렌탈이용시작일</th>
        <th scope="col">렌탈이용만료일</th>
        <th scope="col">렌탈잔여일수</th>
        <th scope="col">원격제어정보</th>
        <th scope="col">PC전원</th>
        <th scope="col">원격재부팅</th>
		<th scope="col">구매포인트</th>
    </tr>
    </thead>
    <tbody>

    <?php

    $now_datetime = date("Y-m-d H:i:s");

    $sql = " select *
               from smart_rental_comspec
			  where member_id = '{$member_mb_id_esc}' AND (start_date != '' AND start_date IS NOT NULL) AND (exp_date != '' AND exp_date IS NOT NULL)
			  and ((TO_DAYS('$now_datetime') - TO_DAYS(exp_date)) > 0)
              order by (
                  select IFNULL(MAX(ct_id), 0)
                  from {$g5['g5_shop_cart_table']}
                  where it_id = no
                    and ct_status in ('입금','배송','완료','확정')
                    and mb_id = '{$member_mb_id_esc}'
              ) desc, no desc
              $limit ";
    $result = sql_query($sql);

	$real_data_cnt = 0;

    for ($i=0; $row=sql_fetch_array($result); $i++)
    {
		// 취소된 주문은 제외 하기 위함.
		$sql_chk = " select * FROM `{$g5['g5_shop_cart_table']}` WHERE it_id = '{$row['no']}' AND (ct_status = '입금' or ct_status = '배송' or ct_status = '완료' or ct_status = '확정') AND mb_id = '{$member_mb_id_esc}' ORDER BY ct_id DESC LIMIT 1 ";
		$result_chk = sql_query($sql_chk);
		$total_chk = @mysqli_num_rows($result_chk);
		$this_ct_id = "";
		if ($total_chk == 0) {
			continue;
		} else {
			$row_chk=sql_fetch_array($result_chk);
			$this_ct_id = $row_chk['ct_id'];
			$this_od_id = $row_chk['od_id'];
			$real_data_cnt++;
		}

        $uid = md5($row['od_id'].$row['od_time'].$row['od_ip']);

        switch($row['od_status']) {
            case '주문':
                $od_status = '<span class="status_01">입금확인중</span>';
                break;
            case '입금':
                $od_status = '<span class="status_02">입금완료</span>';
                break;
            case '준비':
                $od_status = '<span class="status_03">상품준비중</span>';
                break;
            case '배송':
                $od_status = '<span class="status_04">상품배송</span>';
                break;
			case '완료':
				$od_status = '<span class="status_05">배송완료</span>';
				break;
			case '확정':
				$od_status = '<span class="status_07">거래확정</span>'; // 컴뷰어스를 위해 거래확정 항목 추가함. JSLEE
				break;
			default:
                $od_status = '<span class="status_06">주문취소</span>';
                break;
        }
    ?>

    <tr>
        <td><?php echo $row['no']; ?></td>
        <td><?php echo $row['M_storename'];?></td>
        <td style='text-align:left;'>
			<?php
				if (mb_strlen($row['rental_pc_name'],'utf8') <= 10) {
					echo $row['rental_pc_name'] ? mb_substr($row['rental_pc_name'],0,10,'utf8') : "-";
				} else {
					echo $row['rental_pc_name'] ? mb_substr($row['rental_pc_name'],0,10,'utf8')."..." : "-";
				}
			?>
		</td>
        <td>
			<?php
				$rentalPcMemo_disp = $row['rental_pc_memo'] ? "【 " . $row['no'] . "번 렌탈PC메모 】" . "\\n" . addslashes($row['rental_pc_memo']) : "【 " . $row['no'] . "번 렌탈PC메모 】" . "\\n" . "- 메모내용이 없습니다 -";
			?>
			<button onclick="alert('<?php echo $rentalPcMemo_disp; ?>')"><i class="fa fa-sticky-note-o" aria-hidden="true" style='zoom:1.5;'></i><div style='zoom:0.7'>메모보기</div></button>
		</td>
        <td>
			<?php
				// SSD
				$SSDinfo = preg_replace("/SSD/", "",$row['SSDinfo']);
				$SSDinfoArr = explode(",",$SSDinfo);
				$SSDinfoDisp = "";
				$cnt=0;
				for ($js=0; $js<count($SSDinfoArr); $js++) {
					if ($SSDinfoArr[$js] == "") continue;
					if (strpos(strtoupper($SSDinfoArr[$js]),"SAMSUNG") === false) {
						$SSDinfoDispArr = explode(" ",trim($SSDinfoArr[$js]));
						if ($cnt==0) {
							$SSDinfoDisp = trim($SSDinfoDispArr[0]);
							$cnt++;
						} else {
							$SSDinfoDisp = $SSDinfoDisp . " + " . trim($SSDinfoDispArr[0]);
						}
					} else {
						if ($cnt==0) {
							$SSDinfoDisp = trim($SSDinfoArr[$js]);
							$cnt++;
						} else {
							$SSDinfoDisp =  $SSDinfoDisp . " + " . trim($SSDinfoArr[$js]);
						}
					}
				}

				// HDD
				$HDDinfo = preg_replace("/HDD/", "",$row['HDDinfo']);
				$HDDinfoArr = explode(",",$HDDinfo);
				$HDDinfoDisp = "";
				$cnt=0;
				for ($js=0; $js<count($HDDinfoArr); $js++) {
					if ($HDDinfoArr[$js] == "") continue;
					if (strpos(strtoupper($HDDinfoArr[$js]),"SAMSUNG") === false) {
						$HDDinfoDispArr = explode(" ",trim($HDDinfoArr[$js]));
						if ($cnt==0) {
							$HDDinfoDisp = trim($HDDinfoDispArr[0]);
							$cnt++;
						} else {
							$HDDinfoDisp = " + " . trim($HDDinfoDispArr[0]);
						}
					} else {

						if ($cnt==0) {
							$HDDinfoDisp  = trim($HDDinfoArr[$js]);
							$cnt++;
						} else {
							$HDDinfoDisp =  " + " . trim($HDDinfoArr[$js]);
						}
					}
				}

				$gpu_ram = ($row['gpu_ram'] > 0) ? " (" . $row['gpu_ram'] . "GB)" : "";

				$comSpecDisp = "【 " . $row['no'] . "번 렌탈PC사양 】" . "\\n" . "OS : " . $row['OperatingSystem'] . "\\n" . "CPU : " . $row['CpuName'] . "\\n" .  "SSD : "  . $SSDinfoDisp .  "\\n" .  "HDD : "  . $HDDinfoDisp . "\\n" . "RAM : " . $row['RAM'] . "GB" . "\\n" .  "GPU : "  . $row['VideoController'] . $gpu_ram;
			?>
			<button onclick="alert('<?php echo $comSpecDisp; ?>')"><i class="fa fa-info-circle" aria-hidden="true" style='zoom:1.5;'></i><div style='zoom:0.7'>사양보기</div></button>
		</td>
        <td class="td_numbig"><?php echo substr($row['start_date'],0,10)."<br>".substr($row['start_date'],11,99);?></td>
        <td class="td_numbig"><?php echo substr($row['exp_date'],0,10)."<br>".substr($row['exp_date'],11,99);?></td>
        <td class="td_numbig">
		<?php
			$endDate = strtotime($row['exp_date']); //마감시간
			$today = strtotime(date("Y-m-d H:i:s")); //현재시간

			$diff = $endDate - $today;

			$days = floor($diff/3600/24);
			$hours = floor($diff/3600);
			$diff = $diff-($hours*3600);
			$min = floor($diff/60);
			$sec = $diff - ($min*60);

			if ($days >= 0) {
				echo $days . "일 남음";
				$isRental = "yes";
			} else {
				echo "렌탈종료";
				$isRental = "no";
			}
		?>
		</td>
        <td>
			<?php
				if ($isRental == "yes") {
			?>
				<div style='display:flex; justify-content:center; align-items:center; flex-direction:column; width:100%;'>
					<div style='display:flex; justify-content:center; align-items:center; width:100%; border-top:1px solid #efefef; border-bottom:1px solid #efefef;'>
						<div style='width:33.33%; border:1px solid #ffffff; text-align:left; zoom:0.9;'><i class="fa fa-wifi" aria-hidden="true"></i> WAN IP</div>
						<div style='width:66.66%; border:1px solid #ffffff; text-align:left;'>
						<?php
							if ($isRental == "yes") {
								echo $row['extIP'];
							} else {
								echo "-";
							}
						?>
						</div>
					</div>
					<div style='display:flex; justify-content:center; align-items:center; width:100%; border-bottom:1px solid #efefef;'>
						<div style='width:33.33%; border:1px solid #ffffff;'><img src='<?php echo G5_URL?>/mylib/images/anydesk_logo.png' style='height:12px;'></div>
						<?php
							if ($isRental == "yes") {
						?>
								<?php echo trim($row['AnyDeskID']) ? "<div style='width:33.33%; text-align:left;'>" . str_replace([' '], '', $row['AnyDeskID']) . "</div>" : "<div style='width:33.33%;'>-</div>";?><?php echo $row['AnyDeskPWD'] ? "<div style='width:33.33%; text-align:left;'><i class='fa fa-unlock-alt' aria-hidden='true'></i> " . $row['AnyDeskPWD'] . "</div>" : "<div style='width:33.33%;'>-</div>";?>
						<?php
							}
						?>
					</div>
					<div style='display:flex; justify-content:center; align-items:center; width:100%; border-bottom:1px solid #efefef;'>
						<div style='width:33.33%; border:1px solid #ffffff;'><img src='<?php echo G5_URL?>/mylib/images/teamviewer_logo.png' style='height:12px;'></div>
						<?php
							if ($isRental == "yes") {
						?>
							<?php echo trim($row['TeamViewerID']) ? "<div style='width:33.33%; text-align:left;'>" . str_replace([' '], '', $row['TeamViewerID']) . "</div>" : "<div style='width:33.33%;'>-</div>";?><?php echo $row['TeamViewerPWD'] ? "<div style='width:33.33%; text-align:left;'><i class='fa fa-unlock-alt' aria-hidden='true'></i> " . $row['TeamViewerPWD'] . "</div>" : "<div style='width:33.33%;'>-</div>";?>
						<?php
							}
						?>
					</div>
				</div>
			<?php
				} else {
					echo "-";
				}
			?>
		</td>
        <td>
			<?php
			if ($isRental == "yes") {
				$LastUpdateTime = $row['LastUpdateTime']; // 앱에서 마지막으로 업데이트한 일시
				$str_lastUpdateTime = strtotime($LastUpdateTime);
				$str_nowTime = strtotime(date("Y-m-d H:i:s"));
				if (($str_lastUpdateTime+120) < $str_nowTime) { // 70초가 지났는지 체크해서 true라면 offline 상태로 판단
					$isOnline_icon = "<i class='fa fa-plug' aria-hidden='true' style='width:20%; min-width:30px; max-width:40px; zoom:1.5; color:#a7a7a7; padding:3px 4px 3px; border:1px solid #ffffff;'><div style='display:flex; justify-content:center; align-items:center; zoom:0.6; border-bottom:1px solid #efefef;'>OFF</div></i>"; // OFFLINE
					$isOnline = "OFF"; // OFFLINE
				} else {
					$isOnline_icon = "<i class='fa fa-power-off' aria-hidden='true' style='width:20%; min-width:30px; max-width:40px; zoom:1.5; color:#6699ff; padding:3px 4px 3px; border:1px solid #ffffff;'><div style='display:flex; justify-content:center; align-items:center; zoom:0.6; border-bottom:1px solid #efefef;'>ON</div></i>"; // ONLINE
					$isOnline = "ON"; // ONLINE
				}
			} else {
				$isOnline_icon = "-";
				$isOnline = "OFF"; // OFFLINE
			}
			echo $isOnline_icon;
			?>
		</td>
        <td>
			<?php
			if ($isRental == "yes") {
				if ($isOnline == "ON") {
			    	$this_no = $row['no'];
			    	$encrypt_str = Encrypt("reboot" . "Œ" . time() . "Œ" . $this_no  . "Œ" . $member['mb_id'] . date("iHs"));
					//$Restart_icon = "<button id='rcmd_reboot_".$this_no."' onclick='mypagercmd(&quot;$this_no&quot;, &quot;$encrypt_str&quot;, &quot;reboot&quot;);' style='border:1px solid #6699ff;'><i class='fa fa-repeat' aria-hidden='true' style='zoom:1.5; color:#6699ff; padding:3px 4px 3px;'></i></button>"; // 재시작
					$Restart_icon = "<i class='fa fa-windows' aria-hidden='true' style='width:20%; min-width:39px; max-width:50px; zoom:1.5; color:#6699ff; padding:3px 4px 3px; border:1px solid #6699ff; cursor:pointer;' onclick='mypagercmd(&quot;$this_no&quot;, &quot;$encrypt_str&quot;, &quot;reboot&quot;);'><div style='display:flex; justify-content:center; align-items:center; zoom:0.6; border-bottom:1px solid #efefef;'>REBOOT</div></i>"; // REBOOT
				} else if ($isOnline == "OFF") {
					//$Restart_icon = "<button style='border:1px solid #a7a7a7;'><i class='fa fa-repeat' aria-hidden='true' style='zoom:1.5; color:#a7a7a7; padding:3px 4px 3px;'></i></button>"; // 재시작불가(전원OFF상태일때)
					$Restart_icon = "<i class='fa fa-windows' aria-hidden='true' style='width:20%; min-width:39px; max-width:50px; zoom:1.5; color:#a7a7a7; padding:3px 4px 3px; border:1px solid #a7a7a7; cursor:no-drop;'><div style='display:flex; justify-content:center; align-items:center; zoom:0.6; border-bottom:1px solid #efefef;'>REBOOT</div></i>"; // REBOOT
				}
			} else {
				$Restart_icon =  "-";
			}
			echo $Restart_icon;
			?>
		</td>
		<td>
			<?php
				$this_no = $row['no'];
				$sql_od = " select * from {$g5['g5_shop_order_table']} where mb_id = '{$member_mb_id_esc}' and od_id = '{$this_od_id}' order by od_id desc limit 1 ";
				$result_od = sql_query($sql_od);
				$row_od = sql_fetch_array($result_od);
				$sql_ct = " select * from {$g5['g5_shop_cart_table']} where ct_id = '{$this_ct_id}' order by ct_id desc limit 1 ";
				$result_ct = sql_query($sql_ct);
				$row_ct = sql_fetch_array($result_ct);
				$sum_point = $row_ct['ct_point'];

				switch($row_ct['ct_status']) {
					case '주문':
						$ct_status = '<span class="status_01">입금확인중</span>';
						$sum_point_disp = "-";
						break;
					case '입금':
						$ct_status = '<span class="status_02">입금완료</span>';
						$sum_point_disp = "적립하기";
						break;
					case '준비':
						$ct_status = '<span class="status_03">상품준비중</span>';
						$sum_point_disp = "적립하기";
						break;
					case '배송':
						$ct_status = '<span class="status_04">상품배송</span>';
						$sum_point_disp = "적립하기";
						break;
					case '완료':
						$ct_status = '<span class="status_05">배송완료</span>';
						$sum_point_disp = "적립하기";
						break;
					case '확정':
						$ct_status = '<span class="status_07">거래확정</span>'; // 컴뷰어스를 위해 거래확정 항목 추가함. JSLEE
						$sum_point_disp = "적립됨";
						break;
					default:
						$ct_status = '<span class="status_06">주문취소</span>';
						$sum_point_disp = "-";
						break;
				}


                $encrypt_str = Encrypt("pntreq2" . "Œ" . time() . "Œ" . $this_od_id . "Œ" . $this_ct_id  . "Œ" . $member['mb_id'] . date("iHs"));
                if ($sum_point_disp=="적립됨") {
                    echo "<div style='width:100%; padding:2px 2px 2px;'>".display_point($sum_point)."<br>$sum_point_disp</div>";
                } else if ($sum_point_disp=="-") {
                    echo "<div style='width:100%; padding:2px 2px 2px;'>$sum_point_disp</div>";
                } else if ($sum_point_disp=="적립하기") {
                    echo "<i class='fa fa-check' aria-hidden='true' style='width:20%; min-width:35px; max-width:35px; zoom:1.3; color:#6699ff; padding:2px 2px 2px; border:1px solid #6699ff; cursor:pointer;' onclick='putorderpoint2(&quot;$this_od_id&quot;, &quot;$this_ct_id&quot;, &quot;$encrypt_str&quot;, &quot;pntreq2&quot;, &quot;".display_point($sum_point)."&quot;);'><div style='display:flex; justify-content:center; align-items:center; zoom:0.57; border-bottom:1px solid #efefef; margin-top:5px;'>$sum_point_disp</div></i>";
                }
            ?>
		</td>
    </tr>

    <?php
    }

    if ($real_data_cnt == 0)
        echo '<tr><td colspan="11" class="empty_table">렌탈PC이용내역이 없습니다.</td></tr>';
    ?>
    </tbody>
    </table>
</div>

<script>
    function putorderpoint2(this_od_id,this_ct_id,encrypt_str,sum_point_disp, sum_point) {
		console.log(this_od_id,this_ct_id,encrypt_str,sum_point_disp, sum_point);
        if (confirm("[중요고지]\n구매포인트 ("+sum_point+")은 거래확정처리와 동시에 적립이 됩니다.\n적립된 포인트는 결제시 제한없이 사용하실 수 있습니다.\n구매확정이 된 이후에 취소/환불을 신청하시는 경우 포인트로만 환불 받으실 수 있습니다.\n아래 확인 버튼을 누르면 즉시 거래확정이 되며 이용약관에 동의한 것으로 간주됩니다.")) {
            $.ajax({
                url: '/mylib/mypage_putorderpoint2_ajax.php',
                type: 'POST',
                dataType: 'html',
                data: {
                    this_od_id: this_od_id,
                    this_ct_id: this_ct_id,
                    encrypt_str: encrypt_str,
                    sum_point_disp: sum_point_disp,
                    mb_id: '<?php echo $member['mb_id']?>',
                    action:'ajax'
                },
                success:function(data)
                {
                    if(data)
                    {
                        //console.log(data);
                        if (data.trim() == "success") {
                            alert("거래확정후 구매포인트 ("+sum_point+")이 적립되었습니다.");
                            location.reload(false);
                        } else {
                            alert("구매포인트가 적립되지 않았습니다. 관리자에게 요청 해 주십시오. (오류코드:MP2-002)");
                        }
                    }
                }
            });
        }
    }
</script>
<!-- } 렌탈PC 이용내역 목록 끝 -->