<?php include_once('header.php'); ?>
<?php
$action = '';
$gallery_id = '';
if (isset($_GET['action']) && isset($_GET['gallery_id'])) {
    $action = $_GET['action'];
    $gallery_id = $_GET['gallery_id'];
}
?>
<style type="text/css">
    .error {
        border-color: #ecbeb6;
        color: #b55351;
        text-transform: capitalize;
        text-align: left !important;
    }

    #error {
        width: 100%;
    }

    .alert {
        width: 100%;
        text-align: left;
    }
</style>
<div class="container mt-3">
    <div class="card-deck mb-3 text-center">
        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 mt-3 border-bottom" style="width: 100%;">
            <h1 class="h2">Gallery Management</h1>
            <div class="btn-toolbar mb-2 mb-md-0">
                <div class="btn-group mr-2">
                    <?php if($action == ''){ ?>
                    <button type="button" class="btn btn-sm btn-primary" onclick="scrollToForm()">Add Image</button>
                    <?php } else { ?>
                    <a class="btn btn-sm btn-outline-secondary" href="gallery.php">Back to List</a>
                    <?php } ?>
                </div>
            </div>
        </div>

        <div id="error"></div>

        <div class="row text-left">
            <div id="live_data" class="col-md-8"></div>
            <div class="col-md-4">
                <?php if($action == ''){ ?>
                <h4 style="text-align: left;" id="formTitle">Add Gallery Image</h4><br>
                <div id="err"></div>
                <form class="needs-validation" style="text-align: left;" id="add-gallery-form" method="post" enctype="multipart/form-data" action="sql_statements.php">
                    <div class="row">
                        <div class="col-md-12 mb-3">
                            <label for="title" style="text-align:left; float:left">Image Title</label>
                            <input type="text" class="form-control" name="title" required>
                        </div>
                        <div class="col-md-12 mb-3">
                            <label for="category" style="text-align:left; float:left">Category</label>
                            <select class="form-control" name="category" required>
                                <option value="">Select Category</option>
                                <option value="Rooms">Rooms</option>
                                <option value="Restaurant">Restaurant</option>
                                <option value="Events">Events</option>
                                <option value="Other">Other</option>
                            </select>
                        </div>
                        <div class="col-md-12 mb-3">
                            <label for="image" style="text-align:left; float:left">Select Image (JPG, PNG, JPEG)</label>
                            <input type="file" class="form-control" id="image" name="image" accept="image/*" required>
                        </div>
                        <div class="col-md-12 mb-3">
                            <button class="btn btn-primary btn-md form-control" type="submit" name="add_gallery" value="1" style="float: left;">
                                Add Image
                            </button>
                        </div>
                    </div>
                </form>
                <?php } else if($action == 'update'){ ?>
                <h4 style="text-align: left;">Update Gallery Image <a href="gallery.php" class="btn btn-primary btn-sm" style="float:right;"> Gallery List</a></h4><br>
                <?php 
                    $gallery = $con->getRows('gallery', array('where' => 'gallery_id="' . $gallery_id . '"', 'return_type' => 'single'));
                    if(!empty($gallery)){
                ?>
                <div id="err"></div>
                <form class="needs-validation" style="text-align: left;" id="update-gallery-form" method="post" enctype="multipart/form-data" action="sql_statements.php">
                    <div class="row">
                        <div class="col-md-12 mb-3">
                            <label for="title" style="text-align:left; float:left">Image Title</label>
                            <input type="text" class="form-control" name="title" value="<?=$gallery['title']?>" required>
                        </div>
                        <div class="col-md-12 mb-3">
                            <label for="category" style="text-align:left; float:left">Category</label>
                            <select class="form-control" name="category" required>
                                <option value="Events" <?=$gallery['category']=='Events'?'selected':''?>>Events</option>
                                <option value="Other" <?=$gallery['category']=='Other'?'selected':''?>>Other</option>
                            </select>
                        </div>
                        <div class="col-md-12 mb-3">
                            <label for="image" style="text-align:left; float:left">Current Image</label>
                            <img src="../../../assets/uploads/gallery/<?=$gallery['image']?>" style="max-width: 100%; height: auto; margin-bottom: 10px; border: 1px solid #ddd; padding: 5px;">
                        </div>
                        <div class="col-md-12 mb-3">
                            <label for="image" style="text-align:left; float:left">Update Image (Leave empty to keep current)</label>
                            <input type="file" class="form-control" id="image" name="image" accept="image/*">
                            <input type="hidden" name="current_image" value="<?=$gallery['image']?>">
                        </div>
                        <div class="col-md-12 mb-3">
                            <input type="hidden" name="gallery_id" value="<?=$gallery['gallery_id']?>">
                            <button class="btn btn-primary btn-md form-control" type="submit" name="update_gallery" value="1" style="float: left;">
                                Update Image
                            </button>
                        </div>
                    </div>
                </form>
                <?php } } ?>
            </div>
        </div>
    </div>
