<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 Documents</h5>
            <div class="card-body">
                <div style="text-align: start;">
                    <button class="toggle-btn btn btn-info mb-5" onclick="toggleDivDoc()">Click To View
                        Documents</button>
                </div>
                <div id="contentDoc" style="display: none;">
                    <div class="row justify-content-center">
                        <?php 
                                $note_title = $edit_row['n_title'];
                                $n_id = $edit_row['n_id'];
                                $doc_sql = "SELECT * FROM notes_img WHERE ni_type = 'document' AND ni_ref = '$edit_row[n_id]' ORDER BY ni_sl ASC";
                                $doc_res = mysqli_query($con, $doc_sql);
                                if ($doc_total_rows = mysqli_num_rows($doc_res) > 0) {
                                    while ($doc_row = mysqli_fetch_assoc($doc_res)) {
                                        $doc_path = "../upload/notes/";
                                        $doc_sl = $doc_row['ni_sl'];
                                        $doc_name = $doc_row['ni_name'];
                                        $doc_ext = pathinfo($doc_name, PATHINFO_EXTENSION);
                            ?>
                        <div class="col-md-4 col-xs-4 mb-5">
                            <form method="POST" enctype="multipart/form-data">
                                <div class="note-doc-card">
                                    <?php if ($doc_ext == 'pdf') { ?>
                                    <embed src="<?php echo $doc_path . $doc_row['ni_name']; ?>" type="application/pdf"
                                        height="120"
                                        style="display: block;margin-left: auto;margin-right: auto; max-width:100%;">
                                    <?php } else { ?>
                                    <div class="doc-bg"><?php echo $doc_name; ?></div>
                                    <?php } ?>
                                    <br>
                                    <input type="file" name="document" class="form-control"
                                        accept=".pdf,.doc,.docx,.txt" />
                                    <input type="hidden" name="ni_sl" value="<?php echo $doc_sl; ?>"
                                        class="form-control" />
                                    <input type="hidden" name="note_title" value="<?php echo $note_title; ?>"
                                        class="form-control" />
                                    <input type="hidden" name="old_doc_name" value="<?php echo $doc_name; ?>"
                                        class="form-control" />
                                    <input type="submit" value="Update Doc" name="updateDocument" id="edit"
                                        class="btn btn-success text-sm-center mt-4" />
                                    <input type="submit" value="Delete Doc" name="deleteDocument" 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 document-upload">
                                <div class="document-preview"></div>
                                <div class="upload__btn-box">
                                    <p class="m-0"><span style="color:red;">Note*:</span>Maximum number of
                                        selected Documents is 10.</p>
                                    <label class="upload__btn">
                                        <p class="m-0">Select Documents</p>
                                        <input type="file" multiple="" name="document_upload[]" data-max_length="10"
                                            class="upload__inputfile document-upload-input"
                                            accept=".pdf,.doc,.docx,.txt">
                                    </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="doc_submit" class="btn btn-success text-sm-center mt-4">Upload
                            Documents</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 toggleDivDoc() {
    var div = document.getElementById("contentDoc");
    if (div.style.display === "none" || div.style.display === "") {
        div.style.display = "block";
    } else {
        div.style.display = "none";
    }
}
</script>

<?php
// Check if form is submitted and files are uploaded
if(isset($_POST['doc_submit']) && !empty($_FILES['document_upload']['name'][0])) {
    $note_id = $_POST["note_id"];
    $note_title = $_POST["note_title"];
    $upload_dir = '../upload/notes/';
    $allowed_types = array('pdf', 'doc', 'docx', 'txt');
    $max_files = 10;

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

    // Loop through each file
    foreach($_FILES['document_upload']['name'] as $i => $file_name) {
        // Check if file is uploaded
        if($_FILES['document_upload']['error'][$i] == UPLOAD_ERR_OK) {
            $file_tmp = $_FILES['document_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)) {
                    // Update database
                    $insert_query = "INSERT INTO notes_img (ni_name, ni_type, ni_ref) VALUES ('$new_file_name', 'document', '$note_id')";
                    mysqli_query($con, $insert_query); // Execute the insert query

                    // Increment successful upload count
                    $success_count++;
                } else {
                    echo "Error uploading file: " . $_FILES['document_upload']['error'][$i];
                }
            } else {
                echo "Invalid file type: " . $file_name;
            }
        } else {
            echo "File upload error: " . $_FILES['document_upload']['error'][$i];
        }
    }

    // If at least one file was successfully uploaded
    if($success_count > 0) {
        // Show success alert and redirect
        echo '<script>alert("' . $success_count . ' Documents Upload successful!");</script>';
        echo '<script>window.location = "view-notes.php";</script>';
        exit; // Stop further execution
    } else {
        echo '<script>alert("No documents uploaded or all documents failed to upload.");</script>';
    }
}
?>
<?php

if (isset($_POST['updateDocument'])) {
$ni_sl = mysqli_real_escape_string($con, $_POST['ni_sl']);
$note_title = mysqli_real_escape_string($con, $_POST['note_title']);

if (isset($_FILES['document']['error']) && $_FILES['document']['error'] === UPLOAD_ERR_OK) {
$doc_tmp_name = $_FILES['document']['tmp_name'];
$doc_name = basename($_FILES['document']['name']);
$doc_path = "../upload/notes/";
$new_doc_name = $note_title .uniqid() . '_' . $doc_name;
$target_file = $doc_path . $new_doc_name;

$docFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$allowedTypes = array('pdf', 'doc', 'docx', 'txt');
if (!in_array($docFileType, $allowedTypes)) {
echo '<script>
alert("Sorry, only PDF, DOC, DOCX & TXT files are allowed.");
</script>';
exit;
}

if (move_uploaded_file($doc_tmp_name, $target_file)) {
$update_sql = "UPDATE notes_img SET ni_name = '$new_doc_name' WHERE ni_sl = '$ni_sl'";
$update_result = mysqli_query($con, $update_sql);

if ($update_result) {
if (isset($_POST['old_doc_name']) && file_exists($doc_path . $_POST['old_doc_name'])) {
unlink($doc_path . $_POST['old_doc_name']);
}

echo '<script>
alert("Document updated successfully.");
</script>';
echo '<script>
window.location = "edit-notes.php?edit_ref=' . $edit_id . '";
</script>';
exit;
} else {
echo '<script>
alert("Error updating document in the database.");
</script>';
}
} else {
echo '<script>
alert("Error uploading file.");
</script>';
}
} else {
echo '<script>
alert("Error uploading file: ' . $_FILES['document']['error'] . '");
</script>';
}

echo '<script>
window.location = "edit-notes.php?edit_ref=' . $edit_id . '";
</script>';
} elseif (isset($_POST['deleteDocument'])) {
$ni_sl = mysqli_real_escape_string($con, $_POST['ni_sl']);
$doc_name = basename($_POST['old_doc_name']);
$doc_path = "../upload/notes/";

$delete_sql = "DELETE FROM notes_img WHERE ni_sl = '$ni_sl'";
$delete_result = mysqli_query($con, $delete_sql);

if ($delete_result) {
if (file_exists($doc_path . $doc_name)) {
unlink($doc_path . $doc_name);
}

echo '<script>
alert("Document deleted successfully.");
</script>';
} else {
echo '<script>
alert("Error deleting document.");
</script>';
}

echo '<script>
window.location = "edit-notes.php?edit_ref=' . $edit_id . '";
</script>';
}
?>