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

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

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

// ==========================================
// 1. 處理新增/刪除指派 (POST)
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    
    if ($_POST['action'] === 'delete_assign' && !empty($_POST['assign_id'])) {
        try {
            $stmt = $mysql_db->prepare("DELETE FROM task_assignments WHERE id = :id AND family_id = :family_id");
            $stmt->execute([':id' => $_POST['assign_id'], ':family_id' => $family_id]);
            $success_msg = "已成功移除該項任務指派！";
        } catch (PDOException $e) {
            $error_msg = "刪除失敗：" . $e->getMessage();
        }
    }
    elseif ($_POST['action'] === 'add_assign') {
        $player_id = (int)$_POST['player_id'];
        $task_id = (int)$_POST['task_id'];
        $schedule_type = $_POST['schedule_type'];
        $schedule_value = '';

        if ($schedule_type === 'daily') {
            $schedule_value = 'all'; 
        } elseif ($schedule_type === 'weekly') {
            if (!empty($_POST['weekdays'])) {
                $schedule_value = implode(',', $_POST['weekdays']);
            } else {
                $error_msg = "請至少勾選一天！";
            }
        } elseif ($schedule_type === 'specific_date') {
            $schedule_value = trim($_POST['specific_date']);
            if (empty($schedule_value)) $error_msg = "請選擇特定日期！";
        } elseif ($schedule_type === 'daily_deadline') {
            // ★ 新增：打卡任務，儲存目標時間 (例如 21:00)
            $schedule_value = trim($_POST['deadline_time']);
            if (empty($schedule_value)) $error_msg = "請設定打卡目標時間！";
        }

        if (empty($error_msg) && $player_id > 0 && $task_id > 0) {
            try {
                $sql = "INSERT INTO task_assignments (family_id, task_id, player_id, schedule_type, schedule_value) 
                        VALUES (:family_id, :task_id, :player_id, :schedule_type, :schedule_value)";
                $stmt = $mysql_db->prepare($sql);
                $stmt->execute([
                    ':family_id' => $family_id,
                    ':task_id' => $task_id,
                    ':player_id' => $player_id,
                    ':schedule_type' => $schedule_type,
                    ':schedule_value' => $schedule_value
                ]);
                $success_msg = "任務指派成功！";
            } catch (PDOException $e) {
                $error_msg = "指派失敗：" . $e->getMessage();
            }
        } elseif (empty($error_msg)) {
            $error_msg = "請選擇玩家與任務！";
        }
    }
}

