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

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php");
    exit;
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $player_id = (int)$_POST['player_id'];
    $record_id = (int)$_POST['record_id'];
    $sqlite_path = $_POST['sqlite_path'];

    try {
        $player_db = getPlayerSQLiteConnection($sqlite_path);

        if ($_POST['action'] === 'reject') {
            $stmt_del = $player_db->prepare("DELETE FROM task_history WHERE id = :id");
            $stmt_del->execute([':id' => $record_id]);
            $success_msg = "🗑️ 已將該筆重複或無效的任務紀錄刪除！";
        } 
        elseif ($_POST['action'] === 'approve') {
            $stars = (int)$_POST['stars'];
            $task_template_id = (int)$_POST['task_template_id']; // ★ 抓取這個任務的模板 ID

            $stmt_limit = $mysql_db->query("SELECT daily_task_limit FROM global_settings WHERE id = 1");
            $global_limit = (int)$stmt_limit->fetch()['daily_task_limit'];

            $stmt_task = $mysql_db->prepare("SELECT weight FROM tasks_template WHERE id = :id AND family_id = :family_id");
            $stmt_task->execute([':id' => $task_template_id, ':family_id' => $family_id]);
            $task_info = $stmt_task->fetch();
            $weight = $task_info ? (float)$task_info['weight'] : 1.0;

            $player_db->exec("CREATE TABLE IF NOT EXISTS active_buffs (id INTEGER PRIMARY KEY AUTOINCREMENT, buff_type TEXT, active_count INTEGER DEFAULT 0, target_task_id INTEGER DEFAULT 0)");

            $stmt_record = $player_db->prepare("SELECT created_at, estimated_time FROM task_history WHERE id = :id");
            $stmt_record->execute([':id' => $record_id]);
            $task_record = $stmt_record->fetch();
            
            $task_date = substr($task_record['created_at'], 0, 10);
            $task_est = (int)$task_record['estimated_time'];

            $stmt_check = $player_db->prepare("SELECT SUM(estimated_time) as total_raw FROM task_history WHERE stars IS NOT NULL AND substr(created_at, 1, 10) = :task_date");
            $stmt_check->execute([':task_date' => $task_date]);
            $current_raw = (int)$stmt_check->fetch()['total_raw'];

            $remaining_limit = max(0, $global_limit - $current_raw);
            $effective_est = min($task_est, $remaining_limit);

            if ($task_est > 0) {
                $scale_ratio = $effective_est / $task_est;
            } else {
                $scale_ratio = 1;
            }

            $est = (int)$_POST['est']; 
            $act = (int)$_POST['act'];
            $diff = $est - $act;
            
            $original_earned = $diff * $weight;

            // ★ 核心修復：只抓取掛在這個任務上的魔法！
            $stmt_buffs_full = $player_db->prepare("SELECT * FROM active_buffs WHERE active_count > 0 AND target_task_id = :tid");
            $stmt_buffs_full->execute([':tid' => $task_template_id]);
            $active_buffs_full = $stmt_buffs_full->fetchAll();
            
            $engine_result = CardEngine::calculateTask($original_earned, $stars, $active_buffs_full);
            
            $final_base_earned = $engine_result['final_earned'];
            $buff_desc = $engine_result['buff_desc'];
            $used_buff_ids = $engine_result['used_buff_ids'];

            if ($final_base_earned < 0) {
                $earned = $final_base_earned;
            } else {
                $earned = round($final_base_earned * $scale_ratio);
            }

            $player_db->beginTransaction();

            $player_db->prepare("UPDATE task_history SET stars = :stars, earned_minutes = :earned WHERE id = :id")
                      ->execute([':stars' => $stars, ':earned' => $earned, ':id' => $record_id]);

            if ($earned !== 0) {
                $player_db->exec("UPDATE wallet SET balance_minutes = balance_minutes + $earned");
            }

            foreach ($used_buff_ids as $used_id) {
                $player_db->prepare("UPDATE active_buffs SET active_count = active_count - 1 WHERE id = :id")->execute([':id' => $used_id]);
            }

            if ($earned < 0) {
                $desc = "任務逾時懲罰：{$_POST['task_name']} ({$stars}星)" . $buff_desc;
                $success_msg = "驗收完畢！因嚴重超時，已強制倒扣 " . abs($earned) . " 分鐘。" . $buff_desc;
            } elseif ($scale_ratio < 1) {
                $ratio_percent = round($scale_ratio * 100);
                $desc = "任務驗收：{$_POST['task_name']} ({$stars}星) [按 {$ratio_percent}% 比例]" . $buff_desc;
                $success_msg = "驗收成功！因觸及上限按 {$ratio_percent}% 發放 {$earned} 分鐘。" . $buff_desc;
            } else {
                $desc = "任務驗收：{$_POST['task_name']} ({$stars}星)" . $buff_desc;
                $success_msg = "驗收成功！已發放 {$earned} 分鐘。" . $buff_desc;
            }

            $player_db->prepare("INSERT INTO transaction_logs (action_type, amount, description) VALUES ('task_reward', :earned, :desc)")
                      ->execute([':earned' => $earned, ':desc' => $desc]);

            $player_db->commit();
        }

    } catch (Exception $e) {
        if(isset($player_db) && $player_db->inTransaction()) $player_db->rollBack();
        $error_msg = "操作失敗：" . $e->getMessage();
    }
}

