<?php
$pageTitle = 'Edit Package';
require_once 'includes/header.php';

$id = intval($_GET['id'] ?? 0);
$stmt = $db->prepare("SELECT * FROM packages WHERE id = ?");
$stmt->execute([$id]);
$package = $stmt->fetch();

if (!$package) {
    setFlash('danger', 'Package not found.');
    redirect(ADMIN_URL . 'packages-list.php');
}

$places = $db->query("SELECT * FROM places WHERE status = 'active' ORDER BY name")->fetchAll();
$images = getPackageImages($id);
$videos = getPackageVideos($id);
$itineraryItems = getPackageItinerary($id);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $placeId = intval($_POST['place_id']);
    $title = sanitize($_POST['title']);
    $description = sanitize($_POST['description']);
    $pricePerPerson = floatval($_POST['price_per_person']);
    $offerPrice = !empty($_POST['offer_price']) ? floatval($_POST['offer_price']) : null;
    $durationDays = intval($_POST['duration_days']);
    $durationNights = intval($_POST['duration_nights']);
    $minPeople = intval($_POST['min_people']);
    $maxPeople = intval($_POST['max_people']);
    $startDate = $_POST['start_date'] ?: null;
    $endDate = $_POST['end_date'] ?: null;
    $inclusions = sanitize($_POST['inclusions']);
    $exclusions = sanitize($_POST['exclusions']);
    $isFeatured = isset($_POST['is_featured']) ? 1 : 0;
    $status = sanitize($_POST['status']);
    $slug = createSlug($title);
    
    $stmt = $db->prepare("UPDATE packages SET place_id=?, title=?, slug=?, description=?, price_per_person=?, offer_price=?, duration_days=?, duration_nights=?, min_people=?, max_people=?, start_date=?, end_date=?, inclusions=?, exclusions=?, is_featured=?, status=? WHERE id=?");
    $stmt->execute([$placeId, $title, $slug, $description, $pricePerPerson, $offerPrice, $durationDays, $durationNights, $minPeople, $maxPeople, $startDate, $endDate, $inclusions, $exclusions, $isFeatured, $status, $id]);
    
    // Handle new images
    if (!empty($_FILES['images']['name'][0])) {
        foreach ($_FILES['images']['name'] as $key => $name) {
            if ($_FILES['images']['error'][$key] === UPLOAD_ERR_OK) {
                $file = [
                    'name' => $_FILES['images']['name'][$key],
                    'tmp_name' => $_FILES['images']['tmp_name'][$key],
                    'size' => $_FILES['images']['size'][$key],
                    'error' => $_FILES['images']['error'][$key],
                ];
                $upload = uploadFile($file, 'packages');
                if ($upload['success']) {
                    $stmt = $db->prepare("INSERT INTO package_images (package_id, image, is_primary, sort_order) VALUES (?, ?, 0, ?)");
                    $stmt->execute([$id, $upload['filename'], $key + count($images)]);
                }
            }
        }
    }
    
    // Handle new videos (upload)
    if (!empty($_FILES['video_file']['name'])) {
        $upload = uploadVideo($_FILES['video_file']);
        if ($upload['success']) {
            $stmt = $db->prepare("INSERT INTO package_videos (package_id, video_type, video_file, sort_order) VALUES (?, 'upload', ?, ?)");
            $stmt->execute([$id, $upload['filename'], count($videos)]);
        }
    }
    
    // Handle YouTube videos
    if (!empty($_POST['youtube_url'])) {
        $youtubeUrl = sanitize($_POST['youtube_url']);
        $youtubeId = getYouTubeId($youtubeUrl);
        if ($youtubeId) {
            $thumbnail = getYouTubeThumbnail($youtubeId);
            $stmt = $db->prepare("INSERT INTO package_videos (package_id, video_type, youtube_id, youtube_url, thumbnail, sort_order) VALUES (?, 'youtube', ?, ?, ?, ?)");
            $stmt->execute([$id, $youtubeId, $youtubeUrl, $thumbnail, count($videos) + 1]);
        }
    }
    
    // Update itinerary - delete old and insert new
    $db->prepare("DELETE FROM itinerary WHERE package_id = ?")->execute([$id]);
    if (!empty($_POST['itinerary_day'])) {
        foreach ($_POST['itinerary_day'] as $key => $dayNum) {
            if (!empty($_POST['itinerary_title'][$key])) {
                $stmt = $db->prepare("INSERT INTO itinerary (package_id, day_number, title, description, meals, accommodation) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->execute([$id, intval($dayNum), sanitize($_POST['itinerary_title'][$key]), sanitize($_POST['itinerary_description'][$key] ?? ''), sanitize($_POST['itinerary_meals'][$key] ?? ''), sanitize($_POST['itinerary_accommodation'][$key] ?? '')]);
            }
        }
    }
    
    logActivity($_SESSION['user_id'], 'package_updated', "Updated package: $title");
    setFlash('success', 'Package updated successfully!');
    redirect(ADMIN_URL . 'packages-list.php');
}

