<?php
require_once 'conn.php';
checkLogin();

// 辅助函数
$urlStr = '';

// 处理筛选条件
$fliterFromDate = $_GET['fliterFromDate'] ?? '';
$fliterToDate = $_GET['fliterToDate'] ?? '';
$expiryDays = $_GET['expiryDays'] ?? 7; // 默认显示7天内过期的返点

$fliterStr = "";

if (!empty($fliterFromDate)) {
    $fliterStr .= " AND o.order_date >= '" . mysqli_real_escape_string($conn, $fliterFromDate) . "'";
    $urlStr .= "&fliterFromDate=" . urlencode($fliterFromDate);
}

if (!empty($fliterToDate)) {
    $fliterStr .= " AND o.order_date <= '" . mysqli_real_escape_string($conn, $fliterToDate) . " 23:59:59'";
    $urlStr .= "&fliterToDate=" . urlencode($fliterToDate);
}

// 搜索参数
$keys = $_GET['Keys'] ?? '';
$keyscode = mysqli_real_escape_string($conn, $keys);
$page = $_GET['Page'] ?? 1;

// 构建基本条件SQL
$employee_id = $_SESSION['employee_id'];
$isAdmin = checkIfAdmin();

// 查询即将过期的返点订单
// 这里我们获取那些在90天期限内,但是已经接近过期的订单(比如只剩7天有效期)
$cutoffDate = date('Y-m-d', strtotime("-" . (90 - $expiryDays) . " days"));
$expiryDate = date('Y-m-d', strtotime("-90 days"));

$customerListSql = "SELECT DISTINCT 
    o.customer_id,
    c.cs_company AS customer_name,
    c.cs_code,
    MIN(o.order_date) AS oldest_order_date,
    DATE_ADD(MIN(o.order_date), INTERVAL 90 DAY) AS expiry_date,
    DATEDIFF(DATE_ADD(MIN(o.order_date), INTERVAL 90 DAY), CURRENT_DATE()) AS days_left
FROM orders o
JOIN order_items oi ON o.id = oi.order_id
JOIN customer c ON o.customer_id = c.id
JOIN products p ON oi.product_id = p.id
WHERE 
    o.order_date BETWEEN '$expiryDate' AND '$cutoffDate'
    AND p.rebate = 1
    AND NOT EXISTS (
        SELECT 1
        FROM rebate_redemption_items rri
        WHERE rri.order_item_id = oi.id
    )
    AND EXISTS (
        SELECT 1
        FROM rebate_rules rr
        WHERE rr.product_id = oi.product_id
    )
    AND (
        SELECT SUM(oi2.quantity)
        FROM order_items oi2
        JOIN orders o2 ON oi2.order_id = o2.id
        WHERE o2.customer_id = o.customer_id
        AND oi2.product_id = oi.product_id
        AND o2.order_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 90 DAY)
        AND NOT EXISTS (
            SELECT 1
            FROM rebate_redemption_items rri
            WHERE rri.order_item_id = oi2.id
        )
    ) >= (
        SELECT MIN(rr.min_quantity)
        FROM rebate_rules rr
        WHERE rr.product_id = oi.product_id
    )";

// 非管理员只能查看自己的客户返点
if (!$isAdmin) {
    $customerListSql .= " AND c.cs_belong = $employee_id";
}

// 添加搜索条件
if (!empty($keyscode)) {
    $customerListSql .= " AND (c.cs_company LIKE '%$keyscode%' OR c.cs_code LIKE '%$keyscode%')";
}

// 添加日期筛选
$customerListSql .= $fliterStr;

// 分组并按剩余天数排序
$customerListSql .= " GROUP BY o.customer_id, c.cs_company, c.cs_code ORDER BY days_left ASC";

// 执行查询获取客户列表
$result = mysqli_query($conn, $customerListSql);
if (!$result) {
    die("查询即将过期返点错误: " . mysqli_error($conn));
}

// 获取客户列表
$customers = [];
while ($row = mysqli_fetch_assoc($result)) {
    $customers[] = $row;
}

// 设置每页显示记录数和分页
$pageSize = 20;
$totalRecords = count($customers);

// 计算总页数
$totalPages = ceil($totalRecords / $pageSize);
if ($totalPages < 1) $totalPages = 1;

// 验证当前页码
$page = (int)$page;
if ($page < 1) $page = 1;
if ($page > $totalPages) $page = $totalPages;

