<!DOCTYPE html>
<html lang="vi">

<head>
    <?php require_once('head.php');?>
    <title>AdminLTE 3 | Hệ Thống Quản Lý Tên Miền Cao Cấp</title>
    <?php require_once('nav.php');?>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">

    <style>
        body { font-family: 'Inter', sans-serif !important; background-color: #f8fafc; }
        .content-wrapper { background: #f8fafc !important; }

        /* Khối chỉ số đo lường (SaaS Widget) */
        .metric-card {
            background: #ffffff;
            border: 1px solid #e2e8f0;
            border-radius: 14px;
            padding: 20px;
            box-shadow: 0 4px 6px -1px rgba(15, 23, 42, 0.02);
            display: flex;
            align-items: center;
            gap: 16px;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .metric-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 15px -3px rgba(15, 23, 42, 0.05);
        }
        .metric-icon {
            width: 48px; height: 48px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.3rem;
        }
        .metric-info h5 { margin: 0 0 4px 0; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; color: #64748b; font-weight: 600; }
        .metric-info p { margin: 0; font-size: 1.4rem; font-weight: 700; color: #0f172a; }

        /* Card container của Bảng dữ liệu */
        .premium-card {
            border: none !important;
            box-shadow: 0 10px 30px rgba(15, 23, 42, 0.04) !important;
            border-radius: 16px !important;
            background: #ffffff;
            overflow: hidden;
            border: 1px solid #e2e8f0 !important;
        }

        /* Ô tìm kiếm bo tròn tinh tế */
        .search-box-container {
            display: flex; align-items: center; background: #f8fafc; border: 1px solid #cbd5e1; border-radius: 99px; padding: 6px 16px; width: 300px; transition: all 0.2s ease;
        }
        .search-box-container:focus-within { border-color: #6366f1; box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1); background: #ffffff; }
        .search-box-container input { border: none; background: transparent; font-size: 0.85rem; color: #1e293b; width: 100%; margin-left: 8px; }
        .search-box-container input:focus { outline: none; }
        .search-box-container i { color: #94a3b8; }

        /* Cấu trúc thiết kế Bảng phẳng hiện đại */
        .premium-table { border-collapse: separate !important; border-spacing: 0 !important; border: none !important; }
        .premium-table thead th {
            background-color: #f8fafc !important; color: #475569 !important; font-weight: 600 !important; text-transform: uppercase; font-size: 0.75rem !important; letter-spacing: 0.05em; padding: 18px 16px !important; border: none !important; border-bottom: 2px solid #e2e8f0 !important;
        }
        .premium-table tbody td { padding: 18px 16px !important; vertical-align: middle !important; border-bottom: 1px solid #f1f5f9 !important; font-size: 0.9rem; color: #334155; }
        .premium-table tbody tr { transition: background-color 0.15s; }
        .premium-table tbody tr:hover td { background-color: #f8fafc; }

        /* Gắn tag trạng thái dạng Soft Badge */
        .badge-soft { padding: 6px 12px; border-radius: 8px; font-weight: 600; font-size: 0.75rem; display: inline-flex; align-items: center; gap: 6px; }
        .badge-soft-success { background-color: #d1fae5; color: #065f46; }
        .badge-soft-warning { background-color: #fef3c7; color: #92400e; }
        .badge-soft-danger { background-color: #fee2e2; color: #991b1b; }

        /* Các nút Action phẳng mượt */
        .btn-action { padding: 7px 14px; border-radius: 8px; font-size: 0.8rem; font-weight: 600; display: inline-flex; align-items: center; gap: 6px; border: none; transition: all 0.2s; }
        .btn-action-edit { background: #eff6ff; color: #1e40af; }
        .btn-action-edit:hover { background: #dbeafe; transform: translateY(-1px); }
        .btn-action-delete { background: #fff1f2; color: #991b1b; margin-left: 6px; }
        .btn-action-delete:hover { background: #ffe4e6; transform: translateY(-1px); }

        /* Phân trang cuối trang */
        .pagination-container { display: flex; justify-content: flex-end; padding: 20px; border-top: 1px solid #f1f5f9; }
        .page-link { border: 1px solid #e2e8f0 !important; border-radius: 8px !important; margin: 0 3px; color: #475569; padding: 6px 14px; font-size: 0.85rem; font-weight: 500; }
        .page-item.active .page-link { background-color: #4f46e5 !important; border-color: #4f46e5 !important; color: #fff !important; box-shadow: 0 4px 10px rgba(79, 70, 229, 0.2); }
    </style>
</head>

<?php
// XỬ LÝ XÓA AN TOÀN CHỐNG SQL INJECTION
if (isset($_GET['delete'])) {
    $delete = intval($_GET['delete']);
    $stmt = $ketnoi->prepare("DELETE FROM `history_domain` WHERE `id` = ?");
    $stmt->bind_param("i", $delete);
    
    if ($stmt->execute()) {
        echo '<script>
            document.addEventListener("DOMContentLoaded", function() {
                Swal.fire({ icon: "success", title: "Thành Công", text: "Đã gỡ bỏ tên miền khỏi cơ sở dữ liệu.", timer: 1500, showConfirmButton: false })
                .then(() => { window.location.href = "chuyen-muc.php"; });
            });
        </script>';
    } else {
        echo '<script>
            document.addEventListener("DOMContentLoaded", function() {
                Swal.fire({ icon: "error", title: "Thất Bại", text: "Lỗi kết nối máy chủ dữ liệu.", confirmButtonText: "Đóng" });
            });
        </script>';
    }
    $stmt->close();
}

// KHỞI TẠO BỘ ĐẾM TRẠNG THÁI TRỰC QUAN
$count_active = mysqli_fetch_assoc(mysqli_query($ketnoi, "SELECT COUNT(*) AS c FROM `history_domain` WHERE `status`='1' OR `status`='active'"))['c'];
$count_pending = mysqli_fetch_assoc(mysqli_query($ketnoi, "SELECT COUNT(*) AS c FROM `history_domain` WHERE `status`='0' OR `status`='pending'"))['c'];
$count_total = mysqli_fetch_assoc(mysqli_query($ketnoi, "SELECT COUNT(*) AS c FROM `history_domain`"))['c'];
?>

<body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <div class="content-wrapper">
            <div class="content-header">
                <div class="container-fluid">
                    <div class="row mb-3 align-items-center">
                        <div class="col-sm-6">
                            <h1 class="m-0 font-weight-bold" style="color: #0f172a; font-size: 1.6rem; letter-spacing: -0.02em;">Trung tâm Kiểm soát Tên Miền</h1>
                        </div>
                        <div class="col-sm-6">
                            <ol class="breadcrumb float-sm-right">
                                <li class="breadcrumb-item"><a href="#" class="text-muted">Hệ thống</a></li>
                                <li class="breadcrumb-item active">Quản lý Domain</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>

            <section class="content">
                <div class="container-fluid">
                    
                    <div class="row mb-4">
                        <div class="col-md-4 mb-3">
                            <div class="metric-card">
                                <div class="metric-icon" style="background: #e0e7ff; color: #4f46e5;"><i class="fas fa-globe"></i></div>
                                <div class="metric-info">
                                    <h5>Tổng số lượng miền</h5>
                                    <p><?=number_format($count_total);?></p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <div class="metric-card">
                                <div class="metric-icon" style="background: #d1fae5; color: #059669;"><i class="fas fa-check-shield"></i></div>
                                <div class="metric-info">
                                    <h5>Đang hoạt động (Active)</h5>
                                    <p><?=number_format($count_active);?></p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <div class="metric-card">
                                <div class="metric-icon" style="background: #fef3c7; color: #d97706;"><i class="fas fa-hourglass-start"></i></div>
                                <div class="metric-info">
                                    <h5>Đơn chờ xử lý</h5>
                                    <p><?=number_format($count_pending);?></p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-12">
                            <div class="card premium-card">
                                <div class="card-header bg-white py-3 d-flex align-items-center justify-content-between flex-wrap gap-3">
                                    <h3 class="card-title font-weight-bold mb-0" style="font-size: 1.1rem; color: #0f172a;">
                                        <i class="fas fa-database mr-2 text-indigo" style="color: #4f46e5;"></i> Cơ sở dữ liệu lịch sử đăng ký tên miền
                                    </h3>
                                    <div class="search-box-container">
                                        <i class="fas fa-search"></i>
                                        <input type="text" id="tableSearch" placeholder="Gõ tên miền, khách hàng để lọc...">
                                    </div>
                                </div>
                                
                                <div class="card-body p-0">
                                    <div class="table-responsive">
                                        <table id="datatable1" class="table premium-table text-center mb-0">
                                            <thead>
                                                <tr>
                                                    <th style="width: 70px">Mã ID</th>
                                                    <th style="text-align: left; min-width: 180px;">Tên Miền Đăng Ký</th>
                                                    <th>Khách hàng</th>
                                                    <th>Cặp Nameserver</th>
                                                    <th>Trạng thái</th>
                                                    <th>Ngày kích hoạt</th>
                                                    <th>Ngày hết hạn</th>
                                                    <th style="width: 200px">Quản lý</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                $result = mysqli_query($ketnoi, "SELECT * FROM `history_domain` ORDER BY `id` DESC");
                                                while($row = mysqli_fetch_assoc($result)) {
                                                ?>
                                                <tr>
                                                    <td class="font-weight-bold text-muted">#<?=$row['id'];?></td>
                                                    <td style="text-align: left;" class="font-weight-bold text-dark">
                                                        <i class="fas fa-server mr-2 text-slate-400" style="font-size: 0.85rem; color:#94a3b8;"></i><?=htmlspecialchars($row['domain']);?>
                                                    </td>
                                                    <td><span class="badge badge-light text-secondary py-1 px-2"><i class="far fa-user mr-1"></i><?=htmlspecialchars($row['username']);?></span></td>
                                                    <td class="text-muted" style="font-size: 0.85rem; font-family: monospace;"><?=htmlspecialchars($row['nameserver']);?></td>
                                                    <td>
                                                        <?php 
                                                        $st = $row['status'] ?? '';
                                                        $st_text = function_exists('status') ? status($st) : $st;
                                                        
                                                        if (strpos(strtolower($st_text), 'thành công') !== false || $st == '1' || strtolower($st) == 'active') {
                                                            echo '<span class="badge-soft badge-soft-success"><i class="fas fa-check-circle mr-1"></i> ' . htmlspecialchars($st_text) . '</span>';
                                                        } elseif (strpos(strtolower($st_text), 'chờ') !== false || $st == '0' || strtolower($st) == 'pending') {
                                                            echo '<span class="badge-soft badge-soft-warning"><i class="fas fa-spinner fa-spin mr-1"></i> ' . htmlspecialchars($st_text) . '</span>';
                                                        } else {
                                                            echo '<span class="badge-soft badge-soft-danger"><i class="fas fa-minus-circle mr-1"></i> ' . htmlspecialchars($st_text) . '</span>';
                                                        }
                                                        ?>
                                                    </td>
                                                    <td class="text-muted" style="font-size: 0.85rem;"><?=function_exists('ngay') ? ngay($row['ngay_mua']) : $row['ngay_mua'];?></td>
                                                    <td class="text-muted" style="font-size: 0.85rem;"><?=function_exists('ngay') ? ngay($row['ngay_het']) : $row['ngay_het'];?></td>
                                                    <td>
                                                        <a href="edit-lsdomain.php?id=<?=$row['id'];?>" class="btn-action btn-action-edit">
                                                            <i class="fas fa-pen"></i> Sửa
                                                        </a>
                                                        <a href="javascript:void(0);" onclick="confirmDelete(<?=$row['id'];?>)" class="btn-action btn-action-delete">
                                                            <i class="fas fa-trash-alt"></i> Xóa
                                                        </a>
                                                    </td>
                                                </tr>
                                                <?php } ?>
                                            </tbody>
                                        </table>
                                        
                                        <div id="pagination-container" class="pagination-container"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </section>
        </div>
    </div>

    <script>
    // Thay thế hộp confirm thô sơ bằng SweetAlert2 tinh tế
    function confirmDelete(id) {
        Swal.fire({
            title: "Bạn chắc chắn chứ?",
            text: "Dữ liệu cấu hình tên miền này sẽ bị gỡ vĩnh viễn khỏi cơ sở dữ liệu!",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#ef4444",
            cancelButtonColor: "#64748b",
            confirmButtonText: "Đồng ý, xóa ngay!",
            cancelButtonText: "Hủy"
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = "?delete=" + id;
            }
        });
    }

    $(document).ready(function() {
        var $table = $('#datatable1');
        var $rows = $table.find('tbody tr');
        var $paginationContainer = $('#pagination-container');
        var limitPerPage = 10; // Giới hạn hiển thị tối đa 10 dòng/trang

        function runPagination(filteredRows) {
            $paginationContainer.empty();
            var totalPages = Math.ceil(filteredRows.length / limitPerPage);

            if (totalPages > 1) {
                var pagination = '<ul class="pagination mb-0">';
                for (var i = 1; i <= totalPages; i++) {
                    pagination += '<li class="page-item"><a class="page-link" href="javascript:void(0);">' + i + '</a></li>';
                }
                pagination += '</ul>';
                
                $paginationContainer.html(pagination).show();
                $rows.hide();
                filteredRows.slice(0, limitPerPage).show();
                $paginationContainer.find('.page-link').first().addClass('active');

                $paginationContainer.off('click', '.page-link').on('click', '.page-link', function() {
                    var currentPage = parseInt($(this).text());
                    var start = (currentPage - 1) * limitPerPage;
                    var end = start + limitPerPage;

                    $rows.hide();
                    filteredRows.slice(start, end).show();
                    $paginationContainer.find('.page-link').removeClass('active');
                    $(this).addClass('active');
                });
            } else {
                $paginationContainer.hide();
                $rows.hide();
                filteredRows.show();
            }
        }

        // Kích hoạt hệ thống phân trang ban đầu
        runPagination($rows);

        // Bộ lọc tìm kiếm thời gian thực (Real-time Filter) tốc độ cao
        $('#tableSearch').on('keyup', function() {
            var value = $(this).val().toLowerCase();
            var $filtered = $rows.filter(function() {
                return $(this).text().toLowerCase().indexOf(value) > -1;
            });

            runPagination($filtered);

            if($filtered.length === 0) {
                if($('#empty-row-msg').length === 0) {
                    $table.find('tbody').append('<tr id="empty-row-msg"><td colspan="8" class="text-muted py-4"><i class="fas fa-folder-open mr-2"></i>Hệ thống không tìm thấy kết quả phù hợp</td></tr>');
                }
            } else {
                $('#empty-row-msg').remove();
            }
        });
    });
    </script>

    <?php require_once('foot.php');?>
</body>
</html>