<?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 = '';

$form_action = 'add_task';
$form_id = '';
$form_task_name = '';
$form_estimated_time = '';
$form_weight = '1.0';
$form_description = '';
$form_title = '✨ 新增家庭公版任務';

// ==========================================
// 1. 處理 POST 請求 (新增、修改、刪除)
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    if ($action === 'delete_task' && !empty($_POST['task_id'])) {
        try {
            $stmt = $mysql_db->prepare("DELETE FROM tasks_template WHERE id = :id AND family_id = :family_id");
            $stmt->execute([':id' => $_POST['task_id'], ':family_id' => $family_id]);
            $success_msg = "任務已成功刪除！";
        } catch (PDOException $e) {
            $error_msg = "刪除失敗：" . $e->getMessage();
        }
    }
    elseif ($action === 'add_task' || $action === 'edit_task') {
        $task_name = trim($_POST['task_name']);
        $estimated_time = (int)$_POST['estimated_time'];
        $weight = (float)$_POST['weight'];
        $description = trim($_POST['description']);
        $task_id = $_POST['task_id'] ?? '';

        if (empty($task_name) || $estimated_time <= 0) {
            $error_msg = "操作失敗：「任務名稱」與「預計時間」為必填，且時間必須大於 0 分鐘。";
        } elseif ($weight < 0.1 || $weight > 1.2) {
            // ★ 核心防護：為維護全球經濟公平，後端最高限制調降為 1.2 倍
            $error_msg = "操作失敗：為維持全球排行榜的經濟公平性，任務權重最高不得超過 1.2 倍！";
        } else {
            try {
                if ($action === 'add_task') {
                    $sql = "INSERT INTO tasks_template (family_id, task_name, estimated_time, weight, description) 
                            VALUES (:family_id, :task_name, :estimated_time, :weight, :description)";
                    $stmt = $mysql_db->prepare($sql);
                    $stmt->execute([':family_id' => $family_id, ':task_name' => $task_name, ':estimated_time' => $estimated_time, ':weight' => $weight, ':description' => $description]);
                    $success_msg = "任務「{$task_name}」新增成功！";
                } elseif ($action === 'edit_task' && !empty($task_id)) {
                    $sql = "UPDATE tasks_template 
                            SET task_name = :task_name, estimated_time = :estimated_time, weight = :weight, description = :description 
                            WHERE id = :id AND family_id = :family_id";
                    $stmt = $mysql_db->prepare($sql);
                    $stmt->execute([':task_name' => $task_name, ':estimated_time' => $estimated_time, ':weight' => $weight, ':description' => $description, ':id' => $task_id, ':family_id' => $family_id]);
                    $success_msg = "任務「{$task_name}」修改成功！";
                }
            } catch (PDOException $e) {
                $error_msg = "資料庫錯誤：" . $e->getMessage();
            }
        }
    }
}

// ==========================================
// 2. 處理 GET 請求 (載入要修改的資料)
// ==========================================
if (isset($_GET['edit_id'])) {
    try {
        $stmt = $mysql_db->prepare("SELECT * FROM tasks_template WHERE id = :id AND family_id = :family_id");
        $stmt->execute([':id' => $_GET['edit_id'], ':family_id' => $family_id]);
        $edit_data = $stmt->fetch();

        if ($edit_data) {
            $form_action = 'edit_task';
            $form_id = $edit_data['id'];
            $form_task_name = $edit_data['task_name'];
            $form_estimated_time = $edit_data['estimated_time'];
            $form_weight = $edit_data['weight'];
            $form_description = $edit_data['description'];
            $form_title = '✏️ 修改家庭公版任務';
        } else {
            $error_msg = "找不到指定的任務資料，或您無權限修改。";
        }
    } catch (PDOException $e) {
        $error_msg = "讀取資料失敗：" . $e->getMessage();
    }
}

