<?php
// Initialize the session
session_start();
 
// Check if the user is logged in, if not then redirect to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
    header("location: login.php");
    exit;
}

// Include config file
require_once "includes/config.php";

// Initialize variables
$gallery_items = [];
$error = '';
$success = '';
$total_pages = 1;
$current_page = 1;

// Process delete operation
if(isset($_GET["action"]) && $_GET["action"] == "delete" && isset($_GET["id"])) {
    // Prepare a select statement to get the image path
    $sql = "SELECT image_path FROM gallery_images WHERE id = ?";
    
    if($stmt = $conn->prepare($sql)){
        // Bind variables to the prepared statement as parameters
        $stmt->bind_param("i", $param_id);
        
        // Set parameters
        $param_id = trim($_GET["id"]);
        
        // Attempt to execute the prepared statement
        if($stmt->execute()){
            $result = $stmt->get_result();
            
            if($result->num_rows == 1){
                $row = $result->fetch_array(MYSQLI_ASSOC);
                $image_path = $row["image_path"];
                
                // Delete the file if it exists
                if(!empty($image_path) && file_exists("../" . $image_path)) {
                    unlink("../" . $image_path);
                }
                
                // Now delete the record
                $delete_sql = "DELETE FROM gallery_images WHERE id = ?";
                if($delete_stmt = $conn->prepare($delete_sql)){
                    $delete_stmt->bind_param("i", $param_id);
                    if($delete_stmt->execute()){
                        // Record deleted successfully. Redirect to gallery page
                        header("location: gallery.php?success=deleted");
                        exit();
                    } else {
                        $error = "Error deleting record. Please try again.";
                    }
                    $delete_stmt->close();
                }
            } else {
                $error = "Record not found.";
            }
        } else {
            $error = "Oops! Something went wrong. Please try again later.";
        }
    }
    $stmt->close();
    $conn->close();
}

// Check for success messages
if(isset($_GET['success'])) {
    if($_GET['success'] == 'uploaded') {
        $success = 'Image uploaded successfully!';
    } elseif($_GET['success'] == 'updated') {
        $success = 'Image updated successfully!';
    } elseif($_GET['success'] == 'deleted') {
        $success = 'Image deleted successfully!';
    }
}

// Get current page
if (isset($_GET['page'])) {
    $current_page = $_GET['page'];
}

// Attempt to fetch gallery items from the database
try {
    // First, get total count for pagination
    $count_sql = "SELECT COUNT(*) as total FROM gallery_images";
    $count_result = $conn->query($count_sql);
    $total_rows = $count_result->fetch_assoc()['total'];
    $results_per_page = 9; // 3x3 grid
    $total_pages = ceil($total_rows / $results_per_page);
    $start = ($current_page - 1) * $results_per_page;
    
    // Query to get gallery images with pagination
    $sql = "SELECT g.*, c.name as category_name 
            FROM gallery_images g 
            LEFT JOIN gallery_categories c ON g.category_id = c.id 
            ORDER BY g.id DESC 
            LIMIT $start, $results_per_page";
    
    if($result = $conn->query($sql)) {
        if($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                $gallery_items[] = $row;
            }
            $result->free();
        }
    }
} catch (Exception $e) {
    $error = "Error fetching gallery items: " . $e->getMessage();
}