</div>

<!-- Bootstrap core JavaScript -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="../../js/vendor/popper.min.js"></script>
<script src="../../js/bootstrap.min.js"></script>
<script src="../../js/vendor/holder.min.js"></script>
<script type="text/javascript" src="../../js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="../../js/validation.min.js"></script>
<script src="../../js/tables/jquery.dataTables.js"></script>
<script src="../../js/tables/dataTables.bootstrap4.js"></script>

<script>
    function fetchData() {
        $.ajax({
            url: "select-gallery.php",
            method: "GET",
            success: function(data) {
                $('#live_data').html(data);
            }
        });
    }

    function scrollToForm() {
        document.getElementById('formTitle').scrollIntoView({ behavior: 'smooth' });
    }

    $(document).ready(function() {
        fetchData();

        // Validate and submit ADD GALLERY form
        $("#add-gallery-form").validate({
            rules: {
                title: { required: true },
                image: { required: true },
                category: { required: true }
            },
            messages: {
                title: "Please enter image title",
                image: "Please select an image",
                category: "Please select a category"
            },
            submitHandler: function(form) {
                var formData = new FormData(form);
                formData.append('add_gallery', '1');
                
                $.ajax({
                    url: 'sql_statements.php',
                    type: 'POST',
                    data: formData,
                    success: function(response) {
                        if(response == '1') {
                            alert('Image added successfully!');
                            form.reset();
                            fetchData();
                        } else {
                            alert('Failed to add image. Please try again.');
                        }
                    },
                    error: function() {
                        alert('Error submitting form.');
                    },
                    cache: false,
                    contentType: false,
                    processData: false
                });
                return false;
            }
        });

        // Validate and submit UPDATE GALLERY form
        $("#update-gallery-form").validate({
            rules: {
                title: { required: true },
                category: { required: true }
            },
            messages: {
                title: "Please enter image title",
                category: "Please select a category"
            },
            submitHandler: function(form) {
                var formData = new FormData(form);
                formData.append('update_gallery', '1');
                
                $.ajax({
                    url: 'sql_statements.php',
                    type: 'POST',
                    data: formData,
                    success: function(response) {
                        if(response == '1') {
                            alert('Image updated successfully!');
                            window.location.href = 'gallery.php';
                        } else {
                            alert('Failed to update image. Please try again.');
                        }
                    },
                    error: function() {
                        alert('Error submitting form.');
                    },
                    cache: false,
                    contentType: false,
                    processData: false
                });
                return false;
            }
        });

        $(document).on('click', '.btn_delete', function(e) {
            if (confirm("Are you sure you want to delete this image?")) {
                var id = $(this).attr('data-id3');
                $.ajax({
                    url: "sql_statements.php",
                    type: "POST",
                    data: { action: 'delete_gallery', id: id },
                    success: function(data) {
                        if(data == '1') {
                            fetchData();
                        }
                    }
                });
            }
        });

        $(document).on('click', '.btn_show', function(e) {
            var id = $(this).attr('data-id');
            $.ajax({
                url: "sql_statements.php",
                type: "POST",
                data: { action: 'show_gallery', id: id },
                success: function(data) {
                    if(data == '1') {
                        fetchData();
                    }
                }
            });
        });

        $(document).on('click', '.btn_hide', function(e) {
            var id = $(this).attr('data-id');
            $.ajax({
                url: "sql_statements.php",
                type: "POST",
                data: { action: 'hide_gallery', id: id },
                success: function(data) {
                    if(data == '1') {
                        fetchData();
                    }
                }
            });
        });
    });
</script>