// Refresh data after any updates
$images = getPackageImages($id);
$videos = getPackageVideos($id);
?>

<div class="page-header">
    <h1><i class="fas fa-edit text-primary"></i> Edit Package</h1>
    <a href="<?= ADMIN_URL ?>packages-list.php" class="btn btn-outline"><i class="fas fa-arrow-left"></i> Back</a>
</div>

<form method="POST" enctype="multipart/form-data" class="admin-form">
    <div class="admin-card">
        <div class="card-header"><h3>Basic Information</h3></div>
        <div class="card-body">
            <div class="form-row">
                <div class="form-group">
                    <label>Place <span class="required">*</span></label>
                    <select name="place_id" class="form-control" required>
                        <?php foreach ($places as $place): ?>
                            <option value="<?= $place['id'] ?>" <?= $place['id'] == $package['place_id'] ? 'selected' : '' ?>><?= sanitize($place['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Status</label>
                    <select name="status" class="form-control">
                        <option value="active" <?= $package['status'] === 'active' ? 'selected' : '' ?>>Active</option>
                        <option value="inactive" <?= $package['status'] === 'inactive' ? 'selected' : '' ?>>Inactive</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label>Package Title <span class="required">*</span></label>
                <input type="text" name="title" class="form-control" value="<?= sanitize($package['title']) ?>" required>
            </div>
            <div class="form-group">
                <label>Description</label>
                <textarea name="description" class="form-control" rows="4"><?= sanitize($package['description']) ?></textarea>
            </div>
        </div>
    </div>
    
    <div class="admin-card">
        <div class="card-header"><h3>Pricing & Duration</h3></div>
        <div class="card-body">
            <div class="form-row three-col">
                <div class="form-group">
                    <label>Price Per Person (₹)</label>
                    <input type="number" name="price_per_person" class="form-control" step="0.01" value="<?= $package['price_per_person'] ?>" required>
                </div>
                <div class="form-group">
                    <label>Offer Price (₹)</label>
                    <input type="number" name="offer_price" class="form-control" step="0.01" value="<?= $package['offer_price'] ?>">
                </div>
                <div class="form-group">
                    <label>&nbsp;</label>
                    <div class="form-check" style="padding-top:10px;">
                        <input type="checkbox" name="is_featured" id="is_featured" value="1" <?= $package['is_featured'] ? 'checked' : '' ?>>
                        <label for="is_featured">Featured</label>
                    </div>
                </div>
            </div>
            <div class="form-row" style="grid-template-columns:repeat(4,1fr);">
                <div class="form-group">
                    <label>Days</label>
                    <input type="number" name="duration_days" class="form-control" value="<?= $package['duration_days'] ?>" required>
                </div>
                <div class="form-group">
                    <label>Nights</label>
                    <input type="number" name="duration_nights" class="form-control" value="<?= $package['duration_nights'] ?>">
                </div>
                <div class="form-group">
                    <label>Min People</label>
                    <input type="number" name="min_people" class="form-control" value="<?= $package['min_people'] ?>">
                </div>
                <div class="form-group">
                    <label>Max People</label>
                    <input type="number" name="max_people" class="form-control" value="<?= $package['max_people'] ?>">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Start Date</label>
                    <input type="date" name="start_date" class="form-control" value="<?= $package['start_date'] ?>">
                </div>
                <div class="form-group">
                    <label>End Date</label>
                    <input type="date" name="end_date" class="form-control" value="<?= $package['end_date'] ?>">
                </div>
            </div>
        </div>
    </div>
    
    <!-- Images Section -->
    <div class="admin-card">
        <div class="card-header">
            <h3><i class="fas fa-images"></i> Package Images</h3>
        </div>
        <div class="card-body">
            <div class="media-section">
                <label class="media-section-label">Current Images</label>
                <?php if (empty($images)): ?>
                    <p class="text-gray">No images uploaded yet.</p>
                <?php else: ?>
                    <div class="media-grid" id="images-grid">
                        <?php foreach ($images as $img): ?>
                            <div class="media-item" data-id="<?= $img['id'] ?>">
                                <img src="<?= getImageUrl($img['image'], 'packages') ?>" alt="Package Image">
                                <div class="media-item-actions">
                                    <?php if (!$img['is_primary']): ?>
                                        <button type="button" class="btn-action btn-primary" onclick="setPrimaryImage(<?= $img['id'] ?>)" title="Set as Primary">
                                            <i class="fas fa-star"></i>
                                        </button>
                                    <?php else: ?>
                                        <span class="badge badge-primary">Primary</span>
                                    <?php endif; ?>
                                    <button type="button" class="btn-action btn-danger" onclick="deleteImage(<?= $img['id'] ?>)" title="Delete">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                                <?php if ($img['is_primary']): ?>
                                    <div class="media-item-badge"><i class="fas fa-star"></i> Primary</div>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
            
            <div class="media-section" style="margin-top:25px;">
                <label class="media-section-label">Add New Images</label>
                <div class="upload-area" id="image-upload-area">
                    <input type="file" name="images[]" id="image-input" accept="image/jpeg,image/png,image/gif,image/webp" multiple hidden>
                    <div class="upload-area-content" onclick="document.getElementById('image-input').click()">
                        <i class="fas fa-cloud-upload-alt"></i>
                        <p>Click to upload images</p>
                        <span>JPG, PNG, GIF, WebP (Max 5MB each)</span>
                    </div>
                </div>
                <div class="preview-grid" id="image-preview-grid"></div>
            </div>
        </div>
    </div>
    
    <!-- Videos Section -->
    <div class="admin-card">
        <div class="card-header">
            <h3><i class="fas fa-video"></i> Package Videos</h3>
        </div>
        <div class="card-body">
            <!-- Current Videos -->
            <div class="media-section">
                <label class="media-section-label">Current Videos</label>
                <?php if (empty($videos)): ?>
                    <p class="text-gray">No videos added yet.</p>
                <?php else: ?>
                    <div class="media-grid" id="videos-grid">
                        <?php foreach ($videos as $video): ?>
                            <div class="media-item video-item" data-id="<?= $video['id'] ?>">
                                <?php if ($video['video_type'] === 'youtube'): ?>
                                    <img src="<?= $video['thumbnail'] ?: getYouTubeThumbnail($video['youtube_id']) ?>" alt="YouTube Video">
                                    <div class="video-play-icon"><i class="fas fa-play"></i></div>
                                <?php else: ?>
                                    <video src="<?= UPLOAD_URL ?>videos/<?= $video['video_file'] ?>"></video>
                                <?php endif; ?>
                                <div class="media-item-actions">
                                    <button type="button" class="btn-action btn-danger" onclick="deleteVideo(<?= $video['id'] ?>)" title="Delete">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                                <div class="media-item-badge">
                                    <?php if ($video['video_type'] === 'youtube'): ?>
                                        <i class="fab fa-youtube"></i> YouTube
                                    <?php else: ?>
                                        <i class="fas fa-video"></i> Upload
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
            
            <!-- Upload Video -->
            <div class="media-section" style="margin-top:25px;">
                <label class="media-section-label">Upload Video</label>
                <div class="upload-area" id="video-upload-area">
                    <input type="file" name="video_file" id="video-input" accept="video/mp4,video/mov,video/avi,video/webm,video/x-matroska" hidden>
                    <div class="upload-area-content" onclick="document.getElementById('video-input').click()">
                        <i class="fas fa-cloud-upload-alt"></i>
                        <p>Click to upload video</p>
                        <span>MP4, MOV, AVI, WebM (Max 50MB)</span>
                    </div>
                </div>
                <div class="video-preview" id="video-preview" style="display:none;">
                    <video id="video-preview-player" controls></video>
                    <button type="button" class="btn-action btn-danger" onclick="clearVideoPreview()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            
            <!-- YouTube URL -->
            <div class="media-section" style="margin-top:25px;">
                <label class="media-section-label">Or Add YouTube Video</label>
                <div class="youtube-input-group">
                    <input type="text" name="youtube_url" id="youtube-url" class="form-control" placeholder="Paste YouTube URL here (e.g., https://www.youtube.com/watch?v=...)">
                    <button type="button" class="btn btn-primary" onclick="previewYouTube()">
                        <i class="fas fa-plus"></i> Add
                    </button>
                </div>
                <div class="youtube-preview" id="youtube-preview" style="display:none;">
                    <img id="youtube-thumbnail" src="" alt="YouTube Preview">
                    <div class="youtube-preview-info">
                        <p>YouTube video will be added</p>
                    </div>
                    <button type="button" class="btn-action btn-danger" onclick="clearYouTubePreview()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <div class="admin-card">
        <div class="card-header"><h3>Inclusions & Exclusions</h3></div>
        <div class="card-body">
            <div class="form-row">
                <div class="form-group">
                    <label>Inclusions</label>
                    <textarea name="inclusions" class="form-control" rows="6"><?= sanitize($package['inclusions']) ?></textarea>
                </div>
                <div class="form-group">
                    <label>Exclusions</label>
                    <textarea name="exclusions" class="form-control" rows="6"><?= sanitize($package['exclusions']) ?></textarea>
                </div>
            </div>
        </div>
    </div>
    
    <div class="admin-card">
        <div class="card-header">
            <h3>Itinerary</h3>
            <button type="button" class="btn btn-sm btn-primary" onclick="addItineraryDay()"><i class="fas fa-plus"></i> Add Day</button>
        </div>
        <div class="card-body" id="itinerary-container">
            <?php foreach ($itineraryItems as $item): ?>
                <div class="itinerary-form-item" style="border:1px solid var(--gray-lighter);border-radius:8px;padding:20px;margin-bottom:15px;position:relative;">
                    <button type="button" onclick="this.parentElement.remove()" style="position:absolute;top:10px;right:10px;background:var(--danger);color:#fff;border:none;width:28px;height:28px;border-radius:50%;cursor:pointer;"><i class="fas fa-times"></i></button>
                    <div class="form-row" style="grid-template-columns:80px 1fr;">
                        <div class="form-group">
                            <label>Day</label>
                            <input type="number" name="itinerary_day[]" class="form-control" value="<?= $item['day_number'] ?>">
                        </div>
                        <div class="form-group">
                            <label>Title</label>
                            <input type="text" name="itinerary_title[]" class="form-control" value="<?= sanitize($item['title']) ?>">
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Description</label>
                        <textarea name="itinerary_description[]" class="form-control" rows="3"><?= sanitize($item['description']) ?></textarea>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>Meals</label>
                            <input type="text" name="itinerary_meals[]" class="form-control" value="<?= sanitize($item['meals']) ?>">
                        </div>
                        <div class="form-group">
                            <label>Accommodation</label>
                            <input type="text" name="itinerary_accommodation[]" class="form-control" value="<?= sanitize($item['accommodation']) ?>">
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    
    <div style="display:flex;gap:10px;">
        <button type="submit" class="btn btn-primary btn-lg"><i class="fas fa-save"></i> Update Package</button>
        <a href="<?= ADMIN_URL ?>packages-list.php" class="btn btn-outline btn-lg">Cancel</a>
    </div>
</form>

<style>
/* Media Management Styles */
.media-section {
    margin-bottom: 20px;
}
.media-section-label {
    display: block;
    font-weight: 600;
    margin-bottom: 12px;
    color: var(--dark);
}
.media-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 15px;
}
.media-item {
    position: relative;
    border-radius: 8px;
    overflow: hidden;
    background: var(--gray-lightest);
}
.media-item img,
.media-item video {
    width: 100%;
    height: 120px;
    object-fit: cover;
}
.media-item-actions {
    position: absolute;
    top: 8px;
    right: 8px;
    display: flex;
    gap: 5px;
    opacity: 0;
    transition: opacity 0.3s;
}
.media-item:hover .media-item-actions {
    opacity: 1;
}
.btn-action {
    width: 32px;
    height: 32px;
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.9rem;
}
.btn-action.btn-danger { background: var(--danger); color: white; }
.btn-action.btn-primary { background: var(--primary); color: white; }
.btn-action:hover { transform: scale(1.1); }
.media-item-badge {
    position: absolute;
    bottom: 8px;
    left: 8px;
    background: rgba(0,0,0,0.7);
    color: white;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 0.75rem;
}
.video-item .video-play-icon {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 40px;
    height: 40px;
    background: rgba(255,255,255,0.9);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--primary);
}
.upload-area {
    border: 2px dashed var(--gray-light);
    border-radius: 8px;
    padding: 30px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s;
}
.upload-area:hover {
    border-color: var(--primary);
    background: rgba(255,107,53,0.05);
}
.upload-area-content {
    pointer-events: none;
}
.upload-area-content i {
    font-size: 2.5rem;
    color: var(--gray-light);
    margin-bottom: 10px;
}
.upload-area-content p {
    font-weight: 500;
    margin-bottom: 5px;
}
.upload-area-content span {
    font-size: 0.85rem;
    color: var(--gray);
}
.preview-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 10px;
    margin-top: 15px;
}
.preview-item {
    position: relative;
    border-radius: 8px;
    overflow: hidden;
}
.preview-item img {
    width: 100%;
    height: 100px;
    object-fit: cover;
}
.preview-item .remove-preview {
    position: absolute;
    top: 5px;
    right: 5px;
    width: 24px;
    height: 24px;
    background: var(--danger);
    color: white;
    border: none;
    border-radius: 50%;
    cursor: pointer;
    font-size: 0.8rem;
}
.video-preview {
    position: relative;
    margin-top: 15px;
    max-width: 400px;
}
.video-preview video {
    width: 100%;
    border-radius: 8px;
}
.video-preview .btn-action {
    position: absolute;
    top: -10px;
    right: -10px;
}
.youtube-input-group {
    display: flex;
    gap: 10px;
}
.youtube-input-group input {
    flex: 1;
}
.youtube-preview {
    position: relative;
    margin-top: 15px;
    display: flex;
    align-items: center;
    gap: 15px;
    padding: 10px;
    background: var(--gray-lightest);
    border-radius: 8px;
    max-width: 400px;
}
.youtube-preview img {
    width: 120px;
    height: 68px;
    object-fit: cover;
    border-radius: 4px;
}
.youtube-preview-info {
    flex: 1;
}
.youtube-preview .btn-action {
    position: absolute;
    top: 5px;
    right: 5px;
}
.text-gray { color: var(--gray); }
.badge-primary {
    background: var(--primary);
    color: white;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 0.7rem;
}
</style>

