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

<head>
    <?php require_once('head.php');?>
    <title>Hệ Thống | Danh Sách Đơn Tạo Web</title>
    <?php require_once('nav.php');?>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        .custom-card {
            border: none !important;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05) !important;
            border-radius: 12px !important;
        }
        .table th {
            background-color: #f8fafc !important;
            color: #334155 !important;
            font-weight: 600 !important;
            text-transform: uppercase;
            font-size: 0.8rem;
            letter-spacing: 0.05em;
            vertical-align: middle !important;
        }
        .table td {
            vertical-align: middle !important;
            font-size: 0.9rem;
            color: #475569;
        }
        .badge-status {
            padding: 6px 12px;
            border-radius: 30px;
            font-weight: 600;
            font-size: 0.75rem;
        }
        .pagination-container {
            display: flex;
            justify-content: flex-end;
            margin-top: 15px;
        }
        .page-link {
            border-radius: 6px !important;
            margin: 0 2px;
            color: #475569;
        }
        .page-item.active .page-link {
            background-color: #3b82f6 !important;
            border-color: #3b82f6 !important;
        }
        .btn-action {
            margin: 2px;
            font-weight: 500;
            border-radius: 6px;
        }
    </style>
</head>

<?php
// Xử lý các thao tác thông qua POST an toàn (Prepared Statement)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'], $_POST['id'])) {
    $id = intval($_POST['id']);
    $action = $_POST['action'];
    $status_map = [
        'cho'      => 'cho',
        'xoa'      => 'xoa',
        'duyet'    => 'hoatdong',
        'tamkhoa'  => 'tamkhoa',
        'huy'      => 'thatbai'
    ];

    if (array_key_exists($action, $status_map)) {
        $new_status = $status_map[$action];
        $stmt = $ketnoi->prepare("UPDATE `lich_su_tao_web` SET `status` = ? WHERE `id` = ?");
        $stmt->bind_param("si", $new_status, $id);
        
        if ($stmt->execute()) {
            echo '<script>
                document.addEventListener("DOMContentLoaded", function() {
                    Swal.fire({
                        icon: "success",
                        title: "Thành công!",
                        text: "Đã cập nhật trạng thái đơn hàng thành công.",
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        window.location.href = "/admin/lstaoweb.php";
                    });
                });
            </script>';
        }
        $stmt->close();
    }
}
?>

