<?php
if (!defined('IN_SITE')) {
    die('The Request Not Found');
}

require_once(__DIR__ . '/Header.php');
require_once(__DIR__ . '/Sidebar.php');
require_once(__DIR__ . '/../../../core/is_user.php');

CheckLogin();
CheckAdmin();

$title = 'Quản Lý Thành Viên | ' . $DVR->site('title');
$body = [
    'title' => 'Danh sách GDV',
    'header' => '',
    'footer' => ''
];

$page  = !empty($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$limit = !empty($_GET['limit']) ? max(1, (int)$_GET['limit']) : 10;

$id           = !empty($_GET['id']) ? xss(trim($_GET['id'])) : '';
$name         = !empty($_GET['name']) ? xss(trim($_GET['name'])) : '';
$ngay         = !empty($_GET['ngay']) ? xss(trim($_GET['ngay'])) : '';
$role         = !empty($_GET['role']) ? xss(trim($_GET['role'])) : '';
$shortByDate  = !empty($_GET['shortByDate']) ? xss(trim($_GET['shortByDate'])) : '';

$where = "1=1";
$order_by = "ORDER BY `id` DESC";

if ($id !== '') {
    $where .= " AND `id` = '" . $id . "'";
}

if ($name !== '') {
    $where .= " AND `name` LIKE '%" . $name . "%'";
}

if ($ngay !== '') {
    $where .= " AND `ngay` LIKE '%" . $ngay . "%'";
}

if ($role !== '') {
    $where .= " AND `dich_vu` = '" . $role . "'";
}

// Lọc theo ngày
if ($shortByDate == '1') {
    // Hôm nay
    $today = date('Y-m-d');
    $where .= " AND DATE(`ngay`) = '{$today}'";
} elseif ($shortByDate == '4') {
    // Hôm qua
    $yesterday = date('Y-m-d', strtotime('-1 day'));
    $where .= " AND DATE(`ngay`) = '{$yesterday}'";
} elseif ($shortByDate == '2') {
    // Tuần này
    $startOfWeek = date('Y-m-d', strtotime('monday this week'));
    $endOfWeek   = date('Y-m-d', strtotime('sunday this week'));
    $where .= " AND DATE(`ngay`) BETWEEN '{$startOfWeek}' AND '{$endOfWeek}'";
} elseif ($shortByDate == '3') {
    // Tháng này
    $startOfMonth = date('Y-m-01');
    $endOfMonth   = date('Y-m-t');
    $where .= " AND DATE(`ngay`) BETWEEN '{$startOfMonth}' AND '{$endOfMonth}'";
}

// Tổng bản ghi theo bộ lọc
$totalRow = $DVR->get_row("SELECT COUNT(*) AS total FROM `gdv` WHERE {$where}");
$totalItems = (int)($totalRow['total'] ?? 0);
$totalPages = max(1, (int)ceil($totalItems / $limit));

if ($page > $totalPages) {
    $page = $totalPages;
}

$from = ($page - 1) * $limit;

// Danh sách dữ liệu
$listGDV = $DVR->get_list("SELECT * FROM `gdv` WHERE {$where} {$order_by} LIMIT {$from},{$limit}");

// Hàm tạo URL phân trang
function buildPageUrl($pageNum, $id, $name, $ngay, $role, $limit, $shortByDate)
{
    return '/Cpanel/list-gdv?id=' . urlencode($id)
        . '&name=' . urlencode($name)
        . '&ngay=' . urlencode($ngay)
        . '&role=' . urlencode($role)
        . '&limit=' . urlencode($limit)
        . '&shortByDate=' . urlencode($shortByDate)
        . '&page=' . (int)$pageNum;
}
?>

<div class="main-content app-content">
    <div class="container-fluid">
        <div class="d-md-flex d-block align-items-center justify-content-between my-4 page-header-breadcrumb">
            <h1 class="page-title fw-semibold fs-18 mb-0">Danh Sách GDV</h1>
            <div class="ms-md-1 ms-0">
                <nav>
                    <ol class="breadcrumb mb-0">
                        <li class="breadcrumb-item active" aria-current="page">Danh Sách GDV</li>
                    </ol>
                </nav>
            </div>
        </div>

        <div class="row">
            <div class="col-xl-12">
                <div class="card custom-card">
                    <div class="card-header justify-content-between">
                        <div class="card-title">
                            DANH SÁCH GDV
                        </div>
                    </div>

                    <div class="card-body">
                        <form action="" class="align-items-center mb-3" name="formSearch" method="GET">
                            <input type="hidden" value="<?= htmlspecialchars($getUser['token'] ?? '') ?>" id="token">

                            <div class="row row-cols-lg-auto g-3 mb-3">
                                <div class="col-lg col-md-4 col-6">
                                    <input class="form-control" type="number" value="<?= htmlspecialchars($id) ?>" name="id" placeholder="ID GDV">
                                </div>

                                <div class="col-lg col-md-4 col-6">
                                    <input class="form-control" type="text" value="<?= htmlspecialchars($name) ?>" name="name" placeholder="Username">
                                </div>

                                <div class="col-lg col-md-4 col-6">
                                    <input type="text" name="ngay" class="form-control form-control-sm" id="daterange" value="<?= htmlspecialchars($ngay) ?>" placeholder="Chọn thời gian">
                                </div>

                                <div class="col-lg col-md-4 col-6">
                                    <select name="role" class="form-control">
                                        <option value="">Vai trò</option>
                                        <?php foreach ($DVR->get_list("SELECT * FROM `category`") as $dvr) : ?>
                                            <option value="<?= htmlspecialchars($dvr['code']) ?>" <?= ($role == $dvr['code']) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($dvr['code']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <div class="col-12">
                                    <button class="btn btn-hero btn-primary">
                                        <i class="fa fa-search"></i> Search
                                    </button>
                                    <a class="btn btn-hero btn-danger" href="/Cpanel/list-gdv">
                                        <i class="fa fa-trash"></i> Clear filter
                                    </a>
                                </div>
                            </div>

                            <div class="top-filter d-flex flex-wrap gap-3 justify-content-between align-items-center">
                                <div class="filter-show">
                                    <label class="filter-label">Show :</label>
                                    <select name="limit" onchange="this.form.submit()" class="form-select filter-select">
                                        <option <?= ($limit == 5) ? 'selected' : ''; ?> value="5">5</option>
                                        <option <?= ($limit == 10) ? 'selected' : ''; ?> value="10">10</option>
                                        <option <?= ($limit == 20) ? 'selected' : ''; ?> value="20">20</option>
                                        <option <?= ($limit == 50) ? 'selected' : ''; ?> value="50">50</option>
                                        <option <?= ($limit == 100) ? 'selected' : ''; ?> value="100">100</option>
                                        <option <?= ($limit == 500) ? 'selected' : ''; ?> value="500">500</option>
                                        <option <?= ($limit == 1000) ? 'selected' : ''; ?> value="1000">1.000</option>
                                        <option <?= ($limit == 5000) ? 'selected' : ''; ?> value="5000">5.000</option>
                                        <option <?= ($limit == 10000) ? 'selected' : ''; ?> value="10000">10.000</option>
                                    </select>
                                </div>

                                <div class="filter-short">
                                    <label class="filter-label">Short by Date:</label>
                                    <select name="shortByDate" onchange="this.form.submit()" class="form-select filter-select">
                                        <option value="" <?= ($shortByDate == '') ? 'selected' : ''; ?>>Tất cả</option>
                                        <option value="1" <?= ($shortByDate == '1') ? 'selected' : ''; ?>>Hôm nay</option>
                                        <option value="4" <?= ($shortByDate == '4') ? 'selected' : ''; ?>>Hôm qua</option>
                                        <option value="2" <?= ($shortByDate == '2') ? 'selected' : ''; ?>>Tuần này</option>
                                        <option value="3" <?= ($shortByDate == '3') ? 'selected' : ''; ?>>Tháng này</option>
                                    </select>
                                </div>
                            </div>
                        </form>

                        <div class="table-responsive table-wrapper mb-3">
                            <table class="table text-nowrap table-striped table-hover table-bordered">
                                <thead>
                                    <tr>
                                        <th class="text-center">
                                            <div class="form-check form-check-md d-flex align-items-center">
                                                <input type="checkbox" class="form-check-input" name="check_all" id="check_all_checkbox_users" value="1">
                                            </div>
                                        </th>
                                        <th scope="col">Username</th>
                                        <th scope="col">Ảnh</th>
                                        <th scope="col" class="text-center">Số Tiền Bảo Hiểm</th>
                                        <th scope="col" class="text-center">Số ĐT</th>
                                        <th scope="col" class="text-center">ID FB</th>
                                        <th scope="col" class="text-center">Dịch Vụ</th>
                                        <th scope="col" class="text-center">Ngày Cọc</th>
                                        <th scope="col" class="text-center">Thao tác</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (!empty($listGDV)) : ?>
                                        <?php foreach ($listGDV as $row) : ?>
                                            <tr>
                                                <td class="text-center">
                                                    <div class="form-check form-check-md d-flex align-items-center">
                                                        <input type="checkbox" class="form-check-input checkbox_users" data-id="<?= (int)$row['id'] ?>" name="checkbox_users" value="<?= (int)$row['id'] ?>">
                                                    </div>
                                                </td>

                                                <td>
                                                    <a class="text-primary" href="<?= BASE_URL('Cpanel/gdv-edit/') . (int)$row['id'] ?>">
                                                        <?= htmlspecialchars($row['name']) ?> [ID <?= (int)$row['id'] ?>]
                                                    </a>
                                                </td>

                                                <td>
                                                    <img src="<?= htmlspecialchars($row['image']) ?>" style="border-radius: 10px;" alt="pic" height="60">
                                                </td>

                                                <td class="text-right">
                                                    <b style="color:blue;"><?= format_cash($row['money']) ?>đ</b>
                                                </td>

                                                <td class="text-right">
                                                    <b style="color:red;"><?= htmlspecialchars($row['sdt']) ?></b>
                                                </td>

                                                <td class="text-right">
                                                    <b><?= htmlspecialchars($row['id_fb']) ?></b>
                                                </td>

                                                <td class="text-center">
                                                    <?= htmlspecialchars($row['dich_vu']) ?>
                                                </td>

                                                <td class="text-center">
                                                    <?= htmlspecialchars($row['ngay']) ?>
                                                </td>

                                                <td class="text-center fs-base">
                                                    <a href="<?= BASE_URL('Cpanel/gdv-edit/') . (int)$row['id'] ?>" class="btn btn-sm btn-primary shadow-primary btn-wave waves-effect waves-light">
                                                        <i class="fa fa-fw fa-edit"></i> Edit
                                                    </a>
                                                    <a href="javascript:void(0);" onclick="RemoveRow(<?= (int)$row['id'] ?>)" class="btn btn-sm btn-danger shadow-danger btn-wave waves-effect waves-light">
                                                        <i class="fas fa-trash"></i> Delete
                                                    </a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else : ?>
                                        <tr>
                                            <td colspan="9" class="text-center">Không có dữ liệu</td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>

                                <tfoot>
                                    <tr>
                                        <td colspan="9">
                                            <div class="btn-list">
                                                <button type="button" onclick="confirmDeleteAccount()" class="btn btn-outline-danger shadow-danger btn-wave btn-sm waves-effect waves-light">
                                                    <i class="fa-solid fa-trash"></i> XÓA GDV
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>

                        <div class="row">
                            <div class="col-sm-12 col-md-12 mb-3">
                                <div class="pagination-style-1">
                                    <div class="d-flex justify-content-center">
                                        <div class="paging_simple_numbers">
                                            <ul class="pagination">

                                                <?php if ($page > 1): ?>
                                                    <li class="page-item previous">
                                                        <a class="page-link" href="<?= buildPageUrl($page - 1, $id, $name, $ngay, $role, $limit, $shortByDate) ?>">Prev</a>
                                                    </li>
                                                <?php endif; ?>

                                                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                                    <?php if ($i == $page): ?>
                                                        <li class="page-item active">
                                                            <a class="page-link link" href="javascript:void(0);"><?= $i ?></a>
                                                        </li>
                                                    <?php elseif ($i <= 3 || $i > $totalPages - 3 || abs($i - $page) <= 1): ?>
                                                        <li class="page-item">
                                                            <a class="page-link link" href="<?= buildPageUrl($i, $id, $name, $ngay, $role, $limit, $shortByDate) ?>"><?= $i ?></a>
                                                        </li>
                                                    <?php elseif ($i == 4 && $page > 5): ?>
                                                        <li class="page-item disabled">
                                                            <a class="page-link link" href="javascript:void(0);">...</a>
                                                        </li>
                                                    <?php elseif ($i == $totalPages - 3 && $page < $totalPages - 4): ?>
                                                        <li class="page-item disabled">
                                                            <a class="page-link link" href="javascript:void(0);">...</a>
                                                        </li>
                                                    <?php endif; ?>
                                                <?php endfor; ?>

                                                <?php if ($page < $totalPages): ?>
                                                    <li class="page-item next">
                                                        <a class="page-link" href="<?= buildPageUrl($page + 1, $id, $name, $ngay, $role, $limit, $shortByDate) ?>">Next</a>
                                                    </li>
                                                <?php endif; ?>

                                            </ul>
                                        </div>
                                    </div>
                                </div>

                                <div class="text-center mt-2">
                                    Tổng: <b><?= $totalItems ?></b> bản ghi
                                </div>
                            </div>
                        </div>

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

<script>
function RemoveRow(id) {
    cuteAlert({
        type: "question",
        title: "Xác Nhận Xóa GDV",
        message: "Bạn có chắc chắn muốn xóa GDV ID " + id + " không?",
        confirmText: "Đồng Ý",
        cancelText: "Hủy"
    }).then((e) => {
        if (e) {
            $.ajax({
                url: "<?= BASE_URL('') ?>ajaxs/admin/removegdv.php",
                method: "POST",
                dataType: "JSON",
                data: {
                    id: id,
                    token: $("#token").val()
                },
                success: function(response) {
                    if (response.status === 'success') {
                        showMessage(response.msg, "success");
                        setTimeout(function() {
                            location.reload();
                        }, 1500);
                    } else {
                        showMessage(response.msg, response.status);
                    }
                },
                error: function() {
                    showMessage('Có lỗi xảy ra khi xóa dữ liệu', 'error');
                }
            });
        }
    });
}

function postRemoveAccount(id) {
    $.ajax({
        url: "<?= BASE_URL('') ?>ajaxs/admin/removegdv.php",
        type: 'POST',
        dataType: "JSON",
        data: {
            action: 'removeUser',
            id: id,
            token: $("#token").val()
        },
        success: function(result) {
            if (result.status === 'success') {
                showMessage(result.msg, result.status);
            } else {
                showMessage(result.msg, result.status);
            }
        },
        error: function() {
            showMessage('Có lỗi xảy ra khi xóa dữ liệu', 'error');
        }
    });
}

function confirmDeleteAccount() {
    var checkbox = document.getElementsByName('checkbox_users');
    var isAnyCheckboxChecked = false;

    for (var i = 0; i < checkbox.length; i++) {
        if (checkbox[i].checked === true) {
            isAnyCheckboxChecked = true;
            break;
        }
    }

    if (!isAnyCheckboxChecked) {
        showMessage('Vui lòng chọn ít nhất một GDV', 'error');
        return;
    }

    var result = confirm('Bạn có đồng ý xóa các GDV đã chọn không?');
    if (result) {
        function postUpdatesSequentially(index) {
            if (index < checkbox.length) {
                if (checkbox[index].checked === true) {
                    postRemoveAccount(checkbox[index].value);
                }
                setTimeout(function() {
                    postUpdatesSequentially(index + 1);
                }, 120);
            } else {
                setTimeout(function() {
                    location.reload();
                }, 1200);
            }
        }
        postUpdatesSequentially(0);
    }
}

$(function() {
    $('#check_all_checkbox_users').on('click', function() {
        $('.checkbox_users').prop('checked', this.checked);
    });

    $('.checkbox_users').on('click', function() {
        $('#check_all_checkbox_users').prop(
            'checked',
            $('.checkbox_users:checked').length === $('.checkbox_users').length
        );
    });
});
</script>

<?php
require_once(__DIR__ . '/Footer.php');
?>