<script>
// Image preview functionality
document.getElementById('image-input')?.addEventListener('change', function(e) {
    const files = e.target.files;
    const previewGrid = document.getElementById('image-preview-grid');
    previewGrid.innerHTML = '';
    
    Array.from(files).forEach(file => {
        if (file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = function(e) {
                const div = document.createElement('div');
                div.className = 'preview-item';
                div.innerHTML = `<img src="${e.target.result}" alt="Preview">`;
                previewGrid.appendChild(div);
            };
            reader.readAsDataURL(file);
        }
    });
});

// Video preview functionality
document.getElementById('video-input')?.addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        const video = document.getElementById('video-preview-player');
        const preview = document.getElementById('video-preview');
        video.src = URL.createObjectURL(file);
        preview.style.display = 'block';
    }
});

function clearVideoPreview() {
    const video = document.getElementById('video-preview-player');
    const preview = document.getElementById('video-preview');
    const input = document.getElementById('video-input');
    video.src = '';
    preview.style.display = 'none';
    input.value = '';
}

// YouTube preview functionality
function previewYouTube() {
    const url = document.getElementById('youtube-url').value;
    const preview = document.getElementById('youtube-preview');
    const thumbnail = document.getElementById('youtube-thumbnail');
    
    if (url) {
        // Extract video ID
        const videoId = extractYouTubeId(url);
        if (videoId) {
            thumbnail.src = `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`;
            preview.style.display = 'flex';
        } else {
            alert('Please enter a valid YouTube URL');
        }
    }
}