// Close connection
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gallery Management - Real Estate Admin</title>
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome 6 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Custom styles -->
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3f37c9;
            --dark-color: #1a1a2e;
            --light-color: #f8f9fa;
            --success-color: #4cc9f0;
            --danger-color: #f72585;
        }

        body {
            background-color: #f5f7fb;
            color: #4a4a4a;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        /* Sidebar Styles */
        .sidebar {
            background: linear-gradient(180deg, var(--dark-color) 0%, #16213e 100%);
            min-height: 100vh;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
            transition: all 0.3s;
        }

        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 12px 20px;
            margin: 4px 10px;
            border-radius: 8px;
            transition: all 0.3s;
        }

        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            background: rgba(255, 255, 255, 0.1);
            color: white;
            transform: translateX(5px);
        }

        .sidebar .nav-link i {
            width: 24px;
            text-align: center;
            margin-right: 10px;
        }

        /* Main Content */
        .main-content {
            padding: 2rem;
        }

        /* Header */
        .page-header {
            background: white;
            padding: 1.5rem;
            border-radius: 12px;
            box-shadow: 0 2px 15px rgba(0,0,0,0.05);
            margin-bottom: 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .page-title {
            font-weight: 700;
            color: var(--dark-color);
            margin: 0;
        }

        /* Gallery Grid */
        .gallery-container {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 2px 15px rgba(0,0,0,0.05);
        }

        .gallery-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 1.5rem;
            margin-top: 1.5rem;
        }

        .gallery-item {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 6px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
            position: relative;
        }

        .gallery-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }

        .gallery-item-image {
            width: 100%;
            height: 180px;
            object-fit: cover;
            transition: transform 0.5s ease;
        }

        .gallery-item:hover .gallery-item-image {
            transform: scale(1.05);
        }

        .gallery-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.7) 100%);
            opacity: 0;
            transition: opacity 0.3s ease;
            display: flex;
            align-items: flex-end;
            padding: 1rem;
        }

        .gallery-item:hover .gallery-overlay {
            opacity: 1;
        }

        .gallery-actions {
            position: absolute;
            top: 10px;
            right: 10px;
            display: flex;
            gap: 5px;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .gallery-item:hover .gallery-actions {
            opacity: 1;
        }

        .btn-action {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            border: none;
            transition: all 0.2s;
        }

        .btn-edit {
            background: var(--primary-color);
        }

        .btn-delete {
            background: var(--danger-color);
        }

        .btn-action:hover {
            transform: scale(1.1);
        }

        .gallery-info {
            color: white;
            width: 100%;
        }

        .gallery-title {
            font-weight: 600;
            margin: 0;
            font-size: 0.95rem;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .gallery-date {
            font-size: 0.8rem;
            opacity: 0.9;
            margin: 0;
        }

        .category-badge {
            position: absolute;
            top: 10px;
            left: 10px;
            background: var(--success-color);
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 500;
            z-index: 2;
        }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 3rem 1rem;
        }

        .empty-state i {
            font-size: 4rem;
            color: #d1d5db;
            margin-bottom: 1rem;
        }

        .empty-state h4 {
            color: #4b5563;
            margin-bottom: 0.5rem;
        }

        .empty-state p {
            color: #6b7280;
            margin-bottom: 1.5rem;
        }

        /* Buttons */
        .btn-primary {
            background-color: var(--primary-color);
            border: none;
            padding: 0.5rem 1.25rem;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s;
        }

        .btn-primary:hover {
            background-color: var(--secondary-color);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(67, 97, 238, 0.3);
        }

        /* Pagination */
        .pagination {
            margin-top: 2rem;
            justify-content: center;
        }

        .page-link {
            color: var(--primary-color);
            border: 1px solid #dee2e6;
            margin: 0 5px;
            border-radius: 8px !important;
            padding: 0.5rem 1rem;
            min-width: 40px;
            text-align: center;
            transition: all 0.2s;
        }

        .page-item.active .page-link {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }

        .page-link:hover {
            color: var(--secondary-color);
            background-color: #f0f2f5;
            border-color: #dee2e6;
        }

        /* Responsive Adjustments */
        @media (max-width: 768px) {
            .gallery-grid {
                grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            }
            
            .page-header {
                flex-direction: column;
                align-items: flex-start;
            }
        }

        @media (max-width: 576px) {
            .gallery-grid {
                grid-template-columns: 1fr;
            }
            
            .main-content {
                padding: 1rem;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 px-0 sidebar d-md-block">
                <div class="d-flex flex-column flex-shrink-0 p-3 h-100">
                    <a href="index.php" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-white text-decoration-none">
                        <span class="fs-4">RealEstate Pro</span>
                    </a>
                    <hr>
                    <ul class="nav nav-pills flex-column mb-auto">
                        <li class="nav-item">
                            <a href="index.php" class="nav-link">
                                <i class="fas fa-tachometer-alt me-2"></i>
                                Dashboard
                            </a>
                        </li>
                        <li>
                            <a href="properties.php" class="nav-link">
                                <i class="fas fa-home me-2"></i>
                                Properties
                            </a>
                        </li>
                        <li>
                            <a href="gallery.php" class="nav-link active">
                                <i class="fas fa-images me-2"></i>
                                Gallery
                            </a>
                        </li>
                        <li>
                            <a href="categories.php" class="nav-link">
                                <i class="fas fa-tags me-2"></i>
                                Categories
                            </a>
                        </li>
                        <li>
                            <a href="users.php" class="nav-link">
                                <i class="fas fa-users me-2"></i>
                                Users
                            </a>
                        </li>
                        <li>
                            <a href="settings.php" class="nav-link">
                                <i class="fas fa-cog me-2"></i>
                                Settings
                            </a>
                        </li>
                    </ul>
                    <hr>
                    <div class="dropdown">
                        <a href="#" class="d-flex align-items-center text-white text-decoration-none dropdown-toggle" id="dropdownUser1" data-bs-toggle="dropdown" aria-expanded="false">
                            <img src="https://ui-avatars.com/api/?name=<?php echo urlencode($_SESSION['username'] ?? 'Admin'); ?>&background=4361ee&color=fff" alt="User" width="32" height="32" class="rounded-circle me-2">
                            <strong><?php echo htmlspecialchars($_SESSION['username'] ?? 'Admin'); ?></strong>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-dark text-small shadow" aria-labelledby="dropdownUser1">
                            <li><a class="dropdown-item" href="profile.php">Profile</a></li>
                            <li><a class="dropdown-item" href="settings.php">Settings</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="logout.php">Sign out</a></li>
                        </ul>
                    </div>
                </div>
            </div>

            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 main-content">
                <!-- Page Header -->
                <div class="page-header">
                    <h1 class="page-title">Gallery Management</h1>
                    <a href="gallery-upload.php" class="btn btn-primary">
                        <i class="fas fa-plus me-2"></i>Add New Image
                    </a>
                </div>

                <!-- Success/Error Messages -->
                <?php if(!empty($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <div class="d-flex align-items-center">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            <?php echo $error; ?>
                        </div>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <?php if(!empty($success)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <div class="d-flex align-items-center">
                            <i class="fas fa-check-circle me-2"></i>
                            <?php echo $success; ?>
                        </div>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <!-- Gallery Grid -->
                <div class="gallery-container">
                    <?php if(empty($gallery_items)): ?>
                        <div class="empty-state">
                            <i class="fas fa-images fa-4x mb-4"></i>
                            <h4>No Images Found</h4>
                            <p class="mb-4">The gallery is currently empty. Upload some images to get started.</p>
                            <a href="gallery-upload.php" class="btn btn-primary">
                                <i class="fas fa-upload me-2"></i>Upload Your First Image
                            </a>
                            <div class="mt-4">
                                <p class="text-muted">Supported formats: JPG, PNG, GIF, WEBP</p>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="gallery-grid">
                            <?php foreach($gallery_items as $item): 
                                $image_path = !empty($item['image_path']) ? '../' . $item['image_path'] : 'path/to/default-image.jpg';
                            ?>
                                <div class="gallery-item">
                                    <div class="gallery-item-image">
                                        <img src="<?php echo htmlspecialchars($image_path); ?>" alt="<?php echo htmlspecialchars($item['title'] ?? 'Gallery Image'); ?>" class="img-fluid">
                                    </div>
                                    <div class="gallery-item-info">
                                        <h5 class="gallery-item-title"><?php echo htmlspecialchars($item['title'] ?? 'Untitled'); ?></h5>
                                        <?php if(!empty($item['category_name'])): ?>
                                        <span class="category-badge"><?php echo htmlspecialchars($item['category_name']); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    <div class="gallery-actions">
                                        <a href="gallery-edit.php?id=<?php echo $item['id']; ?>" class="btn btn-sm btn-outline-primary" title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <a href="gallery-view.php?id=<?php echo $item['id']; ?>" class="btn btn-sm btn-outline-secondary" title="View">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <a href="gallery.php?action=delete&id=<?php echo $item['id']; ?>" class="btn btn-sm btn-outline-danger" 
                                           onclick="return confirm('Are you sure you want to delete this image? This action cannot be undone.');"
                                           title="Delete">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <!-- Pagination -->
                        <?php if($total_pages > 1): ?>
                            <nav aria-label="Gallery pagination" class="mt-4">
                                <ul class="pagination justify-content-center">
                                    <?php if($current_page > 1): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?php echo ($current_page - 1); ?>" aria-label="Previous">
                                                <span aria-hidden="true">&laquo;</span>
                                            </a>
                                        </li>
                                    <?php endif; ?>

                                    <?php 
                                    $start_page = max(1, $current_page - 2);
                                    $end_page = min($total_pages, $start_page + 4);
                                    $start_page = max(1, $end_page - 4);
                                    
                                    if($start_page > 1) {
                                        echo '<li class="page-item"><span class="page-link">...</span></li>';
                                    }
                                    
                                    for($i = $start_page; $i <= $end_page; $i++): 
                                    ?>
                                        <li class="page-item <?php echo ($i == $current_page) ? 'active' : ''; ?>">
                                            <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                        </li>
                                    <?php 
                                    endfor; 
                                    
                                    if($end_page < $total_pages) {
                                        echo '<li class="page-item"><span class="page-link">...</span></li>';
                                    }
                                    ?>

                                    <?php if($current_page < $total_pages): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?php echo ($current_page + 1); ?>" aria-label="Next">
                                                <span aria-hidden="true">&raquo;</span>
                                            </a>
                                        </li>
                                    <?php endif; ?>
                                </ul>
                            </nav>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </main>
        </div>
    </div>

    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Enable tooltips
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[title]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });

        // Add smooth scrolling to top when clicking pagination links
        document.querySelectorAll('.page-link').forEach(link => {
            link.addEventListener('click', function(e) {
                if (this.getAttribute('href').startsWith('?')) {
                    e.preventDefault();
                    window.scrollTo({
                        top: 0,
                        behavior: 'smooth'
                    });
                    setTimeout(() => {
                        window.location.href = this.getAttribute('href');
                    }, 300);
                }
            });
        });
    </script>
</body>
</html>