<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit;
}
require 'db.php';
$user_id = $_SESSION['user_id']; 

$trip_id = $_GET['id'] ?? null;
if (!$trip_id) { die("未指定的行程"); }

// ==========================================
// 1. 核心權限驗證：檢查是否為建立者或共同編輯者
// ==========================================
// 先查行程基本資料
$stmt = $pdo->prepare("SELECT * FROM trips WHERE id = ?");
$stmt->execute([$trip_id]);
$trip = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$trip) { die("找不到該行程"); }

// 檢查目前登入者是不是這張行程的主人
$is_owner = ($trip['user_id'] == $user_id);

// 如果不是主人，檢查是不是共同編輯者 (Member)
$is_member = false;
if (!$is_owner) {
    $memberCheck = $pdo->prepare("SELECT id FROM trip_members WHERE trip_id = ? AND user_id = ?");
    $memberCheck->execute([$trip_id, $user_id]);
    if ($memberCheck->fetch()) {
        $is_member = true;
    }
}

// 如果既不是主人也不是成員，直接踢走拒絕訪問
if (!$is_owner && !$is_member) {
    die("❌ 權限不足：您不是該行程的成員，無法觀看或編輯。");
}

$error_msg = "";
$success_msg = "";

// ==========================================
// 2. 動作處理 (Action Controller)
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // 【動作 A：新增活動】
    if (isset($_POST['action']) && $_POST['action'] === 'create') {
        $day_number = intval($_POST['day_number']);
        $start_time = $_POST['start_time'];
        $activity = $_POST['activity'];
        $notes = $_POST['notes'];
        $map_link = $_POST['map_link'];

        $insertStmt = $pdo->prepare("INSERT INTO trip_details (trip_id, day_number, start_time, activity, notes, map_link) VALUES (?, ?, ?, ?, ?, ?)");
        $insertStmt->execute([$trip_id, $day_number, $start_time, $activity, $notes, $map_link]);
        header("Location: trip_view.php?id=" . $trip_id);
        exit;
    }

    // 【動作 B：修改活動】
    if (isset($_POST['action']) && $_POST['action'] === 'update') {
        $detail_id = intval($_POST['detail_id']);
        $day_number = intval($_POST['day_number']);
        $start_time = $_POST['start_time'];
        $activity = $_POST['activity'];
        $notes = $_POST['notes'];
        $map_link = $_POST['map_link'];

        $updateStmt = $pdo->prepare("UPDATE trip_details SET day_number = ?, start_time = ?, activity = ?, notes = ?, map_link = ? WHERE id = ? AND trip_id = ?");
        $updateStmt->execute([$day_number, $start_time, $activity, $notes, $map_link, $detail_id, $trip_id]);
        header("Location: trip_view.php?id=" . $trip_id);
        exit;
    }

    // 【動作 C：刪除活動】
    if (isset($_POST['action']) && $_POST['action'] === 'delete') {
        $detail_id = intval($_POST['detail_id']);
        $deleteStmt = $pdo->prepare("DELETE FROM trip_details WHERE id = ? AND trip_id = ?");
        $deleteStmt->execute([$detail_id, $trip_id]);
        header("Location: trip_view.php?id=" . $trip_id);
        exit;
    }

    // 【動作 D：新增共同編輯隊友 (限行程主人操作)】
    if (isset($_POST['action']) && $_POST['action'] === 'add_member') {
        if (!$is_owner) {
            $error_msg = "只有行程建立者可以邀請隊友。";
        } else {
            $friend_email = trim($_POST['friend_email']);
            
            // 根據 Email 尋找使用者
            $userStmt = $pdo->prepare("SELECT id, username FROM users WHERE email = ?");
            $userStmt->execute([$friend_email]);
            $friend = $userStmt->fetch(PDO::FETCH_ASSOC);

            if (!$friend) {
                $error_msg = "❌ 找不到此 Email 的使用者，請確認對方是否已註冊。";
            } elseif ($friend['id'] == $user_id) {
                $error_msg = " 這是您自己的 Email 喔！";
            } else {
                try {
                    $addMemberStmt = $pdo->prepare("INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)");
                    $addMemberStmt->execute([$trip_id, $friend['id']]);
                    $success_msg = "🎉 成功將 " . htmlspecialchars($friend['username']) . " 加入行程隊友！";
                } catch (PDOException $e) {
                    $error_msg = " 他已經在這個行程的隊友名單中了。";
                }
            }
        }
    }
}

