<?php
require_once '../includes/config.php';
requireAuth();
require_once '../includes/functions.php';

$section = $_GET['section'] ?? 'hero';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($section === 'gallery') {
        // Handle gallery image upload
        if (!empty($_FILES['image']['name'])) {
            $result = uploadImage($_FILES['image'], $_POST['caption']);
            if ($result['success']) {
                $success = "Image uploaded successfully!";
            } else {
                $error = $result['message'];
            }
        }
    } else {
        // Handle content update
        $title = $_POST['title'] ?? '';
        $content = $_POST['content'] ?? '';
        $imageUrl = $_POST['image_url'] ?? '';
        
        if (updateWebsiteContent($section, $title, $content, $imageUrl)) {
            $success = "Content updated successfully!";
        } else {
            $error = "Error updating content";
        }
    }
}

// Handle image deletion
if (isset($_GET['delete_image'])) {
    if (deleteImage($_GET['delete_image'])) {
        $success = "Image deleted successfully!";
    } else {
        $error = "Error deleting image";
    }
    header("Location: edit_content.php?section=gallery");
    exit;
}

// Get current content
if ($section !== 'gallery') {
    $currentContent = getWebsiteContent($section);
}

// Get gallery images if needed
if ($section === 'gallery') {
    $gallery = getAllGalleryImages();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit <?= ucfirst($section) ?> - <?= SITE_NAME ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
    <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8f9fa;
        }
        .sidebar {
            position: fixed;
            top: 0;
            left: 0;
            bottom: 0;
            width: 250px;
            background-color: #1a5276;
            color: white;
            padding: 20px 0;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
        }
        .main-content {
            margin-left: 250px;
            padding: 20px;
        }
        .sidebar-header {
            padding: 0 20px 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        .sidebar-menu {
            padding: 20px 0;
        }
        .sidebar-menu a {
            display: block;
            padding: 10px 20px;
            color: white;
            text-decoration: none;
            transition: background-color 0.3s;
        }
        .sidebar-menu a:hover, .sidebar-menu a.active {
            background-color: rgba(255, 255, 255, 0.1);
        }
        .sidebar-menu i {
            margin-right: 10px;
            width: 20px;
            text-align: center;
        }
        .gallery-img {
            height: 150px;
            object-fit: cover;
            border-radius: 5px;
        }
        .section-img {
            height: 200px;
            object-fit: cover;
            border-radius: 5px;
        }
        .note-editable {
            min-height: 200px;
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="sidebar-header">
            <h4><?= SITE_NAME ?></h4>
            <p class="mb-0">Admin Dashboard</p>
        </div>
        <div class="sidebar-menu">
            <a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
            <a href="edit_content.php" class="active"><i class="fas fa-edit"></i> Edit Content</a>
            <a href="edit_content.php?section=gallery"><i class="fas fa-images"></i> Manage Gallery</a>
            <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>
    
    <div class="main-content">
        <nav aria-label="breadcrumb" class="mb-4">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                <li class="breadcrumb-item active" aria-current="page">Edit <?= ucfirst($section) ?></li>
            </ol>
        </nav>
        
        <h1 class="mb-4">Edit <?= ucfirst($section) ?></h1>
        
        <?php if (isset($success)): ?>
        <div class="alert alert-success"><?= $success ?></div>
        <?php endif; ?>
        
        <?php if (isset($error)): ?>
        <div class="alert alert-danger"><?= $error ?></div>
        <?php endif; ?>
        
        <?php if ($section === 'gallery'): ?>
        <div class="card mb-4">
            <div class="card-header">
                Upload New Image
            </div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="image" class="form-label">Image</label>
                        <input type="file" class="form-control" id="image" name="image" required>
                    </div>
                    <div class="mb-3">
                        <label for="caption" class="form-label">Caption (Optional)</label>
                        <input type="text" class="form-control" id="caption" name="caption">
                    </div>
                    <button type="submit" class="btn btn-primary">Upload Image</button>
                </form>
            </div>
        </div>
        
        <div class="card">
            <div class="card-header">
                Gallery Images
            </div>
            <div class="card-body">
                <?php if (count($gallery) > 0): ?>
                <div class="row">
                    <?php foreach ($gallery as $image): ?>
                    <div class="col-md-4 mb-4">
                        <div class="card">
                            <img src="../<?= $image['image_url'] ?>" class="card-img-top gallery-img" alt="Gallery Image">
                            <div class="card-body">
                                <p class="card-text"><?= $image['caption'] ?: 'No caption' ?></p>
                                <a href="edit_content.php?section=gallery&delete_image=<?= $image['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete this image?')">
                                    <i class="fas fa-trash"></i> Delete
                                </a>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php else: ?>
                <p class="text-muted">No gallery images yet.</p>
                <?php endif; ?>
            </div>
        </div>
        <?php else: ?>
        <div class="card">
            <div class="card-header">
                Edit <?= ucfirst($section) ?> Content
            </div>
            <div class="card-body">
                <form method="POST">
                    <div class="mb-3">
                        <label for="title" class="form-label">Title</label>
                        <input type="text" class="form-control" id="title" name="title" value="<?= htmlspecialchars($currentContent['title'] ?? '') ?>">
                    </div>
                    <div class="mb-3">
                        <label for="content" class="form-label">Content</label>
                        <textarea class="form-control" id="content" name="content"><?= htmlspecialchars($currentContent['content'] ?? '') ?></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="image_url" class="form-label">Image URL</label>
                        <input type="text" class="form-control" id="image_url" name="image_url" value="<?= htmlspecialchars($currentContent['image_url'] ?? '') ?>">
                        <?php if (!empty($currentContent['image_url'])): ?>
                        <div class="mt-2">
                            <img src="../<?= $currentContent['image_url'] ?>" class="section-img" alt="Section Image">
                        </div>
                        <?php endif; ?>
                    </div>
                    <button type="submit" class="btn btn-primary">Save Changes</button>
                </form>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#content').summernote({
                height: 300,
                toolbar: [
                    ['style', ['bold', 'italic', 'underline', 'clear']],
                    ['font', ['strikethrough', 'superscript', 'subscript']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['insert', ['link', 'picture', 'video']],
                    ['view', ['fullscreen', 'codeview', 'help']]
                ]
            });
        });
    </script>
</body>
</html>