<div class="container">
    <div class="text-center">
        <div class="card shadow mt-3">
            <h5 class="card-header text-dark  text-center font-weight-bold">Edit Image</h5>
            <div class="card-body">
                <div style="text-align: start;">
                    <button class="toggle-btn btn btn-info mb-5" onclick="toggleDivimg()">Click To View
                        Images</button>
                </div>
                <div id="contentimg" style="display: none;">
                    <div class="row justify-content-center">
                        <?php 
                                $note_title = $edit_row['n_title'];
                                $n_id = $edit_row['n_id'];
                                $img_sql = "SELECT * FROM notes_img  WHERE ni_type = 'image' AND ni_ref = '$edit_row[n_id]' ORDER BY ni_sl ASC";
                                $img_res = mysqli_query($con, $img_sql);
                                if ($img_total_rows = mysqli_num_rows($img_res) > 0) {
                                    $c = 1;
                                    while ($img_row = mysqli_fetch_assoc($img_res)) {
                                        $img_path = "../upload/notes/";
                                        $img_sl = $img_row['ni_sl'];
                                        $img_name = $img_row['ni_name'];
                                        $img_pos = $img_row['ni_pos'];
                             ?>
                        <div class="col-md-4 col-xs-4 mb-5">

                            <form method="POST" enctype="multipart/form-data">
                                <div class="note-img-card">
                                    <img src="<?php echo $img_path . $img_row['ni_name']; ?>" height="120"
                                        style="display: block;margin-left: auto;margin-right: auto; max-width:100%;">
                                    <br>
                                    <!-- Ensure that the file input field is properly named and within the form -->
                                    <input type="file" name="image" class="form-control" />
                                    <!-- Note: name="image[]" to handle multiple images -->
                                    <input type="hidden" name="ni_sl" value="<?php echo $img_sl; ?>"
                                        class="form-control" />
                                    <input type="hidden" name="note_title" value="<?php echo $note_title; ?>"
                                        class="form-control" />
                                    <input type="hidden" name="old_img_name" value="<?php echo $img_name; ?>"
                                        class="form-control" />
                                    <input type="submit" value="Update Img" name="updateImage" id="edit"
                                        class="btn btn-success text-sm-center mt-4" />
                                    <input type="submit" value="Delete Img" name="deleteImage" id="delete"
                                        class="btn btn-danger text-sm-center mt-4" />
                                </div>
                            </form>
                        </div>
                        <?php
                                     }
                                 }
                             ?>
                    </div>
                </div>

                <!--<hr>

                <form method="POST" action="" enctype="multipart/form-data">
                    <div class="row mt-4">
                        <div class="col-md-12">
                            <div class="upload__box">
                                <div class="upload__img-wrap"></div>
                                <div class="upload__btn-box">
                                    <p class="m-0"><span style="color:red;">Note*:</span>Maximum number of
                                        selected Image is 20.</p>
                                    <label class="upload__btn">
                                        <p class="m-0">Select Images</p>
                                        <input type="file" multiple="" name="upload[]" data-max_length="20"
                                            class="upload__inputfile">
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row justify-content-center">
                        <input type="hidden" value="<?php echo $n_id; ?>" name="note_id">
                        <input type="hidden" value="<?php echo $note_title; ?>" name="note_title">
                        <button type="submit" name="img_submit" class="btn btn-success text-sm-center mt-4">Upload
                            Images</button>
                        &nbsp;&nbsp;&nbsp;
                        <a href="view-notes.php" class="btn btn-warning text-sm-center mt-4"> Cancel</a>
                    </div>
                </form>-->
            </div>
        </div>
    </div>
</div>

<script>
function toggleDivimg() {
    var div = document.getElementById("contentimg");
    if (div.style.display === "none" || div.style.display === "") {
        div.style.display = "block";
    } else {
        div.style.display = "none";
    }
}
</script>


