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

// 获取客户ID
$customerId = isset($_GET['customer_id']) ? intval($_GET['customer_id']) : 0;
if ($customerId <= 0) {
    echo "<script>alert('请选择一个有效的客户'); window.location.href='rebate_summary.php';</script>";
    exit;
}

// 获取客户信息
$customerQuery = $conn->query("SELECT c.id, c.cs_code, c.cs_company 
                              FROM customer c 
                              WHERE c.id = " . $customerId);
if (!$customerQuery || $customerQuery->num_rows == 0) {
    echo "<script>alert('找不到指定的客户'); window.location.href='rebate_summary.php';</script>";
    exit;
}
$customerInfo = $customerQuery->fetch_assoc();

// 获取可兑换的返点信息 - 从订单项目中获取
$rebateQuery = "
SELECT 
    o.id AS order_id,
    o.order_code,
    o.order_date,
    oi.id AS order_item_id,
    oi.product_id,
    p.ProductName,
    oi.quantity,
    oi.unit,
    (
        SELECT rr.id
        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 o2.is_deleted = 0
            AND oi2.is_deleted = 0
            AND o2.order_type = 1
            AND oi2.product_id = oi.product_id
            AND o2.order_date >= DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
            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 rebate_rule_id,
    (
        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 o2.is_deleted = 0
            AND oi2.is_deleted = 0
            AND o2.order_type = 1
            AND oi2.product_id = oi.product_id
            AND o2.order_date >= DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
            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 rebate_amount,
    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 o2.is_deleted = 0
            AND oi2.is_deleted = 0
            AND o2.order_type = 1
            AND oi2.product_id = oi.product_id
            AND o2.order_date >= DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
            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 item_rebate_total
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 = $customerId
    AND o.is_deleted = 0
    AND oi.is_deleted = 0
    AND o.order_type = 1
    AND o.order_date >= DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
    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 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 o2.is_deleted = 0
            AND oi2.is_deleted = 0
            AND o2.order_type = 1
            AND oi2.product_id = oi.product_id
            AND o2.order_date >= DATE_FORMAT(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH), '%Y-%m-01')
            AND NOT EXISTS (
                SELECT 1
                FROM rebate_redemption_items rri
                WHERE rri.order_item_id = oi2.id
            )
        )
    )
ORDER BY 
    o.order_date DESC, p.ProductName ASC";

$rebateResult = $conn->query($rebateQuery);
if (!$rebateResult) {
    echo "<script>alert('获取返点信息失败: " . $conn->error . "'); window.location.href='rebate_summary.php';</script>";
    exit;
}

// 计算总返点金额
$totalRebateAmount = 0;
$rebateItems = [];
while ($row = $rebateResult->fetch_assoc()) {
    $rebateItems[] = $row;
    $totalRebateAmount += floatval($row['item_rebate_total']);
}

