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

// 處理建立新行程
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'];
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];
    $description = $_POST['description'];

    if (!empty($title)) {
        $stmt = $pdo->prepare("INSERT INTO trips (user_id, title, start_date, end_date, description) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$user_id, $title, $start_date, $end_date, $description]);
        
        $trip_id = $pdo->lastInsertId();
        header("Location: trip_view.php?id=" . $trip_id);
        exit;
    }
}

// 🔍 升級 A：撈取「我自己建立的行程」
$my_stmt = $pdo->prepare("SELECT * FROM trips WHERE user_id = ? ORDER BY created_at DESC");
$my_stmt->execute([$user_id]);
$my_trips = $my_stmt->fetchAll(PDO::FETCH_ASSOC);

// 🔍 升級 B：撈取「別人邀請我加入的行程」（透過 JOIN 查詢 trip_members）
$shared_stmt = $pdo->prepare("
    SELECT t.*, u.username as owner_name 
    FROM trips t
    JOIN trip_members tm ON t.id = tm.trip_id
    JOIN users u ON t.user_id = u.id
    WHERE tm.user_id = ? 
    ORDER BY t.created_at DESC
");
$shared_stmt->execute([$user_id]);
$shared_trips = $shared_stmt->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">
    <link rel="icon" type="image/png" href="assets/fav.png">
    <title>我的行程清單 - TravelPlanner</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</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>
                <span class="text-light me-3">你好，<strong><?php echo htmlspecialchars($_SESSION['username'], ENT_QUOTES, 'UTF-8'); ?></strong></span>
                <a href="logout.php" class="btn btn-outline-danger btn-sm">登出</a> </div>
        </div>
    </nav>

    <div class="container" style="max-width: 1000px;">
        <div class="row">
            <div class="col-md-4 mb-4">
                <div class="card shadow-sm border-0 p-4 sticky-top" style="top: 20px;">
                    <h3 class="fw-bold text-primary mb-3">開啟新旅程</h3>
                    <form method="POST">
                        <div class="mb-3"><label class="form-label fw-bold">行程名稱</label><input type="text" class="form-control" name="title" required placeholder="例如：東京五天四夜奢華遊"></div>
                        <div class="mb-3"><label class="form-label fw-bold">出發日期</label><input type="date" class="form-control" name="start_date"></div>
                        <div class="mb-3"><label class="form-label fw-bold">結束日期</label><input type="date" class="form-control" name="end_date"></div>
                        <div class="mb-3"><label class="form-label fw-bold">行程簡介</label><textarea class="form-control" name="description" rows="3" placeholder="簡述這次的旅程目的..."></textarea></div>
                        <button type="submit" class="btn btn-primary w-100 fw-bold py-2">建立行程</button>
                    </form>
                </div>
            </div>

            <div class="col-md-8 mb-4">
                <div class="card shadow-sm border-0 p-4 mb-4">
                    <h3 class="fw-bold mb-3 text-dark">👑 我建立的行程</h3>
                    <?php if(empty($my_trips)): ?>
                        <div class="text-muted py-3">目前還沒有建立任何行程。</div>
                    <?php else: ?>
                        <div class="list-group">
                            <?php foreach($my_trips as $t): ?>
                                <a href="trip_view.php?id=<?php echo $t['id']; ?>" class="list-group-item list-group-item-action p-3 mb-2 shadow-sm rounded border-start border-primary border-4">
                                    <div class="d-flex w-100 justify-content-between">
                                        <h5 class="mb-1 fw-bold text-dark"><?php echo htmlspecialchars($t['title'], ENT_QUOTES, 'UTF-8'); ?></h5>
                                        <small class="text-muted">📅 <?php echo $t['start_date'] ?: '未定'; ?></small>
                                    </div>
                                    <p class="mb-1 text-secondary small"><?php echo htmlspecialchars($t['description'], ENT_QUOTES, 'UTF-8'); ?></p>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>

                <div class="card shadow-sm border-0 p-4">
                    <h3 class="fw-bold mb-3 text-secondary">👥 旅伴共享的行程</h3>
                    <?php if(empty($shared_trips)): ?>
                        <div class="text-muted py-3">目前沒有收到任何旅伴的共同編輯邀請。</div>
                    <?php else: ?>
                        <div class="list-group">
                            <?php foreach($shared_trips as $st): ?>
                                <a href="trip_view.php?id=<?php echo $st['id']; ?>" class="list-group-item list-group-item-action p-3 mb-2 shadow-sm rounded border-start border-success border-4">
                                    <div class="d-flex w-100 justify-content-between">
                                        <h5 class="mb-1 fw-bold text-dark"><?php echo htmlspecialchars($st['title'], ENT_QUOTES, 'UTF-8'); ?></h5>
                                        <small class="text-muted">📅 <?php echo $st['start_date'] ?: '未定'; ?></small>
                                    </div>
                                    <p class="mb-1 text-secondary small"><?php echo htmlspecialchars($st['description'], ENT_QUOTES, 'UTF-8'); ?></p>
                                    <div class="mt-2 text-end">
                                        <span class="badge bg-light text-success border border-success">發起人：<?php echo htmlspecialchars($st['owner_name']); ?></span>
                                    </div>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</body>
</html>