<?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;

// Kiểm tra và tạo bảng nếu chưa có
$table_check = $ketnoi->query("SHOW TABLES LIKE 'history_subdomain'");
if($table_check->num_rows == 0) {
    $sql_create = "CREATE TABLE `history_subdomain` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `username` varchar(100) NOT NULL,
        `user_id` int(11) NOT NULL,
        `subdomain` varchar(200) NOT NULL,
        `purpose` varchar(50) DEFAULT 'website',
        `note` text DEFAULT NULL,
        `status` enum('pending','active','rejected') DEFAULT 'pending',
        `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
        `approved_at` datetime DEFAULT NULL,
        `rejected_at` datetime DEFAULT NULL,
        PRIMARY KEY (`id`),
        UNIQUE KEY `subdomain` (`subdomain`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
    $ketnoi->query($sql_create);
}

// Kiểm tra quyền admin
$is_admin = isset($user['role']) && $user['role'] === 'admin';

// Xử lý hành động
$action = isset($_GET['action']) ? $_GET['action'] : '';
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if($action === 'approve' && $id && $is_admin){
    $ketnoi->query("UPDATE `history_subdomain` SET `status` = 'active', `approved_at` = NOW() WHERE `id` = '$id'");
    header('location: quan-ly-subdomain.php?msg=approved');
    exit();
}

if($action === 'reject' && $id && $is_admin){
    $ketnoi->query("UPDATE `history_subdomain` SET `status` = 'rejected', `rejected_at` = NOW() WHERE `id` = '$id'");
    header('location: quan-ly-subdomain.php?msg=rejected');
    exit();
}

if($action === 'delete' && $id){
    if($is_admin) {
        $ketnoi->query("DELETE FROM `history_subdomain` WHERE `id` = '$id'");
    } else {
        $ketnoi->query("DELETE FROM `history_subdomain` WHERE `id` = '$id' AND `username` = '".$user['username']."'");
    }
    header('location: quan-ly-subdomain.php?msg=deleted');
    exit();
}

// Lấy danh sách subdomain
$where = $is_admin ? "1=1" : "`username` = '".$user['username']."'";
$subdomains = $ketnoi->query("SELECT * FROM `history_subdomain` WHERE $where ORDER BY `id` DESC");

// Thống kê
$stats_result = $ketnoi->query("
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
        SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active,
        SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected
    FROM `history_subdomain` 
    WHERE $where
");
$stats = $stats_result ? $stats_result->fetch_assoc() : ['total'=>0, 'pending'=>0, 'active'=>0, 'rejected'=>0];
?>
<!DOCTYPE html>
<html lang="vi">
<head>
<?php require $_SERVER['DOCUMENT_ROOT'].'/hethong/head2.php';?>
<title>Quản Lý 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:#10b981;
  animation:pulse-dot 2s ease-in-out infinite;
}
@keyframes pulse-dot{
  0%,100%{box-shadow:0 0 0 0 rgba(16,185,129,.6)}
  50%{box-shadow:0 0 0 6px rgba(16,185,129,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;
}

/* ── STATS ── */
.stats-row{
  display:grid;
  grid-template-columns:repeat(4,1fr);
  gap:clamp(12px, 2vw, 16px);
  margin-bottom:clamp(16px, 3vw, 24px);
}
.stat-box{
  background:var(--surface);
  border:1px solid var(--border);
  border-radius:var(--rdm);
  padding:clamp(14px, 3vw, 20px);
  box-shadow:var(--sh0);
  text-align:center;
  transition:transform .25s var(--ease),box-shadow .25s;
}
.stat-box:hover{
  transform:translateY(-3px);
  box-shadow:var(--sh1);
}
.stat-box .num{
  font-size:clamp(1.4rem, 3vw, 2rem);
  font-weight:900;
  font-family:'JetBrains Mono',monospace;
  color:var(--h);
  display:block;
}
.stat-box .lbl{
  font-size:0.65rem;font-weight:700;color:var(--m);
  text-transform:uppercase;letter-spacing:.5px;margin-top:4px;
}
.stat-box.pending .num{color:var(--a1)}
.stat-box.active .num{color:var(--g1)}
.stat-box.rejected .num{color:var(--r1)}
.stat-box.total .num{color:var(--v1)}

/* ── TABLE ── */
.table-wrap{
  background:var(--surface);
  border:1px solid var(--border);
  border-radius:var(--rdl);
  padding:clamp(16px, 3vw, 24px);
  box-shadow:var(--sh0);
  overflow:hidden;
}
.sec-hd{
  display:flex;align-items:center;justify-content:space-between;
  margin-bottom:clamp(12px, 2vw, 16px);
  flex-wrap:wrap;gap:10px;
}
.sec-title{
  font-size:0.8125rem;font-weight:800;color:var(--h);
  letter-spacing:.3px;display:flex;align-items:center;gap:8px;
}
.sec-title::before{
  content:'';display:block;width:3px;height:18px;
  background:var(--vg);border-radius:2px;
}
.sec-actions{
  display:flex;gap:8px;flex-wrap:wrap;
}
.btn-sm{
  display:inline-flex;align-items:center;gap:6px;
  padding:clamp(6px, 1vw, 8px) clamp(12px, 2vw, 16px);
  border-radius:var(--rd);border:none;
  font-size:0.7rem;font-weight:700;
  cursor:pointer;transition:transform .2s,box-shadow .2s;
  text-decoration:none;font-family:'Be Vietnam Pro',sans-serif;
}
.btn-sm:hover{transform:translateY(-1px)}
.btn-primary{background:var(--vg);color:#fff;box-shadow:0 4px 12px rgba(84,82,238,.2)}
.btn-primary:hover{box-shadow:0 6px 20px rgba(84,82,238,.35)}
.btn-success{background:var(--gg);color:#fff;box-shadow:0 4px 12px rgba(5,150,105,.2)}
.btn-success:hover{box-shadow:0 6px 20px rgba(5,150,105,.35)}
.btn-danger{background:var(--rg);color:#fff;box-shadow:0 4px 12px rgba(220,38,38,.2)}
.btn-danger:hover{box-shadow:0 6px 20px rgba(220,38,38,.35)}
.btn-outline{background:var(--s2);border:1.5px solid var(--border);color:var(--b)}
.btn-outline:hover{background:var(--s3);border-color:var(--m)}

.table-scroll{
  overflow-x:auto;
}
table{
  width:100%;border-collapse:collapse;
  font-size:0.8rem;
}
table th{
  text-align:left;padding:clamp(10px, 1.5vw, 14px) clamp(10px, 1.5vw, 16px);
  font-weight:700;color:var(--m);text-transform:uppercase;font-size:0.65rem;
  letter-spacing:.5px;border-bottom:2px solid var(--border);
}
table td{
  padding:clamp(10px, 1.5vw, 14px) clamp(10px, 1.5vw, 16px);
  border-bottom:1px solid var(--border2);
  vertical-align:middle;
}
table tr:last-child td{border-bottom:none}
table tr:hover td{background:var(--s2)}

.status-badge{
  display:inline-flex;align-items:center;gap:5px;
  padding:4px 12px;border-radius:20px;
  font-size:0.65rem;font-weight:700;text-transform:uppercase;
}
.status-badge.pending{background:rgba(217,119,6,.1);color:var(--a1)}
.status-badge.active{background:rgba(5,150,105,.1);color:var(--g1)}
.status-badge.rejected{background:rgba(220,38,38,.1);color:var(--r1)}
.status-badge i{font-size:0.55rem}

.empty-state{
  text-align:center;padding:clamp(40px, 8vw, 60px) 20px;
}
.empty-state i{
  font-size:3rem;color:var(--m);opacity:.3;
  margin-bottom:16px;display:block;
}
.empty-state h4{font-size:1rem;color:var(--h);margin-bottom:6px}
.empty-state p{color:var(--m);font-size:0.8rem}

.actions-cell{
  display:flex;gap:6px;flex-wrap:wrap;
}
.actions-cell .btn-sm{
  padding:4px 10px;font-size:0.6rem;
}

/* ── RESPONSIVE ── */
@media (max-width: 992px){
  .hero{grid-template-columns:1fr;}
}
@media (max-width: 768px){
  .page{padding:12px;}
  .hero{padding:24px 18px;}
  .hero-title{font-size:1.4rem;}
  .stats-row{grid-template-columns:repeat(2,1fr);}
  .sec-hd{flex-direction:column;align-items:stretch;}
  .sec-actions{justify-content:flex-start;}
}
@media (max-width: 576px){
  .stats-row{grid-template-columns:1fr 1fr;}
  table{font-size:0.7rem;}
  table th,table td{padding:8px 6px;}
  .actions-cell{flex-direction:column;}
  .actions-cell .btn-sm{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> <?=$is_admin ? 'Quản Trị Hệ Thống' : 'Quản Lý Cá Nhân'?></div>
      <h1 class="hero-title">
        Quản Lý Subdomain<br>
        <span class="grad"><?=$is_admin ? 'Duyệt & Quản Lý Toàn Bộ' : 'Của Bạn'?></span>
      </h1>
      <p class="hero-sub"><?=$is_admin ? 'Quản lý, duyệt và giám sát tất cả subdomain được tạo trên hệ thống.' : 'Xem và quản lý các subdomain bạn đã tạo.'?></p>
    </div>
  </div>

  <!-- ── STATS ── -->
  <div class="stats-row fade-up d2">
    <div class="stat-box total">
      <span class="num"><?=$stats['total'] ?? 0?></span>
      <span class="lbl">Tổng Cộng</span>
    </div>
    <div class="stat-box pending">
      <span class="num"><?=$stats['pending'] ?? 0?></span>
      <span class="lbl">Chờ Duyệt</span>
    </div>
    <div class="stat-box active">
      <span class="num"><?=$stats['active'] ?? 0?></span>
      <span class="lbl">Đã Duyệt</span>
    </div>
    <div class="stat-box rejected">
      <span class="num"><?=$stats['rejected'] ?? 0?></span>
      <span class="lbl">Từ Chối</span>
    </div>
  </div>

  <!-- ── TABLE ── -->
  <div class="table-wrap fade-up d3">
    <div class="sec-hd">
      <span class="sec-title"><i class="fa-solid fa-list" style="color:var(--v1)"></i> Danh Sách Subdomain</span>
      <div class="sec-actions">
        <a href="tao-subdomain.php" class="btn-sm btn-primary"><i class="fa-solid fa-plus"></i> Tạo Mới</a>
        <?php if(!$is_admin): ?>
        <span class="btn-sm btn-outline" style="cursor:default"><i class="fa-regular fa-clock"></i> Chờ duyệt: <?=$stats['pending']??0?></span>
        <?php endif; ?>
      </div>
    </div>

    <div class="table-scroll">
      <?php if($subdomains && $subdomains->num_rows > 0): ?>
      <table>
        <thead>
          <tr>
            <th>#</th>
            <th>Subdomain</th>
            <th>Mục Đích</th>
            <?php if($is_admin): ?>
            <th>Người Tạo</th>
            <?php endif; ?>
            <th>Trạng Thái</th>
            <th>Ngày Tạo</th>
            <th>Thao Tác</th>
          </tr>
        </thead>
        <tbody>
          <?php $i=1; while($row = $subdomains->fetch_assoc()): 
            $status = $row['status'] ?? 'pending';
            $statusClass = $status === 'active' ? 'active' : ($status === 'rejected' ? 'rejected' : 'pending');
            $statusIcon = $status === 'active' ? 'fa-circle-check' : ($status === 'rejected' ? 'fa-circle-xmark' : 'fa-clock');
          ?>
          <tr>
            <td><?=$i++?></td>
            <td><strong style="color:var(--h)"><?=htmlspecialchars($row['subdomain'])?></strong></td>
            <td><?=htmlspecialchars($row['purpose'] ?? '—')?></td>
            <?php if($is_admin): ?>
            <td><span style="font-weight:600;color:var(--v1)"><?=htmlspecialchars($row['username'])?></span></td>
            <?php endif; ?>
            <td>
              <span class="status-badge <?=$statusClass?>">
                <i class="fa-solid <?=$statusIcon?>"></i>
                <?=$status === 'active' ? 'Đã duyệt' : ($status === 'rejected' ? 'Từ chối' : 'Chờ duyệt')?>
              </span>
            </td>
            <td style="font-size:0.7rem;color:var(--m)"><?=date('d/m/Y H:i', strtotime($row['created_at']))?></td>
            <td>
              <div class="actions-cell">
                <?php if($is_admin && $status === 'pending'): ?>
                <a href="quan-ly-subdomain.php?action=approve&id=<?=$row['id']?>" class="btn-sm btn-success" onclick="return confirm('Duyệt subdomain này?')">
                  <i class="fa-solid fa-check"></i> Duyệt
                </a>
                <a href="quan-ly-subdomain.php?action=reject&id=<?=$row['id']?>" class="btn-sm btn-danger" onclick="return confirm('Từ chối subdomain này?')">
                  <i class="fa-solid fa-xmark"></i> Từ chối
                </a>
                <?php endif; ?>
                
                <?php if($is_admin || $row['username'] === $user['username']): ?>
                <a href="quan-ly-subdomain.php?action=delete&id=<?=$row['id']?>" class="btn-sm btn-outline" onclick="return confirm('Xóa subdomain này?')">
                  <i class="fa-solid fa-trash-can" style="color:var(--r1)"></i>
                </a>
                <?php endif; ?>
              </div>
            </td>
          </tr>
          <?php endwhile; ?>
        </tbody>
      </table>
      <?php else: ?>
      <div class="empty-state">
        <i class="fa-regular fa-folder-open"></i>
        <h4>Chưa có subdomain nào</h4>
        <p><?=$is_admin ? 'Chưa có subdomain nào được tạo trên hệ thống.' : 'Bạn chưa tạo subdomain nào. Hãy tạo ngay!'?></p>
        <a href="tao-subdomain.php" class="btn-sm btn-primary" style="margin-top:12px;display:inline-flex">
          <i class="fa-solid fa-plus"></i> Tạo Subdomain Ngay
        </a>
      </div>
      <?php endif; ?>
    </div>
  </div>

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

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

<!-- ── TOAST MESSAGE ── -->
<?php if(isset($_GET['msg'])): 
  $msg = $_GET['msg'];
  $icon = 'success';
  $title = 'Thành công!';
  $text = '';
  if($msg === 'approved'){ $title = '✅ Đã duyệt subdomain!'; $text = 'Subdomain đã được kích hoạt.'; }
  elseif($msg === 'rejected'){ $icon = 'warning'; $title = '⛔ Đã từ chối!'; $text = 'Subdomain đã bị từ chối.'; }
  elseif($msg === 'deleted'){ $icon = 'info'; $title = '🗑️ Đã xóa!'; $text = 'Subdomain đã được xóa khỏi hệ thống.'; }
?>
<script>
$(function(){
    Swal.fire({
        icon: '<?=$icon?>',
        title: '<?=$title?>',
        text: '<?=$text?>',
        timer: 2500,
        showConfirmButton: false
    });
});
</script>
<?php endif; ?>

</body>
</html>