<?php
// Bật hiển thị lỗi để debug
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Kiểm tra file ketnoi
if(!file_exists('hethong/ketnoi.php')) {
    die('Không tìm thấy file hethong/ketnoi.php');
}

require_once('hethong/ketnoi.php');

// Kiểm tra session
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;

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

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

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

if($action === 'delete' && $id){
    $ketnoi->query("DELETE FROM `history_subdomain` WHERE `id` = '$id'");
    header('location: duyet-subdomain.php?msg=deleted');
    exit();
}

// Lấy danh sách subdomain chờ duyệt
$pending_list = $ketnoi->query("SELECT * FROM `history_subdomain` WHERE `status` = 'pending' ORDER BY `created_at` DESC");

// Lấy danh sách đã duyệt (gần đây)
$approved_list = $ketnoi->query("SELECT * FROM `history_subdomain` WHERE `status` = 'active' ORDER BY `approved_at` DESC LIMIT 10");

// 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`
");
$stats = $stats_result ? $stats_result->fetch_assoc() : ['total'=>0, 'pending'=>0, 'active'=>0, 'rejected'=>0];
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <?php 
    // Kiểm tra file head.php
    if(file_exists('head.php')) {
        require_once('head.php'); 
    } else {
        echo '<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Duyệt Subdomain</title>';
    }
    ?>
    <title>Duyệt Subdomain | Dashboard</title>
    <?php 
    // Kiểm tra file nav.php
    if(file_exists('nav.php')) {
        require_once('nav.php'); 
    }
    ?>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;600;800&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        body { font-family: 'Plus Jakarta Sans', sans-serif; background: #f8fafc; }
        .bento-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 1.5rem; }
        .white-card { 
            background: #ffffff;
            border: 1px solid #e2e8f0;
            border-radius: 24px;
            padding: 24px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
            transition: 0.3s;
        }
        .white-card:hover { transform: translateY(-5px); box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); }
        .stat-val { font-size: 2.25rem; font-weight: 800; color: #1e293b; }
        
        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 4px 14px;
            border-radius: 20px;
            font-size: 0.7rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .status-badge.pending { background: #fef3c7; color: #d97706; }
        .status-badge.active { background: #d1fae5; color: #059669; }
        .status-badge.rejected { background: #fee2e2; color: #dc2626; }
        
        .btn-action {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            padding: 6px 14px;
            border-radius: 12px;
            font-size: 0.7rem;
            font-weight: 700;
            border: none;
            cursor: pointer;
            transition: all 0.2s;
            text-decoration: none;
        }
        .btn-action:hover { transform: translateY(-2px); }
        .btn-approve { background: #059669; color: #fff; }
        .btn-approve:hover { background: #047857; box-shadow: 0 4px 12px rgba(5,150,105,0.3); }
        .btn-reject { background: #dc2626; color: #fff; }
        .btn-reject:hover { background: #b91c1c; box-shadow: 0 4px 12px rgba(220,38,38,0.3); }
        .btn-delete { background: #f1f5f9; color: #64748b; }
        .btn-delete:hover { background: #e2e8f0; color: #dc2626; }
        
        .table-wrap {
            overflow-x: auto;
            border-radius: 16px;
            border: 1px solid #e2e8f0;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.85rem;
        }
        table th {
            background: #f8fafc;
            text-align: left;
            padding: 14px 18px;
            font-weight: 700;
            color: #64748b;
            text-transform: uppercase;
            font-size: 0.65rem;
            letter-spacing: 0.5px;
            border-bottom: 2px solid #e2e8f0;
        }
        table td {
            padding: 14px 18px;
            border-bottom: 1px solid #f1f5f9;
            vertical-align: middle;
        }
        table tr:last-child td { border-bottom: none; }
        table tr:hover td { background: #f8fafc; }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
        }
        .empty-state i {
            font-size: 3rem;
            color: #cbd5e1;
            margin-bottom: 16px;
            display: block;
        }
        .empty-state h4 { font-size: 1rem; color: #1e293b; margin-bottom: 6px; }
        .empty-state p { color: #94a3b8; font-size: 0.85rem; }
        
        .tab-active {
            background: #1e293b;
            color: #fff;
        }
        .tab-inactive {
            background: #f1f5f9;
            color: #64748b;
        }
        .tab-inactive:hover { background: #e2e8f0; }
        
        .wrapper {
            max-width: 1400px;
            margin: 0 auto;
        }
        .content-wrapper {
            min-height: 80vh;
        }
        
        @media (max-width: 768px) {
            .bento-grid { grid-template-columns: 1fr 1fr; }
            table { font-size: 0.75rem; }
            table th, table td { padding: 10px 12px; }
            .btn-action { padding: 4px 10px; font-size: 0.6rem; }
        }
        @media (max-width: 576px) {
            .bento-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body class="text-slate-800">
    <div class="wrapper">
        <div class="content-wrapper bg-transparent p-6 md:p-10">
            
            <!-- Header Section -->
            <div class="mb-10">
                <h1 class="text-3xl font-extrabold text-slate-900">📋 Duyệt Subdomain</h1>
                <p class="text-slate-500">Quản lý và duyệt các yêu cầu subdomain từ người dùng</p>
            </div>

            <!-- Stats Grid -->
            <div class="bento-grid mb-8">
                <div class="white-card">
                    <p class="text-indigo-600 text-xs font-bold uppercase tracking-wider">Tổng Subdomain</p>
                    <div class="stat-val"><?=number_format($stats['total'] ?? 0);?></div>
                </div>
                <div class="white-card">
                    <p class="text-amber-600 text-xs font-bold uppercase tracking-wider">Chờ Duyệt</p>
                    <div class="stat-val text-amber-600"><?=number_format($stats['pending'] ?? 0);?></div>
                </div>
                <div class="white-card">
                    <p class="text-emerald-600 text-xs font-bold uppercase tracking-wider">Đã Duyệt</p>
                    <div class="stat-val text-emerald-600"><?=number_format($stats['active'] ?? 0);?></div>
                </div>
                <div class="white-card">
                    <p class="text-rose-600 text-xs font-bold uppercase tracking-wider">Từ Chối</p>
                    <div class="stat-val text-rose-600"><?=number_format($stats['rejected'] ?? 0);?></div>
                </div>
            </div>

            <!-- Tabs -->
            <div class="flex gap-2 mb-6">
                <button onclick="showTab('pending')" id="tabPending" class="px-6 py-2.5 rounded-xl font-bold text-sm transition tab-active">
                    <i class="fa-regular fa-clock mr-2"></i> Chờ Duyệt
                    <span class="ml-2 bg-white/20 px-2 py-0.5 rounded-full text-xs"><?=$stats['pending'] ?? 0?></span>
                </button>
                <button onclick="showTab('approved')" id="tabApproved" class="px-6 py-2.5 rounded-xl font-bold text-sm transition tab-inactive">
                    <i class="fa-regular fa-circle-check mr-2"></i> Đã Duyệt
                </button>
            </div>

            <!-- ── BẢNG CHỜ DUYỆT ── -->
            <div id="pendingTab" class="bg-white border border-slate-200/80 rounded-[24px] p-6 md:p-8 shadow-sm">
                <div class="flex items-center justify-between mb-6 pb-4 border-b border-slate-100">
                    <div class="flex items-center gap-2 text-slate-900 font-bold text-lg">
                        <i class="fa-regular fa-clock text-amber-500 mr-1"></i> Yêu Cầu Chờ Duyệt
                    </div>
                    <span class="bg-amber-50 text-amber-600 text-xs font-bold px-3 py-1.5 rounded-full">
                        <?=$stats['pending'] ?? 0?> yêu cầu
                    </span>
                </div>

                <div class="table-wrap">
                    <?php if($pending_list && $pending_list->num_rows > 0): ?>
                    <table>
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Subdomain</th>
                                <th>Người Tạo</th>
                                <th>Mục Đích</th>
                                <th>Ngày Tạo</th>
                                <th>Thao Tác</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $i=1; while($row = $pending_list->fetch_assoc()): ?>
                            <tr>
                                <td><?=$i++?></td>
                                <td><strong style="color:#1e293b"><?=htmlspecialchars($row['subdomain'])?></strong></td>
                                <td><span class="text-indigo-600 font-semibold"><?=htmlspecialchars($row['username'])?></span></td>
                                <td><?=htmlspecialchars($row['purpose'] ?? '—')?></td>
                                <td style="font-size:0.75rem;color:#94a3b8"><?=date('d/m/Y H:i', strtotime($row['created_at']))?></td>
                                <td>
                                    <div class="flex gap-1.5 flex-wrap">
                                        <a href="duyet-subdomain.php?action=approve&id=<?=$row['id']?>" 
                                           class="btn-action btn-approve" 
                                           onclick="return confirmAction('Duyệt subdomain <b><?=$row['subdomain']?></b>?', this.href)">
                                            <i class="fa-solid fa-check"></i> Duyệt
                                        </a>
                                        <a href="duyet-subdomain.php?action=reject&id=<?=$row['id']?>" 
                                           class="btn-action btn-reject"
                                           onclick="return confirmAction('Từ chối subdomain <b><?=$row['subdomain']?></b>?', this.href)">
                                            <i class="fa-solid fa-xmark"></i> Từ chối
                                        </a>
                                        <a href="duyet-subdomain.php?action=delete&id=<?=$row['id']?>" 
                                           class="btn-action btn-delete"
                                           onclick="return confirmAction('Xóa subdomain <b><?=$row['subdomain']?></b>?', this.href)">
                                            <i class="fa-solid fa-trash-can"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                    <?php else: ?>
                    <div class="empty-state">
                        <i class="fa-regular fa-check-circle text-emerald-400"></i>
                        <h4>Không có yêu cầu chờ duyệt</h4>
                        <p>Tất cả subdomain đã được xử lý.</p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- ── BẢNG ĐÃ DUYỆT ── -->
            <div id="approvedTab" class="bg-white border border-slate-200/80 rounded-[24px] p-6 md:p-8 shadow-sm hidden">
                <div class="flex items-center justify-between mb-6 pb-4 border-b border-slate-100">
                    <div class="flex items-center gap-2 text-slate-900 font-bold text-lg">
                        <i class="fa-regular fa-circle-check text-emerald-500 mr-1"></i> Subdomain Đã Duyệt
                    </div>
                    <span class="bg-emerald-50 text-emerald-600 text-xs font-bold px-3 py-1.5 rounded-full">
                        <?=$stats['active'] ?? 0?> đã duyệt
                    </span>
                </div>

                <div class="table-wrap">
                    <?php if($approved_list && $approved_list->num_rows > 0): ?>
                    <table>
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Subdomain</th>
                                <th>Người Tạo</th>
                                <th>Mục Đích</th>
                                <th>Ngày Duyệt</th>
                                <th>Trạng Thái</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $i=1; while($row = $approved_list->fetch_assoc()): ?>
                            <tr>
                                <td><?=$i++?></td>
                                <td><strong style="color:#1e293b"><?=htmlspecialchars($row['subdomain'])?></strong></td>
                                <td><span class="text-indigo-600 font-semibold"><?=htmlspecialchars($row['username'])?></span></td>
                                <td><?=htmlspecialchars($row['purpose'] ?? '—')?></td>
                                <td style="font-size:0.75rem;color:#94a3b8"><?=date('d/m/Y H:i', strtotime($row['approved_at']))?></td>
                                <td>
                                    <span class="status-badge active">
                                        <i class="fa-solid fa-circle-check"></i> Đã duyệt
                                    </span>
                                </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 được duyệt</h4>
                        <p>Hãy duyệt các yêu cầu từ người dùng.</p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

        </div>
    </div>

    <?php 
    // Kiểm tra file foot.php
    if(file_exists('foot.php')) {
        require_once('foot.php'); 
    }
    ?>

    <script>
        function showTab(tab) {
            // Ẩn cả 2 tab
            document.getElementById('pendingTab').classList.add('hidden');
            document.getElementById('approvedTab').classList.add('hidden');
            
            // Reset style tabs
            document.getElementById('tabPending').className = 'px-6 py-2.5 rounded-xl font-bold text-sm transition tab-inactive';
            document.getElementById('tabApproved').className = 'px-6 py-2.5 rounded-xl font-bold text-sm transition tab-inactive';
            
            // Hiện tab được chọn
            if(tab === 'pending') {
                document.getElementById('pendingTab').classList.remove('hidden');
                document.getElementById('tabPending').className = 'px-6 py-2.5 rounded-xl font-bold text-sm transition tab-active';
            } else {
                document.getElementById('approvedTab').classList.remove('hidden');
                document.getElementById('tabApproved').className = 'px-6 py-2.5 rounded-xl font-bold text-sm transition tab-active';
            }
        }

        function confirmAction(message, url) {
            Swal.fire({
                title: 'Xác nhận?',
                html: message,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#059669',
                cancelButtonColor: '#dc2626',
                confirmButtonText: 'Xác nhận',
                cancelButtonText: 'Hủy'
            }).then((result) => {
                if(result.isConfirmed) {
                    window.location.href = url;
                }
            });
            return false;
        }

        <?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 và sẵn sàng sử dụng.'; 
            }
            elseif($msg === 'rejected'){ 
                $icon = 'warning'; 
                $title = '⛔ Đã từ chối!'; 
                $text = 'Yêu cầu subdomain đã bị từ chối.'; 
            }
            elseif($msg === 'deleted'){ 
                $icon = 'info'; 
                $title = '🗑️ Đã xóa!'; 
                $text = 'Subdomain đã được xóa khỏi hệ thống.'; 
            }
        ?>
        $(document).ready(function() {
            Swal.fire({
                icon: '<?=$icon?>',
                title: '<?=$title?>',
                text: '<?=$text?>',
                timer: 3000,
                showConfirmButton: false,
                toast: true,
                position: 'top-end'
            });
        });
        <?php endif; ?>
    </script>
</body>
</html>