<?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;
?>
<!DOCTYPE html>
<html lang="vi">
<head>
<?php require $_SERVER['DOCUMENT_ROOT'].'/hethong/head2.php';?>
<title>Tạo Subdomain | <?=$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="js/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
: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);
  --s1: #0284c7;
  --s2c: #0ea5e9;
  --sg: linear-gradient(135deg,#0284c7,#0ea5e9);
  --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);
  --ease: cubic-bezier(.16,1,.3,1);
  --fs-hero-title: clamp(1.5rem, 4vw, 2.6rem);
}

*,*::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:1380px;
  margin:0 auto;
}

/* ── HERO ── */
.hero{
  position:relative;overflow:hidden;
  background:linear-gradient(135deg,#0b0d17,#1a1d2e);
  border-radius:var(--rdxl);
  padding: clamp(24px, 5vw, 48px) clamp(18px, 4vw, 52px);
  margin-bottom:clamp(16px, 3vw, 24px);
  display:grid;
  grid-template-columns:1fr auto;
  gap:clamp(16px, 3vw, 32px);
  align-items:center;
}
.hero-bg{
  position:absolute;inset:0;
  background:
    radial-gradient(ellipse 65% 80% at 100% -20%,rgba(84,82,238,.5) 0%,transparent 55%),
    radial-gradient(ellipse 50% 60% at -5%  110%,rgba(139,92,246,.3) 0%,transparent 55%);
  z-index:0;
}
.hero-grid{
  position:absolute;inset:0;z-index:0;
  background-image:
    linear-gradient(rgba(255,255,255,.025) 1px,transparent 1px),
    linear-gradient(90deg,rgba(255,255,255,.025) 1px,transparent 1px);
  background-size:48px 48px;
}
.hero>*{position:relative;z-index:2}

.hero-eyebrow{
  display:inline-flex;align-items:center;gap:8px;
  border:1px solid rgba(255,255,255,.12);
  background:rgba(255,255,255,.05);
  border-radius:50px;
  padding:6px 16px;
  font-size:0.65rem;font-weight:700;letter-spacing:1.3px;
  color:rgba(255,255,255,.6);text-transform:uppercase;
  margin-bottom:1rem;
  backdrop-filter:blur(8px);
}
.hero-dot{
  width:7px;height:7px;border-radius:50%;
  background:#f59e0b;
  animation:pulse-dot 2s ease-in-out infinite;
}
@keyframes pulse-dot{
  0%,100%{box-shadow:0 0 0 0 rgba(245,158,11,.6)}
  50%{box-shadow:0 0 0 6px rgba(245,158,11,0)}
}

.hero-title{
  font-size:var(--fs-hero-title);font-weight:900;line-height:1.18;
  color:#fff;letter-spacing:-.5px;margin-bottom:10px;
}
.hero-title .grad{
  background:linear-gradient(90deg,#a5b4fc,#c084fc);
  -webkit-background-clip:text;-webkit-text-fill-color:transparent;
}
.hero-sub{
  font-size:0.85rem;color:rgba(255,255,255,.45);
  font-weight:400;margin-bottom:1.5rem;line-height:1.6;
  max-width:480px;
}

/* ── FORM ── */
.form-card{
  background:var(--surface);
  border:1px solid var(--border);
  border-radius:var(--rdl);
  padding:clamp(20px, 4vw, 32px);
  box-shadow:var(--sh1);
  max-width:720px;
  margin:0 auto;
}
.form-card .sec-title{
  font-size:0.8125rem;font-weight:800;color:var(--h);
  letter-spacing:.3px;display:flex;align-items:center;gap:8px;
  margin-bottom:clamp(16px, 3vw, 24px);
}
.form-card .sec-title::before{
  content:'';display:block;width:3px;height:18px;
  background:var(--vg);border-radius:2px;
}

.field-group{
  margin-bottom:clamp(16px, 3vw, 22px);
}
.field-group label{
  font-size:0.7rem;font-weight:800;color:var(--m);
  text-transform:uppercase;letter-spacing:.7px;
  display:block;margin-bottom:6px;
}
.field-group label .req{color:var(--r1);margin-left:2px}
.field-group .hint{
  font-size:0.65rem;color:var(--m);
  margin-top:4px;font-weight:500;
}

.input-join{
  display:flex;
}
.input-join .dc-input{
  flex:1;
  border-radius:var(--rd) 0 0 var(--rd);
  border-right:none;
}
.input-join .dc-input:focus{
  border-color:var(--v1);
  box-shadow:0 0 0 3px rgba(84,82,238,.1);
}
.input-suffix{
  background:#f0f3f8;
  border:1.5px solid var(--border);
  border-radius:0 var(--rd) var(--rd) 0;
  padding:clamp(10px, 2vw, 12px) clamp(12px, 2vw, 16px);
  font-size:0.8rem;font-weight:700;
  color:var(--m);
  white-space:nowrap;display:flex;align-items:center;
}

.dc-input{
  width:100%;background:var(--s2);
  border:1.5px solid var(--border);
  border-radius:var(--rd);
  padding:clamp(10px, 2vw, 12px) clamp(12px, 2vw, 16px);
  font-size:0.85rem;font-weight:500;color:var(--h);
  font-family:'Be Vietnam Pro',sans-serif;
  outline:none;transition:border-color .2s,box-shadow .2s;
}
.dc-input:focus{
  border-color:var(--v1);
  box-shadow:0 0 0 3px rgba(84,82,238,.1);
}
.dc-input::placeholder{color:var(--m);font-weight:400}

.dc-select{
  width:100%;background:var(--s2);
  border:1.5px solid var(--border);
  border-radius:var(--rd);
  padding:clamp(10px, 2vw, 12px) clamp(12px, 2vw, 16px);
  font-size:0.85rem;font-weight:500;color:var(--h);
  font-family:'Be Vietnam Pro',sans-serif;
  outline:none;appearance:none;
  transition:border-color .2s,box-shadow .2s;
  cursor:pointer;
}
.dc-select:focus{
  border-color:var(--v1);
  box-shadow:0 0 0 3px rgba(84,82,238,.1);
}

.inv-box{
  background:var(--s2);border:1.5px solid var(--border);
  border-radius:var(--rdm);padding:clamp(14px, 2vw, 20px);
  margin-top:4px;
}
.inv-row2{
  display:flex;justify-content:space-between;align-items:center;
  padding:4px 0;font-size:0.82rem;
}
.inv-row2 .k{color:var(--m);font-weight:500}
.inv-row2 .v{font-weight:700;color:var(--h)}
.inv-row2 .v.green{color:var(--g1)}
.inv-row2 .v.amber{color:var(--a1)}
.inv-sep{border:none;border-top:1.5px dashed var(--border);margin:6px 0}
.inv-total{
  display:flex;justify-content:space-between;align-items:center;
  padding:4px 0;
}
.inv-total .k{
  font-size:0.9rem;font-weight:800;color:var(--h);
}
.inv-total .v{
  font-size:clamp(1.1rem, 2.5vw, 1.4rem);
  font-weight:900;color:var(--v1);
  font-family:'JetBrains Mono',monospace;
}
.inv-free{
  text-align:center;padding:10px 0 4px;
  font-size:0.7rem;font-weight:700;
}
.inv-free .pending{color:var(--a1)}
.inv-free .free{color:var(--g1)}
.inv-free i{margin-right:6px}

.btn-submit{
  width:100%;background:var(--vg);color:#fff;
  font-size:0.85rem;font-weight:800;text-transform:uppercase;letter-spacing:.5px;
  padding:clamp(14px, 2vw, 16px);
  border-radius:var(--rd);border:none;cursor:pointer;
  box-shadow:0 8px 24px rgba(84,82,238,.3);
  transition:transform .3s var(--ease),box-shadow .3s;
  margin-top:6px;
}
.btn-submit:hover{transform:translateY(-2px);box-shadow:0 12px 36px rgba(84,82,238,.45)}
.btn-submit:disabled{opacity:.6;cursor:not-allowed;transform:none!important}

/* ── RESPONSIVE ── */
@media (max-width: 768px){
  .page{padding:12px;}
  .hero{padding:24px 18px;}
  .hero-title{font-size:1.4rem;}
}
@media (max-width: 576px){
  .input-join{flex-wrap:wrap;}
  .input-join .dc-input{border-radius:var(--rd);border-right:1.5px solid var(--border);}
  .input-suffix{border-radius:var(--rd);margin-top:6px;width:100%;justify-content:center;}
}

.fade-up{opacity:0;transform:translateY(18px);animation:fadeUp .55s var(--ease) forwards}
@keyframes fadeUp{to{opacity:1;transform:translateY(0)}}
.d1{animation-delay:.05s}.d2{animation-delay:.1s}.d3{animation-delay:.15s}
</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">

  <!-- ── HERO ── -->
  <div class="hero fade-up d1">
    <div class="hero-bg"></div>
    <div class="hero-grid"></div>
    <div class="hero-content">
      <div class="hero-eyebrow"><span class="hero-dot"></span> Chờ Duyệt Tự Động</div>
      <h1 class="hero-title">
        Đăng Ký Subdomain<br>
        <span class="grad">Miễn Phí & Nhanh Chóng</span>
      </h1>
      <p class="hero-sub">Tạo subdomain miễn phí với đuôi <strong style="color:#818cf8">.khanhcoder.site</strong>. Yêu cầu sẽ được duyệt tự động trong vòng 24h.</p>
    </div>
  </div>

  <!-- ── FORM ── -->
  <div class="form-card fade-up d2">
    <div class="sec-title"><i class="fa-solid fa-link" style="color:var(--v1);font-size:0.9rem"></i> Đăng Ký Subdomain</div>

    <form id="subForm">
      <div class="field-group">
        <label>Tên Subdomain <span class="req">*</span></label>
        <div class="input-join">
          <input type="text" class="dc-input" id="subName" name="name" placeholder="ten-website-cua-ban" required
                 pattern="[a-z0-9\-]+" title="Chỉ nhập chữ thường, số và dấu gạch ngang (-)">
          <span class="input-suffix">.khanhcoder.site</span>
        </div>
        <div class="hint"><i class="fa-regular fa-circle-info"></i> Chỉ sử dụng chữ thường, số và dấu gạch ngang (-), không dấu cách.</div>
      </div>

      <div class="field-group">
        <label>Chọn Mục Đích Sử Dụng</label>
        <select class="dc-select" id="subPurpose" name="purpose">
          <option value="website">🌐 Website / Blog</option>
          <option value="landing">📄 Landing Page</option>
          <option value="api">⚡ API / Backend</option>
          <option value="shop">🛒 Cửa Hàng Trực Tuyến</option>
          <option value="other">📦 Khác</option>
        </select>
      </div>

      <div class="field-group">
        <label>Ghi Chú (Tùy Chọn)</label>
        <input type="text" class="dc-input" id="subNote" name="note" placeholder="Mô tả ngắn về mục đích sử dụng...">
      </div>

      <div class="inv-box">
        <div class="inv-row2"><span class="k">Tên Subdomain</span><span class="v" id="previewSub">—</span></div>
        <div class="inv-row2"><span class="k">Trạng Thái</span><span class="v amber"><i class="fa-solid fa-clock"></i> Chờ duyệt</span></div>
        <hr class="inv-sep">
        <div class="inv-total"><span class="k">Chi Phí</span><span class="v" style="color:#10b981">0đ — Miễn Phí!</span></div>
        <div class="inv-free"><span class="pending"><i class="fa-solid fa-hourglass-half"></i> Yêu cầu sẽ được duyệt trong 24h</span></div>
      </div>

      <button type="submit" class="btn-submit" id="btnCreateSub">
        <i class="fa-solid fa-paper-plane" style="margin-right:8px"></i> Gửi Yêu Cầu
      </button>
    </form>
  </div>

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

<?php require $_SERVER['DOCUMENT_ROOT'].'/hethong/thongbao.php';?>

<script>
$(function(){
    // Preview tên subdomain
    $('#subName').on('input', function(){
        const val = $(this).val().trim().toLowerCase();
        $('#previewSub').text(val ? val + '.khanhcoder.site' : '—');
    });

    // Submit form
    $('#subForm').on('submit', function(e){
        e.preventDefault();
        
        const name = $('#subName').val().trim().toLowerCase();
        if(!name){
            Swal.fire({
                icon: 'warning',
                title: 'Thiếu thông tin',
                text: 'Vui lòng nhập tên subdomain.',
                confirmButtonColor: '#5452ee'
            });
            return;
        }
        if(!/^[a-z0-9\-]+$/.test(name)){
            Swal.fire({
                icon: 'error',
                title: 'Tên không hợp lệ',
                text: 'Chỉ sử dụng chữ thường, số và dấu gạch ngang (-).',
                confirmButtonColor: '#5452ee'
            });
            return;
        }

        const btn = $('#btnCreateSub');
        const originalText = btn.html();
        btn.html('<i class="fa-solid fa-spinner fa-spin"></i> Đang xử lý...').prop('disabled', true);

        // Lấy dữ liệu form
        const formData = new FormData(this);
        formData.append('action', 'create_subdomain');

        // Gửi AJAX
        $.ajax({
            url: 'hethong/create_subdomain.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            timeout: 30000,
            success: function(res) {
                btn.html(originalText).prop('disabled', false);
                
                if(res.status === 'success'){
                    Swal.fire({
                        icon: 'success',
                        title: '✅ Gửi Yêu Cầu Thành Công!',
                        html: `
                            <div style="text-align:left;padding:8px 0">
                                <p><strong>Subdomain:</strong> ${res.subdomain}</p>
                                <p><strong>Trạng thái:</strong> <span style="color:#d97706">⏳ Chờ duyệt</span></p>
                                <p style="margin-top:12px;font-size:0.85rem;color:#8891b0">
                                    <i class="fa-regular fa-clock"></i> Yêu cầu sẽ được duyệt trong vòng 24h.
                                </p>
                                <p style="font-size:0.8rem;color:#8891b0;margin-top:8px;">
                                    <a href="quan-ly-subdomain.php" style="color:#5452ee;text-decoration:none;font-weight:600;">
                                        → Xem danh sách subdomain của bạn
                                    </a>
                                </p>
                            </div>
                        `,
                        confirmButtonColor: '#5452ee',
                        confirmButtonText: 'OK'
                    });
                    // Reset form
                    $('#subName').val('');
                    $('#previewSub').text('—');
                    $('#subNote').val('');
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Lỗi',
                        text: res.message || 'Không thể tạo subdomain.',
                        confirmButtonColor: '#5452ee'
                    });
                }
            },
            error: function(xhr, status, error) {
                btn.html(originalText).prop('disabled', false);
                console.error('AJAX Error:', status, error);
                console.error('Response:', xhr.responseText);
                
                let errorMsg = 'Không thể kết nối đến máy chủ. Vui lòng thử lại.';
                
                // Thử parse response nếu có
                if(xhr.responseText) {
                    try {
                        const res = JSON.parse(xhr.responseText);
                        if(res.message) errorMsg = res.message;
                    } catch(e) {
                        // Nếu không parse được, hiển thị lỗi chi tiết
                        errorMsg = 'Lỗi hệ thống: ' + xhr.status + ' - ' + error;
                        console.log('Raw response:', xhr.responseText);
                    }
                }
                
                Swal.fire({
                    icon: 'error',
                    title: 'Lỗi kết nối',
                    text: errorMsg,
                    confirmButtonColor: '#5452ee'
                });
            }
        });
    });
});
</script>
</body>
</html>