<?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("未指定的行程"); }

// 驗證行程擁有權
$stmt = $pdo->prepare("SELECT * FROM trips WHERE id = ? AND user_id = ?");
$stmt->execute([$trip_id, $user_id]);
$trip = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$trip) { die("找不到該行程或權限不足"); }

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

// ==========================================
// 1. 處理圖片上傳與刪除
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // 【功能 A：上傳圖片】
    if (isset($_POST['action']) && $_POST['action'] === 'upload') {
        $title = trim($_POST['title']);
        $file = $_FILES['media_file'];

        if (!empty($title) && $file['error'] === 0) {
            $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            
            // 檢查檔案格式是否為圖片
            if (in_array($file['type'], $allowed_types)) {
                $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
                // 重新命名檔案，避免檔名重複或中文亂碼
                $new_filename = "trip_" . $trip_id . "_" . uniqid() . "." . $ext;
                $upload_path = 'uploads/' . $new_filename;

                // 將檔案從暫存區移動到 uploads 資料夾
                if (move_uploaded_file($file['tmp_name'], $upload_path)) {
                    $insertStmt = $pdo->prepare("INSERT INTO trip_media (trip_id, title, file_path) VALUES (?, ?, ?)");
                    $insertStmt->execute([$trip_id, $title, $upload_path]);
                    $success_msg = "🎉 圖片上傳成功！";
                } else {
                    $error_msg = "❌ 檔案儲存失敗，請檢查資料夾權限。";
                }
            } else {
                $error_msg = "❌ 只允許上傳 JPG, PNG, GIF 或 WEBP 格式的圖片！";
            }
        } else {
            $error_msg = "❌ 請填寫標題並選擇正確的檔案。";
        }
    }

    // 【功能 B：刪除圖片】
    if (isset($_POST['action']) && $_POST['action'] === 'delete') {
        $media_id = intval($_POST['media_id']);
        
        // 先找出檔案路徑以利從硬碟刪除
        $findStmt = $pdo->prepare("SELECT file_path FROM trip_media WHERE id = ? AND trip_id = ?");
        $findStmt->execute([$media_id, $trip_id]);
        $media = $findStmt->fetch(PDO::FETCH_ASSOC);

        if ($media) {
            // 刪除實體檔案
            if (file_exists($media['file_path'])) {
                unlink($media['file_path']);
            }
            // 刪除資料庫紀錄
            $deleteStmt = $pdo->prepare("DELETE FROM trip_media WHERE id = ?");
            $deleteStmt->execute([$media_id]);
            $success_msg = "🗑️ 圖片已順利刪除。";
        }
    }
}

// 2. 撈取該行程的所有實用圖片
$mediaStmt = $pdo->prepare("SELECT * FROM trip_media WHERE trip_id = ? ORDER BY created_at DESC");
$mediaStmt->execute([$trip_id]);
$media_list = $mediaStmt->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>
        .gallery-img {
            width: 100%;
            height: 220px;
            object-fit: contain; /* 確保 QR Code 不會變形 */
            background-color: #f8f9fa;
            border-bottom: 1px solid #eee;
        }
    </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_view.php?id=<?php echo $trip_id; ?>" class="btn btn-outline-info btn-sm me-2">📋 行程表</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;">
        
        <div class="card mb-4 shadow-sm border-0">
            <div class="card-body p-4 text-center">
                <span class="badge bg-success mb-2">📸 實用圖片與隨身證件庫</span>
                <h1 class="card-title h3 text-dark fw-bold"><?php echo htmlspecialchars($trip['title'], ENT_QUOTES, 'UTF-8'); ?></h1>
            </div>
        </div>

        <?php if(!empty($error_msg)): ?><div class="alert alert-danger text-center"><?php echo $error_msg; ?></div><?php endif; ?>
        <?php if(!empty($success_msg)): ?><div class="alert alert-success text-center"><?php echo $success_msg; ?></div><?php endif; ?>

        <div class="row">
            <div class="col-md-8 mb-4">
                <div class="card shadow-sm border-0 p-4">
                    <h4 class="fw-bold mb-4">🖼️ 隨身圖片收納牆</h4>
                    
                    <?php if(empty($media_list)): ?>
                        <div class="alert alert-secondary text-center py-5">目前還沒有上傳任何圖片。快在右側上傳機票 QR Code、酒店預訂確認單吧！</div>
                    <?php else: ?>
                        <div class="row row-cols-1 row-cols-sm-2 g-3">
                            <?php foreach($media_list as $media): ?>
                                <div class="col">
                                    <div class="card h-100 border-0 shadow-sm">
                                        <a href="<?php echo $media['file_path']; ?>" target="_blank">
                                            <img src="<?php echo $media['file_path']; ?>" class="card-img-top gallery-img" alt="media">
                                        </a>
                                        <div class="card-body d-flex justify-content-between align-items-center py-2 px-3">
                                            <span class="fw-bold text-truncate me-2 small" style="max-width: 150px;">
                                                <?php echo htmlspecialchars($media['title'], ENT_QUOTES, 'UTF-8'); ?>
                                            </span>
                                            
                                            <form method="POST" onsubmit="return confirm('確定要刪除這張圖片嗎？');">
                                                <input type="hidden" name="action" value="delete">
                                                <input type="hidden" name="media_id" value="<?php echo $media['id']; ?>">
                                                <button type="submit" class="btn btn-sm btn-link text-danger p-0 border-0">🗑️ 刪除</button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="col-md-4 mb-4">
                <div class="card shadow-sm border-0">
                    <div class="card-header bg-dark text-white fw-bold py-3">➕ 上傳新圖片</div>
                    <div class="card-body p-3">
                        <form method="POST" enctype="multipart/form-data">
                            <input type="hidden" name="action" value="upload">
                            
                            <div class="mb-3">
                                <label class="form-label fw-bold">圖片用途標題</label>
                                <input type="text" class="form-control" name="title" placeholder="例如：機票 QR Code、環球影城門票" required>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label fw-bold">選擇圖片</label>
                                <input type="file" class="form-control" name="media_file" accept="image/*" required>
                                <div class="form-text">支援 JPG, PNG, WEBP。建議先將確認信或 QR Code 截圖再上傳。</div>
                            </div>
                            
                            <button type="submit" class="btn btn-success w-100 fw-bold py-2">上傳至此行程</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>