// 如果没有可兑换的返点,返回列表页
if (count($rebateItems) == 0) {
    echo "<script>alert('该客户当前没有可兑换的返点'); window.location.href='rebate_summary.php';</script>";
    exit;
}
?>
<!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;
        }
        .rebate-item-row {
            position: relative;
            padding: 12px 15px;
            margin-bottom: 8px;
            border-radius: 4px;
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
            background-color: #f9f9f9;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .rebate-item-row:hover {
            background-color: #f0f0f0;
        }
        .order-code {
            flex: 1;
            min-width: 100px;
        }
        .order-date {
            flex: 1;
            min-width: 120px;
        }
        .product-name {
            flex: 2;
            min-width: 150px;
        }
        .item-quantity {
            flex: 0.8;
            min-width: 80px;
            text-align: center;
        }
        .rebate-rate {
            flex: 0.8;
            min-width: 100px;
            text-align: right;
        }
        .item-total {
            flex: 1;
            min-width: 100px;
            text-align: right;
            font-weight: bold;
            color: #e74c3c;
        }
        
        .customer-info {
            background-color: #f5f5f5;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            border: 1px solid #ddd;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .customer-info .customer-details {
            flex: 1;
        }
        .customer-info h2 {
            margin-top: 0;
            margin-bottom: 10px;
            font-size: 18px;
            color: #333;
        }
        .customer-info p {
            margin: 5px 0;
            color: #555;
        }
        
        .customer-info .actions {
            text-align: right;
        }
        
        .btn-history {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 8px 16px;
            font-size: 14px;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
        }
        .btn-history:hover {
            background-color: #2980b9;
        }
        
        .list-header {
            display: flex;
            background-color: #eee;
            padding: 10px 15px;
            margin-bottom: 10px;
            border-radius: 4px;
            font-weight: bold;
            color: #555;
            font-size: 13px;
            gap: 15px;
        }
        
        .total-section {
            margin-top: 20px;
            padding: 15px;
            background-color: #f5f5f5;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .btn-redeem {
            background-color: #e74c3c;
            color: white;
            border: none;
            padding: 10px 20px;
            font-size: 16px;
            border-radius: 4px;
            cursor: pointer;
            margin-top: 20px;
        }
        .btn-redeem:hover {
            background-color: #c0392b;
        }
        
        .btn-cancel {
            background-color: #7f8c8d;
            color: white;
            border: none;
            padding: 10px 20px;
            font-size: 16px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        .btn-cancel:hover {
            background-color: #6c7a7a;
        }
        
        .rebate-notes {
            margin-top: 15px;
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: vertical;
            min-height: 60px;
        }
        
        @media (max-width: 768px) {
            .rebate-item-row {
                flex-direction: column;
                align-items: flex-start;
            }
            .list-header {
                display: none;
            }
            .order-code, .order-date, .product-name, .item-quantity,
            .rebate-rate, .item-total {
                width: 100%;
                min-width: 100%;
                margin-bottom: 5px;
            }
        }
    </style>
</head>
<body>
<div id="man_zone">
    <div class="customer-info">
        <div class="customer-details">
            <h2>客户返点兑换</h2>
            <p><strong>客户编码:</strong> <?= htmlspecialcharsFix($customerInfo['cs_code']) ?></p>
            <p><strong>客户名称:</strong> <?= htmlspecialcharsFix($customerInfo['cs_company']) ?></p>
        </div>
        <div class="actions">
            <a href="rebate_history.php" class="btn-history">查看返点历史</a>
        </div>
    </div>
    
    <form name="redeemForm" id="redeemForm" method="post" action="rebate_redeem_save.php" onsubmit="return validateRedeemForm()">
        <input type="hidden" name="customer_id" value="<?= $customerId ?>">
        <input type="hidden" name="total_rebate_amount" id="total-rebate-amount" value="<?= $totalRebateAmount ?>">
        
        <div class="list-header">
            <div class="order-code">订单编号</div>
            <div class="order-date">订单日期</div>
            <div class="product-name">产品名称</div>
            <div class="item-quantity">数量</div>
            <div class="rebate-rate">返点单价</div>
            <div class="item-total">返点金额</div>
        </div>
        
        <div id="rebate-items-container">
            <?php foreach ($rebateItems as $index => $item): ?>
            <div class="rebate-item-row">
                <!-- 隐藏字段,所有项目都会被提交 -->
                <input type="hidden" name="items[<?= $index ?>][selected]" value="1">
                <input type="hidden" name="items[<?= $index ?>][order_id]" value="<?= $item['order_id'] ?>">
                <input type="hidden" name="items[<?= $index ?>][order_item_id]" value="<?= $item['order_item_id'] ?>">
                <input type="hidden" name="items[<?= $index ?>][product_id]" value="<?= $item['product_id'] ?>">
                <input type="hidden" name="items[<?= $index ?>][quantity]" value="<?= $item['quantity'] ?>">
                <input type="hidden" name="items[<?= $index ?>][rebate_amount]" value="<?= $item['rebate_amount'] ?>">
                <input type="hidden" name="items[<?= $index ?>][rebate_rule_id]" value="<?= $item['rebate_rule_id'] ?>">
                <input type="hidden" name="items[<?= $index ?>][item_rebate_total]" value="<?= $item['item_rebate_total'] ?>">
                
                <div class="order-code"><?= htmlspecialcharsFix($item['order_code']) ?></div>
                <div class="order-date"><?= date('Y-m-d', strtotime($item['order_date'])) ?></div>
                <div class="product-name"><?= htmlspecialcharsFix($item['ProductName']) ?></div>
                <div class="item-quantity"><?= $item['quantity'] ?> <?= $item['unit'] ?></div>
                <div class="rebate-rate"><?= number_format($item['rebate_amount'], 2) ?> 元/件</div>
                <div class="item-total"><?= number_format($item['item_rebate_total'], 2) ?> 元</div>
            </div>
            <?php endforeach; ?>
        </div>
        
        <div class="total-section">
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <div>
                    <label for="notes">兑换备注:</label>
                    <textarea name="notes" id="notes" class="rebate-notes" placeholder="可选备注内容..."></textarea>
                </div>
                <div style="display: flex; flex-direction: column; align-items: flex-end;">
                    <div style="font-size: 16px; margin-bottom: 10px;">
                        <label>总返点金额:</label>
                        <span id="total-rebate-display" style="font-size: 18px; font-weight: bold; color: #e74c3c;"><?= number_format($totalRebateAmount, 2) ?> 元</span>
                    </div>
                    <div>
                        <button type="button" class="btn-cancel" onclick="window.location.href='rebate_summary.php'">取消</button>
                        <button type="submit" class="btn-redeem">确认兑换</button>
                    </div>
                </div>
            </div>
        </div>
    </form>

    <script>
    // 验证表单
    function validateRedeemForm() {
        return confirm('确定要兑换所有返点项目吗?此操作不可逆!');
    }
    </script>
</div>
</body>
</html>