<?php
require_once('hethong/ketnoi.php');
if(!isset($_SESSION['session'])) { header('location: /landing-page'); exit(); }
$session = $_SESSION['session'];
$check_user = $ketnoi->query("SELECT * FROM `users` WHERE `session` = '$session' ")->fetch_array();
if(empty($check_user['id'])) { header('location: /landing-page'); exit(); }
$user = $check_user;

// Tạo bảng giftcode nếu chưa có
$ketnoi->query("CREATE TABLE IF NOT EXISTS `giftcode` (
  `id` int NOT NULL AUTO_INCREMENT,
  `code` varchar(50) NOT NULL,
  `money` int NOT NULL DEFAULT 0,
  `max_use` int NOT NULL DEFAULT 1,
  `used` int NOT NULL DEFAULT 0,
  `expire_date` date DEFAULT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `code` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

// Tạo bảng lịch sử dùng giftcode nếu chưa có
$ketnoi->query("CREATE TABLE IF NOT EXISTS `giftcode_history` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(100) NOT NULL,
  `code` varchar(50) NOT NULL,
  `money` int NOT NULL DEFAULT 0,
  `used_at` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$money = (int)$user['money'];

// Lấy lịch sử giftcode đã dùng
$history = $ketnoi->query("SELECT * FROM `giftcode_history` WHERE `username`='".$user['username']."' ORDER BY `id` DESC LIMIT 10");
?>
<!DOCTYPE html>
<html lang="vi">
<head>
<?php require $_SERVER['DOCUMENT_ROOT'].'/hethong/head2.php';?>
<title>Nhập Giftcode | <?=$lxtdev['ten_web'];?></title>
<?php require $_SERVER['DOCUMENT_ROOT'].'/hethong/nav.php';?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Be+Vietnam+Pro:ital,wght@0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,400&family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
/* ═══════════════════════════════
   DESIGN TOKENS
═══════════════════════════════ */
:root{
  --bg:        #f0f3f8;
  --surface:   #ffffff;
  --s2:        #f8f9fc;
  --s3:        #eef0f7;
  --border:    rgba(0,0,0,.07);
  --border2:   rgba(0,0,0,.04);
  --h:         #0b0d17;
  --b:         #3d4464;
  --m:         #8891b0;
  --v1:        #5452ee;
  --v2:        #8b5cf6;
  --vg:        linear-gradient(135deg,#5452ee,#8b5cf6);
  --g1:        #059669;
  --g2:        #10b981;
  --gg:        linear-gradient(135deg,#059669,#10b981);
  --a1:        #d97706;
  --a2:        #f59e0b;
  --ag:        linear-gradient(135deg,#d97706,#f59e0b);
  --r1:        #dc2626;
  --r2:        #ef4444;
  --rg:        linear-gradient(135deg,#dc2626,#ef4444);
  --rd:        12px;
  --rdm:       18px;
  --rdl:       24px;
  --rdxl:      32px;
  --sh0:       0 1px 3px rgba(0,0,0,.05);
  --sh1:       0 4px 16px rgba(0,0,0,.06);
  --sh2:       0 8px 32px rgba(0,0,0,.08);
  --shv:       0 8px 28px rgba(84,82,238,.18);
  --ease:      cubic-bezier(.16,1,.3,1);
}

*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}

body{
  font-family:'Be Vietnam Pro',sans-serif;
  background:var(--bg);
  color:var(--b);
  -webkit-font-smoothing:antialiased;
}

.page{
  padding:clamp(12px,3vw,24px) clamp(12px,3vw,28px);
  max-width:900px;
  margin:0 auto;
}

/* ══ PAGE HEADER ══ */
.page-header{
  text-align:center;
  margin-bottom:clamp(20px,3vw,32px);
}
.page-icon{
  width:clamp(64px,10vw,80px);
  height:clamp(64px,10vw,80px);
  border-radius:22px;
  background:var(--vg);
  display:inline-flex;
  align-items:center;
  justify-content:center;
  margin-bottom:16px;
  box-shadow:0 12px 36px rgba(84,82,238,.25);
  animation:float 3s ease-in-out infinite;
}
@keyframes float{
  0%,100%{transform:translateY(0)}
  50%{transform:translateY(-8px)}
}
.page-icon i{font-size:clamp(28px,5vw,36px);color:#fff}
.page-title{
  font-size:clamp(1.3rem,3vw,1.8rem);
  font-weight:900;
  color:var(--h);
  letter-spacing:-.3px;
  margin-bottom:6px;
}
.page-sub{
  font-size:0.85rem;
  color:var(--m);
  font-weight:500;
}

/* ══ GIFTCODE INPUT CARD ══ */
.gc-card{
  background:var(--surface);
  border:1px solid var(--border);
  border-radius:var(--rdxl);
  padding:clamp(20px,3vw,32px);
  box-shadow:var(--sh1);
  margin-bottom:clamp(16px,2vw,24px);
  position:relative;
  overflow:hidden;
}
.gc-card::before{
  content:'';
  position:absolute;
  top:-100px;right:-100px;
  width:300px;height:300px;
  background:radial-gradient(circle,rgba(84,82,238,.04) 0%,transparent 60%);
  pointer-events:none;
}
.gc-card>*{position:relative;z-index:1}

.gc-label{
  font-size:0.7rem;
  font-weight:800;
  color:var(--m);
  text-transform:uppercase;
  letter-spacing:.8px;
  margin-bottom:10px;
  display:flex;
  align-items:center;
  gap:8px;
}
.gc-label i{color:var(--v1);font-size:0.85rem}

.gc-input-wrap{
  display:flex;
  gap:10px;
}
.gc-input{
  flex:1;
  background:var(--s2);
  border:2px solid var(--border);
  border-radius:var(--rdm);
  padding:clamp(13px,2vw,16px) clamp(14px,2vw,20px);
  font-size:1rem;
  font-weight:700;
  color:var(--h);
  font-family:'JetBrains Mono',monospace;
  letter-spacing:1.5px;
  text-transform:uppercase;
  outline:none;
  transition:all .25s;
}
.gc-input::placeholder{
  font-family:'Be Vietnam Pro',sans-serif;
  font-weight:500;
  letter-spacing:0;
  text-transform:none;
  color:var(--m);
  font-size:0.85rem;
}
.gc-input:focus{
  border-color:var(--v1);
  box-shadow:0 0 0 4px rgba(84,82,238,.08);
  background:var(--surface);
}

.gc-btn{
  display:inline-flex;
  align-items:center;
  gap:10px;
  background:var(--vg);
  color:#fff;
  font-size:0.9rem;
  font-weight:800;
  text-transform:uppercase;
  letter-spacing:.5px;
  padding:clamp(13px,2vw,16px) clamp(18px,3vw,28px);
  border-radius:var(--rdm);
  border:none;
  cursor:pointer;
  box-shadow:0 8px 24px rgba(84,82,238,.3);
  transition:all .3s var(--ease);
  white-space:nowrap;
  flex-shrink:0;
}
.gc-btn:hover{
  transform:translateY(-2px);
  box-shadow:0 14px 36px rgba(84,82,238,.45);
}
.gc-btn:active{transform:scale(.97)}
.gc-btn:disabled{
  opacity:.55;
  cursor:not-allowed;
  transform:none!important;
  box-shadow:none!important;
}

.gc-hints{
  display:flex;
  flex-wrap:wrap;
  gap:8px;
  margin-top:14px;
}
.gc-hint{
  display:inline-flex;
  align-items:center;
  gap:6px;
  font-size:0.7rem;
  font-weight:600;
  color:var(--m);
  background:var(--s2);
  padding:6px 12px;
  border-radius:20px;
  border:1px solid var(--border);
}
.gc-hint i{font-size:0.65rem}
.gc-hint.promo{color:var(--v1);border-color:rgba(84,82,238,.15);background:rgba(84,82,238,.04)}
.gc-hint.event{color:var(--a1);border-color:rgba(217,119,6,.15);background:rgba(217,119,6,.04)}

/* ══ RESULT TOAST (inline) ══ */
.gc-result{
  display:none;
  margin-top:16px;
  padding:14px 18px;
  border-radius:var(--rdm);
  font-weight:600;
  font-size:0.85rem;
  animation:slideDown .35s var(--ease);
}
@keyframes slideDown{
  from{opacity:0;transform:translateY(-10px)}
  to{opacity:1;transform:translateY(0)}
}
.gc-result.success{
  display:flex;
  align-items:center;
  gap:12px;
  background:rgba(5,150,105,.06);
  border:1.5px solid rgba(5,150,105,.2);
  color:var(--g1);
}
.gc-result.error{
  display:flex;
  align-items:center;
  gap:12px;
  background:rgba(220,38,38,.05);
  border:1.5px solid rgba(220,38,38,.15);
  color:var(--r1);
}
.gc-result .res-icon{
  width:36px;height:36px;
  border-radius:10px;
  display:flex;
  align-items:center;
  justify-content:center;
  flex-shrink:0;
}
.gc-result.success .res-icon{background:rgba(5,150,105,.12);color:var(--g1)}
.gc-result.error .res-icon{background:rgba(220,38,38,.1);color:var(--r1)}

/* ══ HISTORY TABLE ══ */
.hist-card{
  background:var(--surface);
  border:1px solid var(--border);
  border-radius:var(--rdl);
  padding:clamp(16px,3vw,24px);
  box-shadow:var(--sh0);
}
.hist-title{
  font-size:0.8rem;
  font-weight:800;
  color:var(--h);
  letter-spacing:.3px;
  display:flex;
  align-items:center;
  gap:8px;
  margin-bottom:16px;
}
.hist-title::before{
  content:'';
  display:block;
  width:3px;
  height:16px;
  background:var(--vg);
  border-radius:2px;
}

.hist-table{
  width:100%;
  border-collapse:collapse;
}
.hist-table th{
  text-align:left;
  font-size:0.65rem;
  font-weight:700;
  color:var(--m);
  text-transform:uppercase;
  letter-spacing:.6px;
  padding:10px 12px;
  border-bottom:1.5px solid var(--border);
  white-space:nowrap;
}
.hist-table td{
  padding:12px 12px;
  font-size:0.8rem;
  font-weight:600;
  color:var(--b);
  border-bottom:1px solid var(--border2);
  white-space:nowrap;
}
.hist-table tbody tr{transition:background .15s}
.hist-table tbody tr:hover{background:var(--s2)}
.hist-table .code-cell{
  font-family:'JetBrains Mono',monospace;
  font-weight:700;
  color:var(--v1);
  letter-spacing:.5px;
}
.hist-table .money-cell{
  font-weight:800;
  color:var(--g1);
  font-family:'JetBrains Mono',monospace;
}
.hist-table .date-cell{
  color:var(--m);
  font-weight:500;
  font-size:0.75rem;
}

.hist-empty{
  text-align:center;
  padding:clamp(32px,6vw,48px) 16px;
  color:var(--m);
}
.hist-empty i{
  font-size:clamp(36px,6vw,48px);
  display:block;
  margin-bottom:12px;
  opacity:.4;
}
.hist-empty span{
  display:block;
  font-size:0.85rem;
  font-weight:600;
}

/* ══ WALLET BALANCE BAR ══ */
.balance-bar{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:12px;
  background:var(--h);
  border-radius:var(--rdm);
  padding:clamp(12px,2vw,16px) clamp(16px,2vw,20px);
  margin-bottom:clamp(16px,2vw,24px);
  flex-wrap:wrap;
}
.balance-label{
  font-size:0.7rem;
  font-weight:700;
  color:rgba(255,255,255,.5);
  text-transform:uppercase;
  letter-spacing:.6px;
}
.balance-amount{
  font-size:clamp(1.1rem,2vw,1.3rem);
  font-weight:900;
  color:#fff;
  font-family:'JetBrains Mono',monospace;
}
.balance-refresh{
  color:rgba(255,255,255,.5);
  cursor:pointer;
  transition:color .2s;
  font-size:0.9rem;
}
.balance-refresh:hover{color:#fff}

/* ══ RESPONSIVE ══ */
@media(max-width:640px){
  .gc-input-wrap{flex-direction:column}
  .gc-btn{width:100%;justify-content:center}
  .hist-table{font-size:0.7rem}
  .hist-table th,.hist-table td{padding:8px 6px}
  .balance-bar{gap:8px}
}

@media(max-width:420px){
  .hist-table .date-cell{display:none}
}
</style>
</head>
<body id="kt_app_body" data-kt-app-layout="light-sidebar" data-kt-app-header-fixed="true"
  data-kt-app-sidebar-enabled="true" data-kt-app-sidebar-fixed="true" data-kt-app-sidebar-hoverable="true"
  data-kt-app-sidebar-push-header="true" data-kt-app-sidebar-push-toolbar="true"
  data-kt-app-sidebar-push-footer="true" data-kt-app-toolbar-enabled="true" class="app-default">

<div class="d-flex flex-column flex-root app-root" id="kt_app_root">
<div class="app-page flex-column flex-column-fluid" id="kt_app_page">
<div class="app-wrapper flex-column flex-row-fluid" id="kt_app_wrapper">
<?php require $_SERVER['DOCUMENT_ROOT'].'/hethong/sider.php';?>

<div class="app-main flex-column flex-row-fluid" id="kt_app_main">
<div class="d-flex flex-column flex-column-fluid">
<div class="page">

  <!-- ══ PAGE HEADER ═══════════════════ -->
  <div class="page-header">
    <div class="page-icon">
      <i class="fa-solid fa-gift"></i>
    </div>
    <h1 class="page-title">Nhập Giftcode</h1>
    <p class="page-sub">Nhập mã quà tặng để nhận tiền thưởng vào ví ngay lập tức</p>
  </div>

  <!-- ══ BALANCE BAR ═══════════════════ -->
  <div class="balance-bar">
    <div>
      <div class="balance-label">💳 Số dư ví hiện tại</div>
      <div class="balance-amount" id="currentBalance"><?=number_format($money,0,',','.');?>đ</div>
    </div>
    <i class="fa-solid fa-arrows-rotate balance-refresh" onclick="location.reload()" title="Làm mới số dư"></i>
  </div>

  <!-- ══ GIFTCODE INPUT ═══════════════════ -->
  <div class="gc-card">
    <div class="gc-label">
      <i class="fa-solid fa-ticket"></i> Nhập mã giftcode của bạn
    </div>

    <div class="gc-input-wrap">
      <input
        type="text"
        class="gc-input"
        id="giftcodeInput"
        placeholder="VD: KHANHCODER2024"
        maxlength="30"
        autocomplete="off"
      >
      <button class="gc-btn" id="submitBtn" onclick="submitGiftcode()">
        <i class="fa-solid fa-paper-plane"></i> Nhận Ngay
      </button>
    </div>

    <div class="gc-hints">
      <span class="gc-hint"><i class="fa-solid fa-circle-info"></i> Mã phân biệt HOA/thường</span>
      <span class="gc-hint promo"><i class="fa-solid fa-tag"></i> KHANHCODER20</span>
      <span class="gc-hint event"><i class="fa-solid fa-star"></i> Sự kiện: TẾT2024</span>
    </div>

    <!-- RESULT MESSAGE -->
    <div class="gc-result" id="gcResult"></div>
  </div>

  <!-- ══ HISTORY ═══════════════════ -->
  <div class="hist-card">
    <div class="hist-title">Lịch Sử Nhận Giftcode</div>

    <?php if($history->num_rows > 0): ?>
    <div style="overflow-x:auto">
      <table class="hist-table">
        <thead>
          <tr>
            <th>Mã Giftcode</th>
            <th>Tiền Nhận</th>
            <th>Thời Gian</th>
          </tr>
        </thead>
        <tbody>
          <?php while($row = $history->fetch_assoc()): ?>
          <tr>
            <td class="code-cell"><?=htmlspecialchars($row['code']);?></td>
            <td class="money-cell">+<?=number_format($row['money'],0,',','.');?>đ</td>
            <td class="date-cell"><?=date('d/m/Y H:i', strtotime($row['used_at']));?></td>
          </tr>
          <?php endwhile; ?>
        </tbody>
      </table>
    </div>
    <?php else: ?>
    <div class="hist-empty">
      <i class="fa-solid fa-ticket-simple"></i>
      <span>Chưa có giftcode nào được nhận</span>
    </div>
    <?php endif; ?>
  </div>

</div><!-- /.page -->
</div>
</div>
<?php require $_SERVER['DOCUMENT_ROOT'].'/hethong/foot.php';?>
</div><!-- /app-main -->
</div></div></div>

<script>
/* ═══════════════════════════════════
   GIFTCODE SUBMIT
═══════════════════════════════════ */
function submitGiftcode(){
  const input  = $('#giftcodeInput');
  const btn    = $('#submitBtn');
  const result = $('#gcResult');
  const code   = input.val().trim();

  // Validate
  if(code === ''){
    showResult('error', 'Vui lòng nhập mã giftcode!');
    input.focus();
    return;
  }
  if(code.length < 3){
    showResult('error', 'Mã giftcode quá ngắn, vui lòng kiểm tra lại!');
    input.focus();
    return;
  }

  // Disable button
  btn.prop('disabled', true).html('<i class="fa-solid fa-spinner fa-spin"></i> Đang kiểm tra...');
  result.slideUp(150);

  // AJAX
  $.ajax({
    url: '/hethong/giftcode-xuly.php',
    type: 'POST',
    data: { code: code },
    dataType: 'json',
    timeout: 15000,
    success: function(res){
      if(res.status === 'success'){
        showResult('success', `
          <div>
            <strong>🎉 Chúc mừng!</strong><br>
            Bạn đã nhận được <strong>+${formatMoney(res.money)}đ</strong> từ giftcode <strong>${escapeHtml(res.code)}</strong>.
            ${res.streak ? '<br>🔥 Chuỗi điểm danh hiện tại: <strong>'+res.streak+' ngày</strong>' : ''}
          </div>
        `);
        // Update balance
        if(res.new_balance !== undefined){
          $('#currentBalance').text(formatMoney(res.new_balance) + 'đ');
        }
        input.val('');
        // Reload page after 2s to refresh history
        setTimeout(() => location.reload(), 2500);
      } else {
        showResult('error', res.message || 'Có lỗi xảy ra, vui lòng thử lại!');
      }
    },
    error: function(xhr, status, error){
      let msg = 'Không thể kết nối máy chủ!';
      if(xhr.responseJSON && xhr.responseJSON.message) msg = xhr.responseJSON.message;
      showResult('error', msg);
    },
    complete: function(){
      btn.prop('disabled', false).html('<i class="fa-solid fa-paper-plane"></i> Nhận Ngay');
    }
  });
}

/* ═══════════════════════════════════
   HELPER FUNCTIONS
═══════════════════════════════════ */
function showResult(type, message){
  const result = $('#gcResult');
  result
    .removeClass('success error')
    .addClass(type)
    .html(`
      <div class="res-icon">
        <i class="fa-solid fa-${type === 'success' ? 'circle-check' : 'circle-exclamation'}"></i>
      </div>
      <div>${message}</div>
    `)
    .slideDown(250);
}

function formatMoney(n){
  return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.');
}

function escapeHtml(text){
  const map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' };
  return text.replace(/[&<>"']/g, m => map[m]);
}

/* ═══════════════════════════════════
   ENTER KEY SUPPORT
═══════════════════════════════════ */
$(document).ready(function(){
  $('#giftcodeInput').on('keydown', function(e){
    if(e.key === 'Enter'){
      e.preventDefault();
      submitGiftcode();
    }
  });
});
</script>
</body>
</html>