function extractYouTubeId(url) {
    const regExp = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/]{11})/;
    const match = url.match(regExp);
    return match ? match[1] : null;
}

function clearYouTubePreview() {
    document.getElementById('youtube-url').value = '';
    document.getElementById('youtube-preview').style.display = 'none';
}

// AJAX functions for media management
function deleteImage(id) {
    if (!confirm('Are you sure you want to delete this image?')) return;
    
    fetch('<?= ADMIN_URL ?>ajax-media.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'action=delete_image&id=' + id
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            document.querySelector(`#images-grid .media-item[data-id="${id}"]`)?.remove();
            showToast('Image deleted successfully', 'success');
        } else {
            showToast(data.message || 'Failed to delete image', 'error');
        }
    });
}

function setPrimaryImage(id) {
    fetch('<?= ADMIN_URL ?>ajax-media.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'action=set_primary_image&id=' + id
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            showToast(data.message || 'Failed to set primary image', 'error');
        }
    });
}

function deleteVideo(id) {
    if (!confirm('Are you sure you want to delete this video?')) return;
    
    fetch('<?= ADMIN_URL ?>ajax-media.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'action=delete_video&id=' + id
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            document.querySelector(`#videos-grid .media-item[data-id="${id}"]`)?.remove();
            showToast('Video deleted successfully', 'success');
        } else {
            showToast(data.message || 'Failed to delete video', 'error');
        }
    });
}