// ==========================================
// 2. 準備下拉選單所需的資料
// ==========================================
try {
    $stmt_players = $mysql_db->prepare("SELECT id, display_name FROM users WHERE family_id = :family_id AND role = 'player'");
    $stmt_players->execute([':family_id' => $family_id]);
    $players = $stmt_players->fetchAll();

    $stmt_tasks = $mysql_db->prepare("SELECT id, task_name FROM tasks_template WHERE family_id = :family_id");
    $stmt_tasks->execute([':family_id' => $family_id]);
    $tasks = $stmt_tasks->fetchAll();

    $sql_assign = "
        SELECT a.*, u.display_name AS player_name, t.task_name 
        FROM task_assignments a
        JOIN users u ON a.player_id = u.id
        JOIN tasks_template t ON a.task_id = t.id
        WHERE a.family_id = :family_id
        ORDER BY u.display_name ASC, a.created_at DESC
    ";
    $stmt_assign = $mysql_db->prepare($sql_assign);
    $stmt_assign->execute([':family_id' => $family_id]);
    $assignments = $stmt_assign->fetchAll();
} 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', 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); margin-bottom: 20px; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; color: #34495e; font-size: 0.95rem; }
        select, input[type="date"], input[type="time"] { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; font-size: 1rem; }
        .schedule-details { display: none; background: #f8f9fa; padding: 15px; border-radius: 6px; border: 1px dashed #ccc; margin-top: 10px; }
        .checkbox-group { display: flex; flex-wrap: wrap; gap: 15px; }
        .checkbox-group label { display: flex; align-items: center; font-weight: normal; cursor: pointer; }
        .checkbox-group input { margin-right: 5px; width: auto; }
        button { background-color: #3498db; color: white; border: none; padding: 12px 20px; border-radius: 4px; cursor: pointer; font-size: 1rem; font-weight: bold; width: 100%; }
        button:hover { background-color: #2980b9; }
        table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #eee; }
        th { background-color: #f8f9fa; }
        .badge { display: inline-block; padding: 3px 8px; border-radius: 12px; font-size: 0.8rem; font-weight: bold; }
        .badge-daily { background-color: #e8f8f5; color: #1abc9c; border: 1px solid #1abc9c; }
        .badge-weekly { background-color: #ebf5fb; color: #3498db; border: 1px solid #3498db; }
        .badge-date { background-color: #fef9e7; color: #f39c12; border: 1px solid #f39c12; }
        .badge-deadline { background-color: #fce4ec; color: #8e44ad; border: 1px solid #8e44ad; }
        .btn-delete { background-color: #e74c3c; color: white; border: none; padding: 5px 10px; border-radius: 4px; cursor: pointer; font-size: 0.85rem; }
        .alert { padding: 10px; border-radius: 4px; margin-bottom: 15px; text-align: center; }
        .alert-error { background: #f8d7da; color: #721c24; }
        .alert-success { background: #d4edda; color: #155724; }
    </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>➕ 新增任務指派</h2>
        <?php if (count($players) === 0 || count($tasks) === 0): ?>
            <p style="color: #e74c3c; font-weight: bold;">⚠️ 您需要先建立「至少一位玩家」與「至少一項任務」，才能進行指派喔！</p>
        <?php else: ?>
            <form method="POST" action="assignments.php">
                <input type="hidden" name="action" value="add_assign">
                
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                    <div class="form-group">
                        <label>👤 選擇玩家 (指派給誰)</label>
                        <select name="player_id" required>
                            <option value="">-- 請選擇 --</option>
                            <?php foreach ($players as $p): ?>
                                <option value="<?php echo $p['id']; ?>"><?php echo htmlspecialchars($p['display_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>🎯 選擇任務</label>
                        <select name="task_id" required>
                            <option value="">-- 請選擇 --</option>
                            <?php foreach ($tasks as $t): ?>
                                <option value="<?php echo $t['id']; ?>"><?php echo htmlspecialchars($t['task_name']); ?> (最高獎勵: <?php echo $t['estimated_time']; ?>分)</option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="form-group">
                    <label>⏰ 執行頻率 (排程)</label>
                    <select name="schedule_type" id="schedule_type" onchange="toggleScheduleOptions()" required>
                        <option value="daily">每天執行 (需倒數計時)</option>
                        <option value="weekly">每週指定星期 (需倒數計時)</option>
                        <option value="specific_date">特定日期 (需倒數計時)</option>
                        <option value="daily_deadline">🚨 每日打卡 (如：21:00 上床睡覺)</option>
                    </select>
                </div>

                <div id="div_weekly" class="schedule-details">
                    <label>請勾選星期幾要執行：</label>
                    <div class="checkbox-group">
                        <label><input type="checkbox" name="weekdays[]" value="1"> 星期一</label>
                        <label><input type="checkbox" name="weekdays[]" value="2"> 星期二</label>
                        <label><input type="checkbox" name="weekdays[]" value="3"> 星期三</label>
                        <label><input type="checkbox" name="weekdays[]" value="4"> 星期四</label>
                        <label><input type="checkbox" name="weekdays[]" value="5"> 星期五</label>
                        <label><input type="checkbox" name="weekdays[]" value="6"> 星期六</label>
                        <label><input type="checkbox" name="weekdays[]" value="0"> 星期日</label>
                    </div>
                </div>

                <div id="div_specific" class="schedule-details">
                    <label>請選擇特定日期：</label>
                    <input type="date" name="specific_date">
                </div>

                <div id="div_deadline" class="schedule-details">
                    <label style="color:#8e44ad;">請設定目標打卡時間 (早到給獎，遲到扣分)：</label>
                    <input type="time" name="deadline_time" value="21:00">
                    <p style="font-size: 0.8rem; color: #7f8c8d; margin-top: 5px;">
                        ※ 提示：這類任務的「預計時間」會變成「最多能賺取的分鐘數」。例如您設定任務預計時間為 10 分鐘，提早 30 分鐘打卡，最多依然只會給 10 分鐘。
                    </p>
                </div>

                <button type="submit" style="margin-top: 15px;">💾 儲存指派</button>
            </form>
        <?php endif; ?>
    </div>

    <div class="card">
        <h2>📋 現有排程清單</h2>
        <?php if (count($assignments) > 0): ?>
            <table>
                <thead>
                    <tr>
                        <th>玩家</th>
                        <th>任務名稱</th>
                        <th>排程規則</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($assignments as $a): ?>
                    <tr>
                        <td><strong><?php echo htmlspecialchars($a['player_name']); ?></strong></td>
                        <td><?php echo htmlspecialchars($a['task_name']); ?></td>
                        <td>
                            <?php 
                                if ($a['schedule_type'] === 'daily') {
                                    echo '<span class="badge badge-daily">每天</span>';
                                } elseif ($a['schedule_type'] === 'weekly') {
                                    $map = ['0'=>'日', '1'=>'一', '2'=>'二', '3'=>'三', '4'=>'四', '5'=>'五', '6'=>'六'];
                                    $days = explode(',', $a['schedule_value']);
                                    $day_strs = array_map(function($d) use ($map) { return $map[$d] ?? $d; }, $days);
                                    echo '<span class="badge badge-weekly">每週 ' . implode('、', $day_strs) . '</span>';
                                } elseif ($a['schedule_type'] === 'specific_date') {
                                    echo '<span class="badge badge-date">' . htmlspecialchars($a['schedule_value']) . '</span>';
                                } elseif ($a['schedule_type'] === 'daily_deadline') {
                                    // ★ 顯示打卡專屬標籤
                                    echo '<span class="badge badge-deadline">⏰ 每日 ' . htmlspecialchars($a['schedule_value']) . ' 前打卡</span>';
                                }
                            ?>
                        </td>
                        <td>
                            <form method="POST" style="display:inline;" onsubmit="return confirm('確定要取消這個指派嗎？');">
                                <input type="hidden" name="action" value="delete_assign">
                                <input type="hidden" name="assign_id" value="<?php echo $a['id']; ?>">
                                <button type="submit" class="btn-delete">移除</button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <p style="text-align: center; color: #95a5a6; padding: 20px;">目前沒有任何指派，趕快把任務分配給小孩吧！</p>
        <?php endif; ?>
    </div>
</div>

<script>
    function toggleScheduleOptions() {
        const type = document.getElementById('schedule_type').value;
        document.getElementById('div_weekly').style.display = (type === 'weekly') ? 'block' : 'none';
        document.getElementById('div_specific').style.display = (type === 'specific_date') ? 'block' : 'none';
        // ★ 控制打卡區塊顯示
        document.getElementById('div_deadline').style.display = (type === 'daily_deadline') ? 'block' : 'none';
    }
    window.onload = toggleScheduleOptions;
</script>

</body>
</html>