<body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <div class="content-wrapper" style="background: #f1f5f9;">
            <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 text-dark" style="font-size: 1.6rem;">Quản Lý Đơn Tạo Web</h1>
                        </div>
                        <div class="col-sm-6">
                            <ol class="breadcrumb float-sm-right" style="background: transparent;">
                                <li class="breadcrumb-item"><a href="#" class="text-muted">Home</a></li>
                                <li class="breadcrumb-item active text-primary">Danh sách đơn tạo web</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>

            <section class="content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card custom-card">
                                <div class="card-header bg-white py-3">
                                    <h3 class="card-title font-weight-bold text-secondary mb-0">
                                        <i class="fa-solid fa-list-check text-primary mr-2"></i> Danh Sách Đơn Hàng Hệ Thống
                                    </h3>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table id="datatable1" class="table table-hover table-striped table-bordered text-center mb-0">
                                            <thead>
                                                <tr>
                                                    <th>STT</th>
                                                    <th>Khách hàng</th>
                                                    <th>Tên Miền</th>
                                                    <th>Loại Web</th>
                                                    <th>User Admin</th>
                                                    <th>Pass Admin</th>
                                                    <th>Trạng Thái</th>
                                                    <th>Thời gian mua</th>
                                                    <th>Hết Hạn</th>
                                                    <th style="min-width: 240px;">Thao Tác</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                $i = 1;
                                                $result = mysqli_query($ketnoi, "SELECT * FROM `lich_su_tao_web` ORDER BY `id` DESC");
                                                while ($row = mysqli_fetch_assoc($result)) { 
                                                    // Lấy cấu hình mẫu web an toàn
                                                    $loaiweb_id = intval($row['loaiweb']);
                                                    $site_query = mysqli_query($ketnoi, "SELECT `title` FROM `list_mau_web` WHERE `id` = '$loaiweb_id'");
                                                    $site = mysqli_fetch_assoc($site_query);
                                                ?>
                                                <tr>
                                                    <td><?= $i++; ?></td>
                                                    <td class="font-weight-bold text-dark"><?= htmlspecialchars($row['username']); ?></td>
                                                    <td>
                                                        <a href="http://<?= htmlspecialchars($row['domain']); ?>" target="_blank" class="text-primary font-weight-bold">
                                                            <?= htmlspecialchars($row['domain']); ?> <i class="fa-solid fa-arrow-up-right-from-square style-sub" style="font-size: 10px;"></i>
                                                        </a>
                                                    </td>
                                                    <td><span class="badge bg-light text-dark border p-2"><?= htmlspecialchars($site['title'] ?? 'Không rõ'); ?></span></td>
                                                    <td><code><?= htmlspecialchars($row['user_admin']); ?></code></td>
                                                    <td><code><?= htmlspecialchars($row['pass_admin']); ?></code></td>
                                                    <td>
                                                        <?php 
                                                        // Tối ưu hóa hiển thị Badge tùy trạng thái đơn
                                                        $status = $row['status'];
                                                        if($status == 'hoatdong') echo '<span class="badge badge-status bg-success-subtle text-success border border-success">Hoạt Động</span>';
                                                        elseif($status == 'cho') echo '<span class="badge badge-status bg-warning-subtle text-warning border border-warning">Chờ Duyệt</span>';
                                                        elseif($status == 'tamkhoa') echo '<span class="badge badge-status bg-secondary-subtle text-secondary border border-secondary">Tạm Khóa</span>';
                                                        else echo '<span class="badge badge-status bg-danger-subtle text-danger border border-danger">Đã Hủy/Xóa</span>';
                                                        ?>
                                                    </td>
                                                    <td><small class="text-muted"><?= ngay($row['ngay_mua']); ?></small></td>
                                                    <td><small class="text-muted"><?= ngay($row['ngay_het']); ?></small></td>
                                                    <td>
                                                        <button onclick="submitAction(<?= $row['id']; ?>, 'duyet')" class="btn btn-success btn-sm btn-action"><i class="fa-solid fa-check mr-1"></i>Duyệt</button>
                                                        <button onclick="submitAction(<?= $row['id']; ?>, 'tamkhoa')" class="btn btn-warning btn-sm btn-action text-white"><i class="fa-solid fa-lock mr-1"></i>Khóa</button>
                                                        <button onclick="submitAction(<?= $row['id']; ?>, 'huy')" class="btn btn-info btn-sm btn-action"><i class="fa-solid fa-ban mr-1"></i>Hủy</button>
                                                        <button onclick="submitAction(<?= $row['id']; ?>, 'xoa')" class="btn btn-danger btn-sm btn-action"><i class="fa-solid fa-trash mr-1"></i>Xóa</button>
                                                    </td>
                                                </tr>
                                                <?php } ?>
                                            </tbody>
                                        </table>

                                        <div id="pagination-container" class="pagination-container"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>

        <form id="actionForm" method="POST" action="">
            <input type="hidden" id="form_id" name="id">
            <input type="hidden" id="form_action" name="action">
        </form>

        <aside class="control-sidebar control-sidebar-dark"></aside>
    </div>

    <script>
    function submitAction(id, action) {
        let actionText = "";
        let confirmButtonColor = "#3085d6";
        
        switch(action) {
            case 'duyet': actionText = "kích hoạt và duyệt đơn hàng này"; confirmButtonColor = "#28a745"; break;
            case 'tamkhoa': actionText = "tạm khóa dịch vụ này"; confirmButtonColor = "#ffc107"; break;
            case 'huy': actionText = "hủy bỏ đơn hàng này"; confirmButtonColor = "#17a2b8"; break;
            case 'xoa': actionText = "xóa đơn hàng này khỏi danh sách hoạt động"; confirmButtonColor = "#dc3545"; break;
        }

        Swal.fire({
            title: 'Xác nhận thực hiện?',
            text: "Bạn có chắc chắn muốn " + actionText + " không?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: confirmButtonColor,
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Đồng ý',
            cancelButtonText: 'Hủy bỏ'
        }).then((result) => {
            if (result.isConfirmed) {
                document.getElementById('form_id').value = id;
                document.getElementById('form_action').value = action;
                document.getElementById('actionForm').submit();
            }
        });
    }

    $(document).ready(function() {
        var $table = $('#datatable1');
        var $rows = $table.find('tbody tr');
        var $paginationContainer = $('#pagination-container');
        var limitPerPage = 10;
        var totalPages = Math.ceil($rows.length / limitPerPage);

        if (totalPages > 1) {
            var pagination = '<ul class="pagination">';
            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().slice(0, limitPerPage).show();
            $paginationContainer.find('.page-link').first().addClass('active');

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

                $rows.hide().slice(start, end).show();
                $paginationContainer.find('.page-link').removeClass('active');
                $(this).addClass('active');
            });
        }
    });
    </script>

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

</html>