$pending_list = [];
try {
    $stmt_users = $mysql_db->prepare("SELECT id, display_name, sqlite_file FROM users WHERE role = 'player' AND family_id = :family_id");
    $stmt_users->execute([':family_id' => $family_id]);
    $players = $stmt_users->fetchAll();

    foreach ($players as $p) {
        if (!empty($p['sqlite_file']) && file_exists('../' . $p['sqlite_file'])) {
            $p_db = getPlayerSQLiteConnection($p['sqlite_file']);
            $stmt_p = $p_db->query("SELECT * FROM task_history WHERE stars IS NULL ORDER BY created_at ASC");
            foreach ($stmt_p->fetchAll() as $row) {
                $row['player_name'] = $p['display_name'];
                $row['player_id'] = $p['id'];
                $row['sqlite_path'] = $p['sqlite_file'];
                
                // ★ 在家長的驗收清單上，精準秀出小孩掛在這個任務上的卡牌
                $b_stmt = $p_db->prepare("SELECT * FROM active_buffs WHERE active_count > 0 AND target_task_id = :tid");
                $b_stmt->execute([':tid' => $row['task_id']]);
                $b_arr = [];
                foreach($b_stmt->fetchAll() as $b) {
                    if ($b['buff_type'] == 'shield') $b_arr[] = '🛡️';
                    if ($b['buff_type'] == 'multiplier') $b_arr[] = "🧪(x{$b['effect_value']})";
                    if ($b['buff_type'] == 'fixed_time') $b_arr[] = "⏳({$b['effect_value']})";
                }
                $row['active_buffs'] = implode(' ', $b_arr);
                
                $pending_list[] = $row;
            }
        }
    }
} catch (PDOException $e) {
    $error_msg = "讀取失敗：" . $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', sans-serif; background-color: #f4f7f6; margin: 0; padding: 0; }
        .container { max-width: 900px; margin: 20px auto; padding: 0 20px; }
        .card { background: white; border-radius: 8px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #eee; }
        th { background-color: #f8f9fa; }
        .player-tag { background: #34495e; color: white; padding: 3px 8px; border-radius: 4px; font-size: 0.85rem;}
        .diff-pos { color: #27ae60; font-weight: bold; }
        .diff-neg { color: #e74c3c; font-weight: bold; }
        .btn-approve { background: #27ae60; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-weight: bold;}
        .btn-reject { background: transparent; color: #e74c3c; border: 1px solid #e74c3c; padding: 5px 10px; border-radius: 4px; cursor: pointer; font-size: 0.85rem;}
        .btn-reject:hover { background: #fdf2e9; }
        .alert { padding: 10px; border-radius: 4px; margin-bottom: 15px; }
        .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb;}
        .alert-error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb;}
    </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">
        <h2>⏳ 待處理的任務 (共 <?php echo count($pending_list); ?> 項)</h2>
        <?php if (count($pending_list) > 0): ?>
            <table>
                <thead>
                    <tr>
                        <th>玩家</th>
                        <th>任務內容</th>
                        <th>時間統計</th>
                        <th width="220">評價並結算</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($pending_list as $item): 
                        $diff = $item['estimated_time'] - $item['actual_time'];
                        $diff_class = ($diff >= 0) ? 'diff-pos' : 'diff-neg';
                    ?>
                    <tr>
                        <td>
                            <span class="player-tag"><?php echo htmlspecialchars($item['player_name']); ?></span>
                            <?php if(!empty($item['active_buffs'])): ?>
                                <span style="font-size:0.8rem; margin-top:5px; display:block; color:#8e44ad; font-weight:bold;">掛有魔法: <?php echo $item['active_buffs']; ?></span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <strong><?php echo htmlspecialchars($item['task_name']); ?></strong><br>
                            <small style="color: #95a5a6;"><?php echo htmlspecialchars($item['created_at']); ?></small>
                        </td>
                        <td>
                            預計：<?php echo $item['estimated_time']; ?> 分<br>
                            實際：<?php echo $item['actual_time']; ?> 分<br>
                            差額：<span class="<?php echo $diff_class; ?>"><?php echo ($diff > 0 ? '+' : '') . $diff; ?> 分</span>
                        </td>
                        <td>
                            <form method="POST" style="display: flex; gap: 8px; align-items: center; margin:0;">
                                <input type="hidden" name="player_id" value="<?php echo $item['player_id']; ?>">
                                <input type="hidden" name="record_id" value="<?php echo $item['id']; ?>">
                                <input type="hidden" name="sqlite_path" value="<?php echo $item['sqlite_path']; ?>">
                                <input type="hidden" name="task_template_id" value="<?php echo $item['task_id']; ?>">
                                <input type="hidden" name="task_name" value="<?php echo $item['task_name']; ?>">
                                <input type="hidden" name="est" value="<?php echo $item['estimated_time']; ?>">
                                <input type="hidden" name="act" value="<?php echo $item['actual_time']; ?>">
                                
                                <select name="stars" style="padding:5px; flex:1;">
                                    <option value="3">★★★ (1.2x)</option>
                                    <option value="2" selected>★★ (1.0x)</option>
                                    <option value="1">★ (0.5x)</option>
                                </select>
                                <button type="submit" name="action" value="approve" class="btn-approve">結算</button>
                                
                                <button type="submit" name="action" value="reject" class="btn-reject" onclick="return confirm('確定要作廢並刪除這筆任務嗎？');" title="作廢刪除">🗑️</button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <p style="text-align: center; color: #95a5a6; padding: 20px;">目前沒有等待驗收的任務喔！</p>
        <?php endif; ?>
    </div>
</div>

</body>
</html>