// 分页处理
$paginatedCustomers = array_slice($customers, ($page - 1) * $pageSize, $pageSize);

// 获取每个客户的返点金额
foreach ($paginatedCustomers as &$customer) {
    $customer_id = $customer['customer_id'];
    
    // 计算客户的总返点金额
    $rebateAmountSql = "
    SELECT 
        SUM(
            oi.quantity * (
                SELECT rr.rebate_amount
                FROM rebate_rules rr
                WHERE rr.product_id = oi.product_id
                AND rr.min_quantity <= (
                    SELECT SUM(oi2.quantity)
                    FROM order_items oi2
                    JOIN orders o2 ON oi2.order_id = o2.id
                    WHERE o2.customer_id = o.customer_id
                    AND oi2.product_id = oi.product_id
                    AND o2.order_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 90 DAY)
                    AND NOT EXISTS (
                        SELECT 1
                        FROM rebate_redemption_items rri
                        WHERE rri.order_item_id = oi2.id
                    )
                )
                ORDER BY rr.min_quantity DESC
                LIMIT 1
            )
        ) AS total_rebate_amount,
        COUNT(DISTINCT oi.product_id) AS qualifying_products
    FROM 
        orders o
    JOIN 
        order_items oi ON o.id = oi.order_id
    JOIN
        products p ON oi.product_id = p.id
    WHERE 
        o.customer_id = $customer_id
        AND o.order_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 90 DAY)
        AND p.rebate = 1
        AND NOT EXISTS (
            SELECT 1
            FROM rebate_redemption_items rri
            WHERE rri.order_item_id = oi.id
        )";
    
    $amountResult = mysqli_query($conn, $rebateAmountSql);
    if (!$amountResult) {
        die("计算返点金额错误: " . mysqli_error($conn));
    }
    
    $amountRow = mysqli_fetch_assoc($amountResult);
    $customer['total_rebate_amount'] = $amountRow['total_rebate_amount'] ?? 0;
    $customer['qualifying_products'] = $amountRow['qualifying_products'] ?? 0;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>即将过期返点提醒</title>
    <link rel="stylesheet" href="css/common.css" type="text/css" />
    <link rel="stylesheet" href="css/alert.css" type="text/css" />
    <script src="js/jquery-1.7.2.min.js"></script>
    <script src="js/js.js"></script>
    <style>
        body {
            margin: 0;
            padding: 20px;
            background: #fff;
        }
        #man_zone {
            margin-left: 0;
        }
        
        /* 表格布局 */
        .table2 {
            width: 100%;
        }
        
        .theader, .tline {
            display: flex;
            flex-direction: row;
            align-items: center;
            width: 100%;
            border-bottom: 1px solid #ddd;
        }
        
        .theader {
            background-color: #f2f2f2;
            font-weight: bold;
            height: 40px;
        }
        
        .tline {
            height: 45px;
        }
        
        .tline:hover {
            background-color: #f5f5f5;
        }
        
        .col2 { width: 5%; text-align: center; }
        .col3 { width: 15%; }
        .col4 { width: 20%; }
        .col5 { width: 12%; text-align: center; }
        .col6 { width: 12%; text-align: center; }
        .col7 { width: 8%; text-align: center; }
        .col8 { width: 12%; text-align: right; }
        .col9 { width: 16%; text-align: center; }

        /* 表格布局修复 */
        .table2 .col2 { width: 5%; text-align: center; }
        .table2 .col3 { width: 15%; }
        .table2 .col4 { width: 20%; }
        .table2 .col5 { width: 12%; text-align: center; }
        .table2 .col6 { width: 12%; text-align: center; }
        .table2 .col7 { width: 8%; text-align: center; }
        .table2 .col8 { width: 12%; text-align: right; }
        .table2 .col9 { width: 16%; text-align: center; }

        .theader > div, .tline > div {
            padding: 0 5px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .col3, .col4 {
            justify-content: flex-start !important;
        }
        
        .col8 {
            justify-content: flex-end !important;
        }
        
        /* 日期选择器样式 */
        .date-input {
            padding: 5px;
            border: 1px solid #ccc;
            border-radius: 3px;
        }
        
        /* 警告信息样式 */
        .expiry-warning {
            color: #ff0000;
            font-weight: bold;
        }
        
        .days-left-critical {
            background-color: #ffeeee;
        }
        
        .days-left-warning {
            background-color: #fff5e6;
        }
        
        /* 选择框样式 */
        .select-days {
            padding: 5px;
            border: 1px solid #ccc;
            border-radius: 3px;
            margin-left: 5px;
        }
        
        /* 顶部提示样式 */
        .alert-box {
            background-color: #f8d7da;
            color: #721c24;
            padding: 15px;
            margin-bottom: 20px;
            border: 1px solid #f5c6cb;
            border-radius: 4px;
        }

        .fastSelect .selectItem
        {
            width: 50%;
        }

        


        .inputSearch {
            display: flex;
            align-items: center;
        }
        
        .inputTxt {
            padding: 5px;
            border: 1px solid #ccc;
            border-radius: 3px;
            margin-right: 5px;
            width: 180px;
        }
        
        .searchgo {
            padding: 5px 15px;
            background: #3498db;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        
        .searchgo:hover {
            background: #2980b9;
        }
        
        .action-buttons {
            width: 100%;
            display: flex;
            justify-content: flex-end;
            margin-top: 10px;
        }
    </style>
</head>
<body>
<div id="man_zone">
    <div class="alert-box">
        <strong>注意!</strong> 此页面显示即将过期的返点信息。返点订单在创建后90天内有效,过期后将无法兑换。请尽快处理以下客户的返点兑换。
    </div>

    <div class="fastSelect clear">
        <H1>筛选条件</H1>
        <div class="selectItem">
            <label>订单日期</label>
            <input type="date" name="fliterFromDate" class="date-input filterSearch" value="<?= $fliterFromDate ?>">
            <label>到</label>
            <input type="date" name="fliterToDate" class="date-input filterSearch" value="<?= $fliterToDate ?>">
            <label>过期天数</label>
            <select name="expiryDays" class="select-days filterSearch">
                <option value="3" <?= $expiryDays == 3 ? 'selected' : '' ?>>3天内</option>
                <option value="7" <?= $expiryDays == 7 ? 'selected' : '' ?>>7天内</option>
                <option value="14" <?= $expiryDays == 14 ? 'selected' : '' ?>>14天内</option>
                <option value="30" <?= $expiryDays == 30 ? 'selected' : '' ?>>30天内</option>
            </select>
        </div>
        <div class="inputSearch">
            <input type="text" id="keys" class="inputTxt" placeholder="请输入客户名称或编码"
                value="<?= empty($keyscode) ? '' : $keyscode ?>" />
            <input type="button" id="searchgo" class="searchgo" value="搜索"
                onClick="location.href='?Keys='+encodeURIComponent(document.getElementById('keys').value)+'&expiryDays='+document.getElementsByName('expiryDays')[0].value" />
        </div>
    </div>
    <div align="right" style="margin-bottom: 10px;">


        <a href="rebate_history.php" class="btn1" style="display: inline-flex; align-items: center; justify-content: center; padding: 5px 15px; margin-top: 0; height: 22px; margin-right: 5px;">查看返点历史</a>
        <a href="rebate_summary.php" class="btn1" style="display: inline-flex; align-items: center; justify-content: center; padding: 5px 15px; margin-top: 0; height: 22px;">返回返点统计</a>
    </div>

    <div class="table2 em<?= $_SESSION['employee_id'] ?>">
        <div class="theader">
            <div class="col2">序号</div>
            <div class="col3">客户编码</div>
            <div class="col4">客户名称</div>
            <div class="col5">最早订单日期</div>
            <div class="col6">过期日期</div>
            <div class="col7">剩余天数</div>
            <div class="col8">返点金额</div>
            <div class="col9">操作</div>
        </div>

        <?php
        if (!empty($paginatedCustomers)) {
            $tempNum = ($page - 1) * $pageSize;
            foreach ($paginatedCustomers as $customer) {
                $tempNum++;
                $daysLeft = $customer['days_left'];
                $rowClass = '';
                
                // 根据剩余天数添加不同的警告样式
                if ($daysLeft <= 3) {
                    $rowClass = 'days-left-critical';
                } elseif ($daysLeft <= 7) {
                    $rowClass = 'days-left-warning';
                }
                ?>
                <div class="tline <?= $rowClass ?>">
                    <div class="col2"><?= $tempNum ?></div>
                    <div class="col3"><?= htmlspecialcharsFix($customer['cs_code']) ?></div>
                    <div class="col4"><?= htmlspecialcharsFix($customer['customer_name']) ?></div>
                    <div class="col5"><?= date('Y-m-d', strtotime($customer['oldest_order_date'])) ?></div>
                    <div class="col6"><?= date('Y-m-d', strtotime($customer['expiry_date'])) ?></div>
                    <div class="col7 <?= $daysLeft <= 3 ? 'expiry-warning' : '' ?>"><?= $daysLeft ?> 天</div>
                    <div class="col8"><?= number_format($customer['total_rebate_amount'], 2) ?> 元</div>
                    <div class="col9">
                        <a href="rebate_redeem.php?customer_id=<?= $customer['customer_id'] ?>" class="ico_edit ico">立即处理兑换</a>
                    </div>
                </div>
                <?php
            }
        } else {
            echo '<div class="tline"><div style="width: 100%; text-align: center;">目前没有即将过期的返点订单</div></div>';
        }
        ?>

        <div class="showpagebox">
            <?php
            if ($totalPages > 1) {
                $pageName = "?Keys=$keys$urlStr&expiryDays=$expiryDays&";
                $pageLen = 3;

                if ($page > 1) {
                    echo "<a href=\"{$pageName}Page=1\">首页</a>";
                    echo "<a href=\"{$pageName}Page=" . ($page - 1) . "\">上一页</a>";
                }

                if ($pageLen * 2 + 1 >= $totalPages) {
                    $startPage = 1;
                    $endPage = $totalPages;
                } else {
                    if ($page <= $pageLen + 1) {
                        $startPage = 1;
                        $endPage = $pageLen * 2 + 1;
                    } else {
                        $startPage = $page - $pageLen;
                        $endPage = $page + $pageLen;
                    }
                    if ($page + $pageLen > $totalPages) {
                        $startPage = $totalPages - $pageLen * 2;
                        $endPage = $totalPages;
                    }
                }

                for ($i = $startPage; $i <= $endPage; $i++) {
                    if ($i == $page) {
                        echo "<a class=\"current\">$i</a>";
                    } else {
                        echo "<a href=\"{$pageName}Page=$i\">$i</a>";
                    }
                }

                if ($page < $totalPages) {
                    if ($totalPages - $page > $pageLen) {
                        echo "<a href=\"{$pageName}Page=$totalPages\">...$totalPages</a>";
                    }
                    echo "<a href=\"{$pageName}Page=" . ($page + 1) . "\">下一页</a>";
                    echo "<a href=\"{$pageName}Page=$totalPages\">尾页</a>";
                }
            }
            ?>
        </div>
    </div>

    <script>
    $(document).ready(function() {
        // 添加日期验证逻辑
        $('input[name="fliterToDate"]').on('change', function() {
            var fromDate = $('input[name="fliterFromDate"]').val();
            var toDate = $(this).val();
            
            if (fromDate && toDate && new Date(toDate) < new Date(fromDate)) {
                alert('结束日期不能早于开始日期');
                $(this).val(''); // 清空结束日期
                return false;
            }
        });
        
        // 开始日期变更时也进行验证
        $('input[name="fliterFromDate"]').on('change', function() {
            var fromDate = $(this).val();
            var toDate = $('input[name="fliterToDate"]').val();
            
            if (fromDate && toDate && new Date(toDate) < new Date(fromDate)) {
                alert('开始日期不能晚于结束日期');
                $('input[name="fliterToDate"]').val(''); // 清空结束日期
                return false;
            }
        });

        // 处理筛选条件改变
        $('.filterSearch').change(function() {
            var url = '?';
            var keys = $('#keys').val();
            if (keys && keys != '请输入客户名称或编码') {
                url += 'Keys=' + encodeURIComponent(keys) + '&';
            }

            url += 'expiryDays=' + $('select[name="expiryDays"]').val() + '&';

            $('.date-input.filterSearch').each(function() {
                var name = $(this).attr('name');
                var value = $(this).val();
                if (value) {
                    url += name + '=' + encodeURIComponent(value) + '&';
                }
            });

            // 移除末尾的&
            if (url.endsWith('&')) {
                url = url.substring(0, url.length - 1);
            }

            location.href = url;
        });
    });
    </script>
</div>
</body>
</html>