// ==========================================
// 3. 撈取並整理資料
// ==========================================
// 撈取景點細節
$detailStmt = $pdo->prepare("SELECT * FROM trip_details WHERE trip_id = ? ORDER BY day_number ASC, start_time ASC");
$detailStmt->execute([$trip_id]);
$activities = $detailStmt->fetchAll(PDO::FETCH_ASSOC);

$weekdays = ['日', '一', '二', '三', '四', '五', '六'];
$timeline = [];
foreach ($activities as $act) {
    if (!empty($trip['start_date'])) {
        $day_offset = $act['day_number'] - 1;
        $current_date_ts = strtotime($trip['start_date'] . " +$day_offset days");
        $day_display = date("m/d", $current_date_ts) . " (週" . $weekdays[date("w", $current_date_ts)] . ")"; 
    } else {
        $day_display = "Day " . $act['day_number'];
    }
    $timeline[$day_display][] = $act;
}
$days = array_keys($timeline);

// 撈取目前的共同編輯隊友名單（用 JOIN 把名字撈出來）
$memberStmt = $pdo->prepare("SELECT u.username, u.email FROM trip_members tm JOIN users u ON tm.user_id = u.id WHERE tm.trip_id = ?");
$memberStmt->execute([$trip_id]);
$current_members = $memberStmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($trip['title'], ENT_QUOTES, 'UTF-8'); ?> - 行程規劃</title>
    <link rel="icon" type="image/png" href="assets/fav.png">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .timeline-item { position: relative; padding-left: 25px; border-left: 2px solid #0d6efd; margin-bottom: 25px; }
        .timeline-item::before { content: ''; position: absolute; left: -7px; top: 5px; width: 12px; height: 12px; border-radius: 50%; background-color: #0d6efd; }
    </style>
</head>
<body class="bg-light">
    <nav class="navbar navbar-dark bg-dark mb-4 shadow-sm">
        <div class="container">
            <span class="navbar-brand mb-0 h1">🧳 TravelPlanner</span>
            <div>
                <a href="trip_media.php?id=<?php echo $trip_id; ?>" class="btn btn-info btn-sm me-2 fw-bold">📸 實用圖片庫</a>
                <a href="add_trip.php" class="btn btn-outline-light btn-sm">← 行程清單</a>
                <a href="logout.php" class="btn btn-outline-danger btn-sm">登出</a> </div>
            </div>
        </div>
    </nav>

    <div class="container" style="max-width: 1000px;">
        
        <?php if(!empty($error_msg)): ?><div class="alert alert-danger text-center shadow-sm"><?php echo $error_msg; ?></div><?php endif; ?>
        <?php if(!empty($success_msg)): ?><div class="alert alert-success text-center shadow-sm"><?php echo $success_msg; ?></div><?php endif; ?>

        <div class="card mb-4 shadow-sm border-0">
            <div class="card-body p-4">
                <h1 class="card-title h2 text-primary fw-bold"><?php echo htmlspecialchars($trip['title'], ENT_QUOTES, 'UTF-8'); ?></h1>
                <p class="text-muted mb-0">📅 <strong>日期：</strong><?php echo $trip['start_date'] ?: '未定'; ?> ~ <?php echo $trip['end_date'] ?: '未定'; ?></p>
                <span class="badge bg-secondary mt-2">身分：<?php echo $is_owner ? '👑 行程建立者' : '👥 共同編輯者'; ?></span>
            </div>
        </div>

        <div class="row">
            <div class="col-md-7 mb-4">
                <div class="card shadow-sm border-0 p-4">
                    <h3 class="mb-4 fw-bold">📅 行程時間軸</h3>

                    <?php if (empty($timeline)): ?>
                        <div class="alert alert-info text-center py-4">目前沒有行程，請在右側表單加入第一個景點！</div>
                    <?php else: ?>
                        <ul class="nav nav-pills mb-4" id="pills-tab" role="tablist">
                            <?php foreach ($days as $index => $day_label): ?>
                                <li class="nav-item">
                                    <button class="nav-link <?php echo $index === 0 ? 'active' : ''; ?> me-2 fw-bold" data-bs-toggle="pill" data-bs-target="#content-tab-<?php echo $index; ?>" type="button"><?php echo $day_label; ?></button>
                                </li>
                            <?php endforeach; ?>
                        </ul>

                        <div class="tab-content">
                            <?php $content_index = 0; ?>
                            <?php foreach ($timeline as $day_label => $acts): ?>
                                <div class="tab-pane fade <?php echo $content_index === 0 ? 'show active' : ''; ?>" id="content-tab-<?php echo $content_index; ?>">
                                    <div class="ps-2">
                                        <?php foreach ($acts as $act): ?>
                                            <div class="timeline-item">
                                                <div class="d-flex justify-content-between align-items-start">
                                                    <span class="badge bg-primary fs-6"><?php echo date("H:i", strtotime($act['start_time'])); ?></span>
                                                    <div>
                                                        <?php if(!empty($act['map_link'])): ?>
                                                            <a href="<?php echo htmlspecialchars($act['map_link'], ENT_QUOTES, 'UTF-8'); ?>" target="_blank" class="btn btn-sm btn-outline-success me-1">🗺️ 地圖</a>
                                                        <?php endif; ?>
                                                        <button type="button" class="btn btn-sm btn-outline-secondary me-1" onclick="editActivity(<?php echo htmlspecialchars(json_encode($act), ENT_QUOTES, 'UTF-8'); ?>)">✏️ 編輯</button>
                                                        <form method="POST" class="d-inline" onsubmit="return confirm('確定要刪除這個景點嗎？');">
                                                            <input type="hidden" name="action" value="delete"><input type="hidden" name="detail_id" value="<?php echo $act['id']; ?>">
                                                            <button type="submit" class="btn btn-sm btn-outline-danger">🗑️</button>
                                                        </form>
                                                    </div>
                                                </div>
                                                <h4 class="h5 mt-2 fw-bold text-dark"><?php echo htmlspecialchars($act['activity'], ENT_QUOTES, 'UTF-8'); ?></h4>
                                                <?php if(!empty($act['notes'])): ?><p class="text-secondary small mb-0 mt-1 bg-light p-2 rounded"><?php echo nl2br(htmlspecialchars($act['notes'], ENT_QUOTES, 'UTF-8')); ?></p><?php endif; ?>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <?php $content_index++; ?>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="col-md-5 mb-4">
                
                <div class="card shadow-sm border-0 mb-4">
                    <div id="form-header" class="card-header bg-dark text-white fw-bold py-3">➕ 新增景點/活動</div>
                    <div class="card-body p-3">
                        <form method="POST" id="mainForm">
                            <input type="hidden" name="action" id="form-action" value="create">
                            <input type="hidden" name="detail_id" id="form-detail-id" value="">
                            <div class="mb-3">
                                <label class="form-label fw-bold">第幾天 (請填數字)</label>
                                <input type="number" class="form-control" name="day_number" id="form-day" min="1" value="1" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label fw-bold">時間</label>
                                <input type="time" class="form-control" name="start_time" id="form-time" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label fw-bold">景點/活動名稱</label>
                                <input type="text" class="form-control" name="activity" id="form-activity" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label fw-bold">🗺️ 地圖連結</label>
                                <input type="url" class="form-control" name="map_link" id="form-map" placeholder="貼上 Google Maps 共享網址">
                            </div>
                            <div class="mb-3">
                                <label class="form-label fw-bold">備註/筆記</label>
                                <textarea class="form-control" name="notes" id="form-notes" rows="2"></textarea>
                            </div>
                            <div class="d-flex gap-2">
                                <button type="submit" id="submit-btn" class="btn btn-primary flex-grow-1 fw-bold">加入行程表</button>
                                <button type="button" id="cancel-btn" class="btn btn-secondary d-none" onclick="resetForm()">取消編輯</button>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="card shadow-sm border-0">
                    <div class="card-header bg-secondary text-white fw-bold py-3">👥 行程共同編輯隊友</div>
                    <div class="card-body p-3">
                        
                        <?php if ($is_owner): ?>
                            <form method="POST" class="mb-4 pb-3 border-bottom">
                                <input type="hidden" name="action" value="add_member">
                                <label class="form-label small fw-bold text-muted">利用 Email 邀請旅伴加入：</label>
                                <div class="input-group">
                                    <input type="email" class="form-control" name="friend_email" placeholder="旅伴的註冊 Email" required>
                                    <button class="btn btn-success fw-bold" type="submit">邀請</button>
                                </div>
                            </form>
                        <?php endif; ?>

                        <label class="form-label small fw-bold text-muted mb-2">目前成員名單：</label>
                        <ul class="list-group list-group-flush">
                            <li class="list-group-item px-0 d-flex justify-content-between align-items-center">
                                <span>👑 <strong><?php echo htmlspecialchars($trip['user_id'] == $user_id ? '我' : '（發起人）'); ?></strong></span>
                                <span class="badge bg-primary rounded-pill">主人</span>
                            </li>
                            <?php foreach ($current_members as $mem): ?>
                                <li class="list-group-item px-0 d-flex justify-content-between align-items-center">
                                    <div>
                                        <span class="fw-bold"><?php echo htmlspecialchars($mem['username']); ?></span>
                                        <div class="text-muted" style="font-size: 11px;"><?php echo htmlspecialchars($mem['email']); ?></div>
                                    </div>
                                    <span class="badge bg-light text-dark border">隊友</span>
                                </li>
                            <?php endforeach; ?>
                        </ul>

                    </div>
                </div>

            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function editActivity(data) {
            document.getElementById('form-header').innerText = "✏️ 編輯景點/活動";
            document.getElementById('form-header').className = "card-header bg-warning text-dark fw-bold py-3";
            document.getElementById('form-action').value = "update";
            document.getElementById('form-detail-id').value = data.id;
            document.getElementById('form-day').value = data.day_number;
            document.getElementById('form-time').value = data.start_time;
            document.getElementById('form-activity').value = data.activity;
            document.getElementById('form-map').value = data.map_link;
            document.getElementById('form-notes').value = data.notes;
            document.getElementById('submit-btn').innerText = "儲存修改";
            document.getElementById('submit-btn').className = "btn btn-warning flex-grow-1 fw-bold text-dark";
            document.getElementById('cancel-btn').classList.remove('d-none');
            document.getElementById('mainForm').scrollIntoView({ behavior: 'smooth' });
        }
        function resetForm() {
            document.getElementById('form-header').innerText = "➕ 新增景點/活動";
            document.getElementById('form-header').className = "card-header bg-dark text-white fw-bold py-3";
            document.getElementById('form-action').value = "create";
            document.getElementById('form-detail-id').value = "";
            document.getElementById('mainForm').reset();
            document.getElementById('submit-btn').innerText = "加入行程表";
            document.getElementById('submit-btn').className = "btn btn-primary flex-grow-1 fw-bold";
            document.getElementById('cancel-btn').classList.add('d-none');
        }
    </script>
</body>
</html>