<?php
if(isset($_POST['img_submit']) && !empty($_FILES['upload']['name'][0])) {
    $note_id = $_POST["note_id"];
    $note_title = $_POST["note_title"];
    $upload_dir = '../upload/notes/';
    $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
    $max_files = 20;

    // Variable to track successful uploads
    $success_count = 0;

    // Loop through each file
    foreach($_FILES['upload']['name'] as $i => $file_name) {
        // Check if file is uploaded
        if($_FILES['upload']['error'][$i] == UPLOAD_ERR_OK) {
            $file_tmp = $_FILES['upload']['tmp_name'][$i];
            $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

            // Check file type
            if(in_array($file_ext, $allowed_types)) {
                // Generate new file name
                $new_file_name = $note_title . '_' . date('Y-m-d') . '_' . $i . '.' . $file_ext;
                $new_file_path = $upload_dir . $new_file_name;

                // Move file to upload folder
                if (move_uploaded_file($file_tmp, $new_file_path)) {
                    // Compress image
                    $compressed_image = imagecreatefromstring(file_get_contents($new_file_path));
                    imagejpeg($compressed_image, $new_file_path, 50); // Compressing to 50% quality, you can adjust as needed

                    // Update database
                    $insert_query = "INSERT INTO notes_img (ni_name, ni_type, ni_ref) VALUES ('$new_file_name', 'image', '$note_id')";
                    mysqli_query($con, $insert_query); // Execute the insert query

                    // Increment successful upload count
                    $success_count++;
                }
            }
        }
    }

    // If at least one file was successfully uploaded
    if($success_count > 0) {
        // Show success alert and redirect
        echo '<script>alert("' . $success_count . ' Images Upload successful!");</script>';
        echo '<script>window.location = "edit-notes.php?edit_ref=' . $edit_id . '</script>';
        exit; // Stop further execution
    }
}
?>

<?php
    if (isset($_POST['updateImage'])) {
        $ni_sl = mysqli_real_escape_string($con, $_POST['ni_sl']); // Escape user input
        $note_title = mysqli_real_escape_string($con, $_POST['note_title']); // Escape user input

        // Handle file upload for the image
        if (isset($_FILES['image']['error']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $img_tmp_name = $_FILES['image']['tmp_name'];
            $img_name = basename($_FILES['image']['name']); // Sanitize file name
            $img_path = "../upload/notes/";
            $new_img_name = uniqid() . '_' . $img_name; // Generating a unique name for the image
            $target_file = $img_path . $new_img_name;

            // Check file type if needed
            $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
            $allowedTypes = array('jpg', 'jpeg', 'png', 'gif');
            if (!in_array($imageFileType, $allowedTypes)) {
                echo '<script>alert("Sorry, only JPG, JPEG, PNG & GIF files are allowed.");</script>';
                exit;
            }

            // Move uploaded file to destination directory
            if (move_uploaded_file($img_tmp_name, $target_file)) {
                // Update database with new image name
                $update_sql = "UPDATE notes_img SET ni_name = '$new_img_name' WHERE ni_sl = '$ni_sl'";
                $update_result = mysqli_query($con, $update_sql);

                if ($update_result) {
                    // Unlink old image if it exists
                    if (isset($_POST['old_img_name']) && file_exists($img_path . $_POST['old_img_name'])) {
                        unlink($img_path . $_POST['old_img_name']);
                    }

                    // Additional actions if needed
                    echo '<script>alert("Image updated successfully.");</script>';
                    echo '<script>window.location = "edit-notes.php?edit_ref=' . $edit_id . '";</script>';
                    exit; // Terminate script execution after redirection
                } else {
                    // Handle database update error
                    echo '<script>alert("Error updating image in the database.");</script>';
                }
            } else {
                // Handle file upload error
                echo '<script>alert("Error uploading file.");</script>';
            }
        } else {
            // Handle file error
            echo '<script>alert("Error uploading file: ' . $_FILES['image']['error'] . '");</script>';
        }
        
    // Redirect to the appropriate page after processing
    echo '<script>window.location = "edit-notes.php?edit_ref=' . $edit_id . '";</script>';
    } elseif (isset($_POST['deleteImage'])) {
        $ni_sl = mysqli_real_escape_string($con, $_POST['ni_sl']);
        $img_name = basename($_POST['old_img_name']);
        $img_path = "../upload/notes/";

        // Delete image from database
        $delete_sql = "DELETE FROM notes_img WHERE ni_sl = '$ni_sl'";
        $delete_result = mysqli_query($con, $delete_sql);

        if ($delete_result) {
            // Unlink image from directory
            if (file_exists($img_path . $img_name)) {
                unlink($img_path . $img_name);
            }

            // Additional actions if needed
            echo '<script>alert("Image deleted successfully.");</script>';
        } else {
            // Handle deletion error
            echo '<script>alert("Error deleting image.");</script>';
        }
        
    // Redirect to the appropriate page after processing
    echo '<script>window.location = "edit-notes.php?edit_ref=' . $edit_id . '";</script>';
    }
    
?>