<?php
require_once '../config.php';

// 權限檢查：必須登入且為 admin
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php");
    exit;
}

$family_id = $_SESSION['family_id'];
$success_msg = '';
$error_msg = '';

// ==========================================
// 1. 處理核銷動作 (POST)
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'fulfill') {
    $redemption_id = (int)$_POST['redemption_id'];

    try {
        // 更新訂單狀態為已履約，並壓上當前時間
        // (加入 family_id 條件作為安全防護，避免改到別家的訂單)
        $sql = "UPDATE reward_redemptions 
                SET status = 'fulfilled', fulfilled_at = CURRENT_TIMESTAMP 
                WHERE id = :id AND family_id = :fid AND status = 'pending'";
        $stmt = $mysql_db->prepare($sql);
        $stmt->execute([':id' => $redemption_id, ':fid' => $family_id]);

        if ($stmt->rowCount() > 0) {
            $success_msg = "✅ 核銷成功！已記錄履約時間。";
        } else {
            $error_msg = "核銷失敗，該筆訂單可能已經被處理過了。";
        }
    } catch (PDOException $e) {
        $error_msg = "系統錯誤：" . $e->getMessage();
    }
}

// ==========================================
// 2. 讀取兌換訂單 (關聯 users 表以取得小孩名稱)
// ==========================================
try {
    $sql_orders = "
        SELECT r.*, u.display_name AS player_name 
        FROM reward_redemptions r
        JOIN users u ON r.player_id = u.id
        WHERE r.family_id = :fid
        ORDER BY 
            CASE WHEN r.status = 'pending' THEN 1 ELSE 2 END ASC, 
            r.created_at DESC
    ";
    $stmt_orders = $mysql_db->prepare($sql_orders);
    $stmt_orders->execute([':fid' => $family_id]);
    $all_orders = $stmt_orders->fetchAll();

    // 將資料分為待處理與已履約
    $pending_orders = [];
    $fulfilled_orders = [];
    foreach ($all_orders as $order) {
        if ($order['status'] === 'pending') {
            $pending_orders[] = $order;
        } else {
            $fulfilled_orders[] = $order;
        }
    }
} catch (PDOException $e) {
    die("讀取資料失敗：" . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>兌換券核銷中心 | 時間大富翁</title>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f4f7f6; color: #333; margin: 0; padding: 0; }
        
        .container { max-width: 900px; margin: 20px auto; padding: 0 20px; }
        .card { background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); margin-bottom: 20px; }
        .card-header { border-bottom: 2px solid #3498db; padding-bottom: 10px; margin-bottom: 15px; color: #2c3e50; font-size: 1.2rem; font-weight: bold; }
        
        .alert { padding: 10px; border-radius: 4px; margin-bottom: 15px; }
        .alert-error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .alert-success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }
        th { background-color: #f8f9fa; color: #2c3e50; }
        
        .player-badge { background: #e8f8f5; color: #1abc9c; padding: 4px 10px; border-radius: 12px; font-weight: bold; font-size: 0.9rem; }
        .item-cost { color: #e67e22; font-weight: bold; }
        
        .btn-fulfill { background-color: #27ae60; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; font-size: 0.95rem; font-weight: bold; transition: 0.2s;}
        .btn-fulfill:hover { background-color: #219653; transform: scale(1.05);}
        
        .time-text { font-size: 0.85rem; color: #7f8c8d; }
    </style>
</head>
<body>

<?php include 'navbar.php'; ?>

<div class="container">
    <?php if ($error_msg): ?><div class="alert alert-error"><?php echo $error_msg; ?></div><?php endif; ?>
    <?php if ($success_msg): ?><div class="alert alert-success"><?php echo $success_msg; ?></div><?php endif; ?>

    <div class="card">
        <div class="card-header" style="border-color: #e67e22; color: #d35400;">⏳ 待履約的訂單 (共 <?php echo count($pending_orders); ?> 筆)</div>
        <?php if (count($pending_orders) > 0): ?>
            <table>
                <thead>
                    <tr>
                        <th>申請玩家</th>
                        <th>兌換獎勵</th>
                        <th>花費時間</th>
                        <th>申請時間</th>
                        <th width="100">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($pending_orders as $order): ?>
                        <tr>
                            <td><span class="player-badge"><?php echo htmlspecialchars($order['player_name']); ?></span></td>
                            <td><strong><?php echo htmlspecialchars($order['item_name']); ?></strong></td>
                            <td class="item-cost"><?php echo $order['cost_minutes']; ?> 分</td>
                            <td class="time-text"><?php echo date('Y/m/d H:i', strtotime($order['created_at'])); ?></td>
                            <td>
                                <form method="POST" onsubmit="return confirm('確定已經讓小孩兌換【<?php echo htmlspecialchars($order['item_name']); ?>】了嗎？');">
                                    <input type="hidden" name="action" value="fulfill">
                                    <input type="hidden" name="redemption_id" value="<?php echo $order['id']; ?>">
                                    <button type="submit" class="btn-fulfill">完成履約</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <p style="text-align: center; color: #7f8c8d; padding: 20px;">太棒了！目前沒有欠小孩任何獎勵喔！</p>
        <?php endif; ?>
    </div>

    <div class="card">
        <div class="card-header">📜 歷史履約紀錄</div>
        <?php if (count($fulfilled_orders) > 0): ?>
            <table>
                <thead>
                    <tr>
                        <th>玩家</th>
                        <th>兌換獎勵</th>
                        <th>花費</th>
                        <th>申請時間</th>
                        <th>完成時間</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($fulfilled_orders as $order): ?>
                        <tr style="opacity: 0.8; background-color: #fcfcfc;">
                            <td><span class="player-badge" style="background:#f0f3f4; color:#7f8c8d;"><?php echo htmlspecialchars($order['player_name']); ?></span></td>
                            <td><?php echo htmlspecialchars($order['item_name']); ?></td>
                            <td class="time-text"><?php echo $order['cost_minutes']; ?> 分</td>
                            <td class="time-text"><?php echo date('Y/m/d H:i', strtotime($order['created_at'])); ?></td>
                            <td class="time-text" style="color: #27ae60; font-weight: bold;">
                                <?php echo date('Y/m/d H:i', strtotime($order['fulfilled_at'])); ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <p style="text-align: center; color: #7f8c8d; padding: 20px;">目前尚無歷史紀錄。</p>
        <?php endif; ?>
    </div>
</div>

</body>
</html>