// ==========================================
// 3. 讀取任務列表
// ==========================================
try {
    $stmt = $mysql_db->prepare("SELECT * FROM tasks_template WHERE family_id = :family_id ORDER BY created_at DESC");
    $stmt->execute([':family_id' => $family_id]);
    $tasks = $stmt->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', Tahoma, Geneva, Verdana, sans-serif; background-color: #f4f7f6; color: #333; margin: 0; padding: 0; }
        .container { max-width: 1000px; 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; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; color: #34495e; }
        input[type="text"], input[type="number"], textarea { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; }
        button { background-color: #3498db; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; font-size: 16px; }
        button:hover { background-color: #2980b9; }
        .btn-edit { background-color: #f39c12; color: white; padding: 6px 12px; text-decoration: none; border-radius: 4px; font-size: 14px; margin-right: 5px;}
        .btn-edit:hover { background-color: #e67e22; }
        .btn-delete { background-color: #e74c3c; color: white; padding: 6px 12px; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; }
        .btn-delete:hover { background-color: #c0392b; }
        .btn-cancel { background-color: #95a5a6; color: white; text-decoration: none; padding: 10px 20px; border-radius: 4px; display: inline-block; margin-left: 10px;}
        .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; margin-top: 10px; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }
        th { background-color: #f8f9fa; color: #2c3e50; }
        tr:hover { background-color: #f1f1f1; }
        .weight-badge { background-color: #27ae60; color: white; padding: 3px 8px; border-radius: 12px; font-size: 0.85em; }
    </style>
</head>
<body>

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

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

    <div class="card" id="task-form">
        <h2><?php echo $form_title; ?></h2>
        <form method="POST" action="tasks.php">
            <input type="hidden" name="action" value="<?php echo $form_action; ?>">
            <input type="hidden" name="task_id" value="<?php echo $form_id; ?>">
            
            <div class="form-group">
                <label for="task_name">任務名稱</label>
                <input type="text" id="task_name" name="task_name" required placeholder="請輸入任務名稱" value="<?php echo htmlspecialchars($form_task_name); ?>">
            </div>

            <div class="form-group" style="display: flex; gap: 15px;">
                <div style="flex: 1;">
                    <label for="estimated_time">預計時間 (分鐘)</label>
                    <input type="number" id="estimated_time" name="estimated_time" min="1" required value="<?php echo htmlspecialchars($form_estimated_time); ?>">
                </div>
                <div style="flex: 1;">
                    <label for="weight">時間權重 (倍率)</label>
                    <input type="number" id="weight" name="weight" step="0.1" min="0.1" max="1.2" required value="<?php echo htmlspecialchars($form_weight); ?>">
                    <small style="color:#7f8c8d; display:block; margin-top:4px;">※ 為維持全球經濟公平，最高上限改為 1.2 倍</small>
                </div>
            </div>

            <div class="form-group">
                <label for="description">任務說明與驗收標準 (選填)</label>
                <textarea id="description" name="description" rows="3"><?php echo htmlspecialchars($form_description); ?></textarea>
            </div>

            <button type="submit"><?php echo ($form_action === 'edit_task') ? '儲存修改' : '新增至家庭任務庫'; ?></button>
            
            <?php if ($form_action === 'edit_task'): ?>
                <a href="tasks.php" class="btn-cancel">取消修改</a>
            <?php endif; ?>
        </form>
    </div>

    <div class="card">
        <h2>📋 家庭任務庫清單</h2>
        <?php if (count($tasks) > 0): ?>
            <table>
                <thead>
                    <tr>
                        <th>任務名稱</th>
                        <th>預計時間</th>
                        <th>權重</th>
                        <th>說明</th>
                        <th width="150">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($tasks as $task): ?>
                        <tr>
                            <td><strong><?php echo htmlspecialchars($task['task_name']); ?></strong></td>
                            <td><?php echo htmlspecialchars($task['estimated_time']); ?> 分鐘</td>
                            <td><span class="weight-badge">x <?php echo htmlspecialchars($task['weight']); ?></span></td>
                            <td style="color: #666; font-size: 0.9em;"><?php echo nl2br(htmlspecialchars($task['description'] ?? '無')); ?></td>
                            <td>
                                <a href="tasks.php?edit_id=<?php echo $task['id']; ?>#task-form" class="btn-edit">修改</a>
                                <form method="POST" style="display:inline;" onsubmit="return confirm('確定要刪除「<?php echo htmlspecialchars($task['task_name']); ?>」嗎？這將無法復原喔！');">
                                    <input type="hidden" name="action" value="delete_task">
                                    <input type="hidden" name="task_id" value="<?php echo $task['id']; ?>">
                                    <button type="submit" class="btn-delete">刪除</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <p style="text-align: center; color: #7f8c8d; padding: 20px;">您的家庭還沒有設定任務，趕快在上方新增吧！</p>
        <?php endif; ?>
    </div>
</div>

</body>
</html>