function showToast(message, type) {
    // Remove any existing toasts first
    document.querySelectorAll('.toast').forEach(t => t.remove());
    
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.innerHTML = `<i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i> ${message}`;
    
    // Create container if it doesn't exist
    let container = document.querySelector('.toast-container');
    if (!container) {
        container = document.createElement('div');
        container.className = 'toast-container';
        document.body.appendChild(container);
    }
    
    container.appendChild(toast);
    setTimeout(() => toast.remove(), 3000);
}

// Itinerary functionality
let dayCounter = <?= count($itineraryItems) ?>;
function addItineraryDay() {
    dayCounter++;
    const container = document.getElementById('itinerary-container');
    const html = `<div class="itinerary-form-item" style="border:1px solid var(--gray-lighter);border-radius:8px;padding:20px;margin-bottom:15px;position:relative;"><button type="button" onclick="this.parentElement.remove()" style="position:absolute;top:10px;right:10px;background:var(--danger);color:#fff;border:none;width:28px;height:28px;border-radius:50%;cursor:pointer;"><i class="fas fa-times"></i></button><div class="form-row" style="grid-template-columns:80px 1fr;"><div class="form-group"><label>Day</label><input type="number" name="itinerary_day[]" class="form-control" value="${dayCounter}"></div><div class="form-group"><label>Title</label><input type="text" name="itinerary_title[]" class="form-control"></div></div><div class="form-group"><label>Description</label><textarea name="itinerary_description[]" class="form-control" rows="3"></textarea></div><div class="form-row"><div class="form-group"><label>Meals</label><input type="text" name="itinerary_meals[]" class="form-control"></div><div class="form-group"><label>Accommodation</label><input type="text" name="itinerary_accommodation[]" class="form-control"></div></div></div>`;
    container.insertAdjacentHTML('beforeend', html);
}
</script>

<?php require_once 'includes/footer.php';
