<?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
$id = 0;
$title = '';
$description = '';
$image_path = '';
$error = '';

// Process form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Get hidden input value
    $id = $_POST["id"];
    
    // Validate title
    $input_title = trim($_POST["title"]);
    if(empty($input_title)){
        $error = "Please enter a title.";
    } else{
        $title = $input_title;
    }
    
    // Validate description
    $description = trim($_POST["description"]);
    
    // Check input errors before updating in database
    if(empty($error)){
        // Check if a new image was uploaded
        if(!empty($_FILES["image"]["name"])) {
            $target_dir = "../images/gallery/";
            $imageFileType = strtolower(pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION));
            $new_filename = "img_" . uniqid() . "." . $imageFileType;
            $target_file = $target_dir . $new_filename;
            
            // Check if image file is an actual image
            $check = getimagesize($_FILES["image"]["tmp_name"]);
            if($check === false) {
                $error = "File is not an image.";
            } 
            // Check file size (5MB max)
            else if ($_FILES["image"]["size"] > 5 * 1024 * 1024) {
                $error = "Sorry, your file is too large. Maximum size is 5MB.";
            }
            // Allow certain file formats
            else if(!in_array($imageFileType, ["jpg", "jpeg", "png", "gif", "webp"])) {
                $error = "Sorry, only JPG, JPEG, PNG, GIF & WEBP files are allowed.";
            }
            // Try to upload file
            else if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
                // Delete old image if it exists
                if(!empty($image_path) && file_exists("../" . $image_path)) {
                    unlink("../" . $image_path);
                }
                $image_path = "images/gallery/" . $new_filename;
            } else {
                $error = "Sorry, there was an error uploading your file.";
            }
        }
        
        if(empty($error)) {
            // Prepare an update statement
            if(!empty($image_path)) {
                $sql = "UPDATE gallery SET title=?, description=?, image_path=? WHERE id=?";
            } else {
                $sql = "UPDATE gallery SET title=?, description=? WHERE id=?";
            }
            
            if($stmt = $conn->prepare($sql)){
                if(!empty($image_path)) {
                    $stmt->bind_param("sssi", $title, $description, $image_path, $id);
                } else {
                    $stmt->bind_param("ssi", $title, $description, $id);
                }
                
                // Attempt to execute the prepared statement
                if($stmt->execute()){
                    // Records updated successfully. Redirect to gallery page
                    header("location: gallery.php?success=updated");
                    exit();
                } else{
                    $error = "Something went wrong. Please try again later.";
                }
                $stmt->close();
            }
        }
    }
} else {
    // Check existence of id parameter before processing further
    if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
        // Get URL parameter
        $id =  trim($_GET["id"]);
        
        // Prepare a select statement
        $sql = "SELECT * FROM gallery 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 = $id;
            
            // Attempt to execute the prepared statement
            if($stmt->execute()){
                $result = $stmt->get_result();
                
                if($result->num_rows == 1){
                    /* Fetch result row as an associative array. Since the result set
                    contains only one row, we don't need to use while loop */
                    $row = $result->fetch_array(MYSQLI_ASSOC);
                    
                    // Retrieve individual field value
                    $title = $row["title"];
                    $description = $row["description"];
                    $image_path = $row["image_path"];
                } else{
                    // URL doesn't contain valid id. Redirect to error page
                    header("location: error.php");
                    exit();
                }
                
            } else{
                $error = "Oops! Something went wrong. Please try again later.";
            }
            $stmt->close();
        }
    } else{
        // URL doesn't contain id parameter. Redirect to error page
        header("location: error.php");
        exit();
    }
}

// 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>Edit Image - 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">
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3f37c9;
            --dark-color: #1a1a2e;
            --light-color: #f8f9fa;
        }

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

        .form-container {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 2px 15px rgba(0,0,0,0.05);
            margin-top: 2rem;
        }

        .form-label {
            font-weight: 600;
            margin-bottom: 0.5rem;
        }

        .form-control, .form-select, .form-file-input {
            border-radius: 8px;
            padding: 0.75rem 1rem;
            border: 1px solid #dee2e6;
            transition: all 0.3s;
        }

        .form-control:focus, .form-select:focus, .form-file-input:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.25rem rgba(67, 97, 238, 0.25);
        }

        .btn-primary {
            background-color: var(--primary-color);
            border: none;
            padding: 0.75rem 1.5rem;
            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);
        }

        .preview-image {
            max-width: 100%;
            height: auto;
            border-radius: 8px;
            margin-top: 1rem;
            border: 1px solid #dee2e6;
            padding: 0.5rem;
            background-color: #f8f9fa;
        }

        .image-preview-container {
            text-align: center;
            margin-bottom: 1.5rem;
        }

        .back-link {
            color: var(--primary-color);
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            margin-bottom: 1.5rem;
            transition: all 0.3s;
        }

        .back-link:hover {
            color: var(--secondary-color);
            transform: translateX(-3px);
        }

        .back-link i {
            margin-right: 0.5rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-8">
                <a href="gallery.php" class="back-link">
                    <i class="fas fa-arrow-left"></i> Back to Gallery
                </a>
                
                <div class="form-container">
                    <h2 class="mb-4">Edit Image</h2>
                    
                    <?php 
                    if(!empty($error)){
                        echo '<div class="alert alert-danger">' . $error . '</div>';
                    }        
                    ?>
                    
                    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
                        <div class="mb-3">
                            <label class="form-label">Title <span class="text-danger">*</span></label>
                            <input type="text" name="title" class="form-control" value="<?php echo htmlspecialchars($title); ?>" required>
                        </div>
                        
                        <div class="mb-4">
                            <label class="form-label">Description</label>
                            <textarea name="description" class="form-control" rows="3"><?php echo htmlspecialchars($description); ?></textarea>
                        </div>
                        
                        <div class="mb-4">
                            <label class="form-label">Current Image</label>
                            <div class="image-preview-container">
                                <?php if(!empty($image_path) && file_exists("../" . $image_path)): ?>
                                    <img src="/Real_state_website/<?php echo htmlspecialchars($image_path); ?>" alt="Current Image" class="preview-image" style="max-height: 300px;">
                                    <p class="text-muted mt-2">Current image will be replaced if you upload a new one.</p>
                                <?php else: ?>
                                    <div class="alert alert-warning">No image found for this entry.</div>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="mb-4">
                            <label class="form-label">Change Image</label>
                            <input type="file" name="image" class="form-control" accept="image/*" onchange="previewImage(this)">
                            <div class="form-text">Leave blank to keep the current image. Max size: 5MB. Allowed formats: JPG, JPEG, PNG, GIF, WEBP</div>
                        </div>
                        
                        <div class="d-flex justify-content-between align-items-center">
                            <input type="hidden" name="id" value="<?php echo $id; ?>">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save me-2"></i>Save Changes
                            </button>
                            <a href="gallery.php" class="btn btn-outline-secondary">Cancel</a>
                        </div>
                    </form>
                </div>
            </div>
        </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>
        // Preview image before upload
        function previewImage(input) {
            const previewContainer = document.querySelector('.image-preview-container');
            
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                
                reader.onload = function(e) {
                    previewContainer.innerHTML = `
                        <img src="${e.target.result}" alt="Preview" class="preview-image" style="max-height: 300px;">
                        <p class="text-muted mt-2">New image preview</p>
                    `;
                }
                
                reader.readAsDataURL(input.files[0]);
            }
        }
    </script>
</body>
</html>
