<?php
/**
 *
 * Copyright (C) 2007,2008  Arie Nugraha (dicarve@yahoo.com)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

/* Dynamic content Management section */

// key to authenticate
define('INDEX_AUTH', '1');
// key to get full database access
define('DB_ACCESS', 'fa');

use SLiMS\Filesystems\Storage;
use SLiMS\Url;

// main system configuration
require '../../../sysconfig.inc.php';
// IP based access limitation
require LIB.'ip_based_access.inc.php';
do_checkIP('smc');
do_checkIP('smc-system');
// start the session
require SB.'admin/default/session.inc.php';
require SB.'admin/default/session_check.inc.php';
require SIMBIO.'simbio_GUI/form_maker/simbio_form_table_AJAX.inc.php';
require SIMBIO.'simbio_GUI/template_parser/simbio_template_parser.inc.php';
require SIMBIO.'simbio_GUI/table/simbio_table.inc.php';
require SIMBIO.'simbio_GUI/paging/simbio_paging.inc.php';
require SIMBIO.'simbio_DB/datagrid/simbio_dbgrid.inc.php';
require SIMBIO . 'simbio_FILE/simbio_file_upload.inc.php';
require SIMBIO.'simbio_DB/simbio_dbop.inc.php';

$base_url = Url::getSlimsBaseUri();

// privileges checking
$can_read = utility::havePrivilege('system', 'r');
$can_write = utility::havePrivilege('system', 'w');

if (!$can_read) {
    die('<div class="errorBox">'.__('You don\'t have enough privileges to view this section').'</div>');
}

/* ----------------------------------------------------
 * CEK LIBRARY_ID DARI PUSTAKAWAN YANG SEDANG LOGIN
 * ---------------------------------------------------- */
$user_lib_id = $_SESSION['user_lib_id'] ?? null;

// Jika tidak ada di sesi, ambil langsung dari DB berdasarkan ID user
if (is_null($user_lib_id) && isset($_SESSION['uid'])) {
    $user_q = $dbs->query("SELECT library_id FROM user WHERE user_id = " . intval($_SESSION['uid']));
    if ($user_q && $user_d = $user_q->fetch_assoc()) {
        $user_lib_id = $user_d['library_id'];
    }
}

// Ambil tipe user dari session SLiMS (biasanya $_SESSION['utype'])
$user_type = $_SESSION['utype'] ?? $_SESSION['user_type'] ?? null;

// Cek apakah user adalah Super Admin
// Super admin jika: library_id kosong/1 ATAU tipe user-nya 'A' (Admin) / 1
$is_super_admin = (empty($user_lib_id) || $user_lib_id == 1 || $user_type === 'A' || $user_type == 1);


// Image upload handler from CKEditor5
if ($can_write AND !empty($_FILES['upload']) AND $_FILES['upload']['size']) {

    ob_start();
    header('Content-Type: application/json');
    try {
        if (!is_writable(IMGBS)) throw new Exception(IMGBS . ' is not writeable!');
        if (!is_dir(IMGBS . 'content') && !mkdir(IMGBS . 'content')) throw new Exception('Failed to create ' . IMGBS . 'content');

        $images_disk = Storage::images();
        $file_key = 'upload';
        $filename_base = basename($_FILES[$file_key]['name'] ?? 'file');
        $unique_filename = hash('sha256', time() . $filename_base);
        $image_upload = $images_disk->upload($file_key, function($images) use($sysconf) {
            $images->isExtensionAllowed($sysconf['allowed_images']);
            $images->isLimitExceeded($sysconf['max_image_upload']*1024);
            if (empty($images->getError())) $images->cleanExifInfo();
            if (empty($images->getError())) $images->sanitizeImageWithGD();
            if (!empty($images->getError())) $images->destroyIfFailed();
        })->as('content/' . $unique_filename);

        if ($image_upload->getUploadStatus()) {
            ob_end_clean();
            $original_filename = $_FILES[$file_key]['name'];
            $extension = pathinfo($original_filename, PATHINFO_EXTENSION);
            $final_filename = $unique_filename;
            if (!empty($extension)) {
                $final_filename .= '.' . strtolower($extension);
            }
            $public_url = rtrim($base_url, '/') . '/images/content/' . $final_filename;
            echo json_encode(['uploaded' => true, 'url' => $public_url]);
            writeLog('staff', $_SESSION['uid'], 'system', $_SESSION['realname'] . ' upload content image file content/' . $final_filename);
        } else {
            throw new Exception($image_upload->getError());
        }

    } catch (Exception $e) {
        ob_end_clean();
        echo json_encode(['uploaded' => false, 'error' => ['message' => 'Error : ' . $e->getMessage()]]);
    }
    exit;
}

if (isset($_POST['action']) AND $_POST['action'] == 'deleteImage' AND isset($_POST['imageURL'])) {
    if (!$can_write) {
        http_response_code(403);
        die(json_encode(['status' => 'error', 'message' => 'Not enough privileges.']));
    }

    $imageURL = trim($_POST['imageURL']);

    if (strpos($imageURL, '/images/content/') === false) {
        http_response_code(400);
        die(json_encode(['status' => 'error', 'message' => 'Invalid image path pattern.']));
    }

    $base_path_segment = '/images/';
    $pos = strpos($imageURL, $base_path_segment);

    if (!defined('IMGBS')) {
        http_response_code(500);
        die(json_encode(['status' => 'error', 'message' => 'IMGBS constant not defined.']));
    }

    if ($pos !== false) {
        $relative_path_from_images = substr($imageURL, $pos + strlen($base_path_segment));
        $file_to_delete = IMGBS . $relative_path_from_images;

        if (file_exists($file_to_delete) && is_file($file_to_delete)) {
            if (@unlink($file_to_delete)) {
                writeLog('staff', $_SESSION['uid'], 'system', 'REAL-TIME DELETE content image file: ' . $relative_path_from_images);
                die(json_encode(['status' => 'success', 'message' => 'File deleted.']));
            } else {
                http_response_code(500);
                die(json_encode(['status' => 'error', 'message' => 'Failed to delete file. Check permissions.']));
            }
        } else {
            die(json_encode(['status' => 'success', 'message' => 'File not found on server, assuming deleted.']));
        }
    } else {
        http_response_code(400);
        die(json_encode(['status' => 'error', 'message' => 'Could not determine file path.']));
    }
    exit;
}

/* RECORD OPERATION */
if (isset($_POST['saveData'])) {
    if (!$can_write) {
        utility::jsToastr('Error', __('You don\'t have enough privileges to perform this action'), 'error');
        exit();
    }

    $contentTitle = trim(strip_tags($_POST['contentTitle']));
    $contentPath = trim(strip_tags($_POST['contentPath']));

    if (empty($contentTitle) OR empty($contentPath)) {
        utility::jsToastr('Error', __('Title or Path can\'t be empty!'), 'error');
        exit();
    } else {
        $data['content_title'] = $dbs->escape_string(strip_tags(trim($contentTitle)));
        $data['content_path'] = strtolower($dbs->escape_string(strip_tags(trim($contentPath))));
        $data['is_news'] = '0';
        if (isset($_POST['isNews']) && $_POST['isNews'] == '1') {
            $data['is_news'] = '1';
        }

        if (!empty($_POST['publishDate'])) {
            $data['publish_date'] = $dbs->escape_string($_POST['publishDate']);
        }

        $data['is_draft'] = (isset($_POST['isDraft']) && $_POST['isDraft'] == '1') ? '1' : '0';
        
        // PUSTAKAWAN UNIT: Kunci library_id sesuai dengan unit pustakawan tersebut
        if (!$is_super_admin) {
            $data['library_id'] = intval($user_lib_id);
        } else {
            $data['library_id'] = isset($_POST['library_id']) ? intval($_POST['library_id']) : 1;
        }

        $allowed_html_tags = '<h1><h2><h3><h4><h5><h6><p><a><img><ul><ol><li><br><em><strong><u><span><div><table><thead><tbody><tr><td><th>';
        $raw_content_desc = trim($_POST['contentDesc']);

        if (method_exists('utility', 'cleanHTML')) {
             $clean_content_desc = utility::cleanHTML($raw_content_desc, $allowed_html_tags);
        } else {
             $clean_content_desc = strip_tags($raw_content_desc, $allowed_html_tags);
        }

        $data['content_desc'] = $dbs->escape_string(html_entity_decode($clean_content_desc, ENT_QUOTES, 'UTF-8'));
        $data['input_date'] = date('Y-m-d H:i:s');
        $data['last_update'] = date('Y-m-d H:i:s');

        $sql_op = new simbio_dbop($dbs);
        if (isset($_POST['updateRecordID'])) {
            unset($data['input_date']);
            $updateRecordID = (integer)$_POST['updateRecordID'];
            
            // Validasi Keamanan: Pustakawan unit tidak boleh mengedit konten unit lain
            if (!$is_super_admin) {
                $check_owner = $dbs->query("SELECT library_id FROM content WHERE content_id = " . $updateRecordID);
                $owner_d = $check_owner->fetch_assoc();
                if ($owner_d && $owner_d['library_id'] != $user_lib_id) {
                    utility::jsToastr('Error', __('Anda tidak memiliki akses untuk mengubah konten dari perpustakaan lain!'), 'error');
                    exit();
                }
            }

            $update = $sql_op->update('content', $data, 'content_id='.$updateRecordID);
            if ($update) {
                writeLog('staff', $_SESSION['uid'], 'system', 'Update content data ('.$data['content_title'].')', 'Content', 'Update');
                utility::jsToastr('Success', __('Content data updated'), 'success');
                echo '<script type="text/javascript">parent.$(\'#mainContent\').simbioAJAX(parent.$.ajaxHistory[0].url);</script>';
            } else { 
                utility::jsToastr('Error', __('Content data FAILED to update!')."\nDEBUG : ".$sql_op->error, 'error'); 
            }
            exit();
        } else {
            if ($sql_op->insert('content', $data)) {
                writeLog('staff', $_SESSION['uid'], 'system', $_SESSION['realname'].' add new content ('.$data['content_title'].')');
                utility::jsToastr('Success', __('Content data saved'), 'success');
                echo '<script type="text/javascript">parent.$(\'#mainContent\').simbioAJAX(\''.$_SERVER['PHP_SELF'].'\');</script>';
            } else {  
                utility::jsToastr('Error', __('Content data FAILED to save!')."\n".$sql_op->error, 'error'); 
            }
            exit();
        }
    }
    exit();
} else if (isset($_POST['itemID']) AND !empty($_POST['itemID']) AND isset($_POST['itemAction'])) {
    if (!($can_read AND $can_write)) {
        die();
    }
    $sql_op = new simbio_dbop($dbs);
    $error_num = 0;
    if (!is_array($_POST['itemID'])) {
        $_POST['itemID'] = array((integer)$_POST['itemID']);
    }
    foreach ($_POST['itemID'] as $itemID) {
        $itemID = (integer)$itemID;
        $content_q = $dbs->query('SELECT content_title, content_desc, library_id FROM content WHERE content_id='.$itemID);
        $content_d = $content_q->fetch_assoc();

        if ($content_d) {
            // Validasi Keamanan: Pustakawan unit tidak boleh menghapus konten unit lain
            if (!$is_super_admin && $content_d['library_id'] != $user_lib_id) {
                $error_num++;
                continue;
            }

            $content_title = $content_d['content_title'];
            $content_desc = $content_d['content_desc'];
            $cleaned_content = stripslashes($content_desc);
            $cleaned_content = html_entity_decode($cleaned_content, ENT_QUOTES, 'UTF-8');
            $regex = '/src=["\'](.*images\/content\/[a-f0-9]+\.(?:png|jpg|jpeg|gif|webp))["\']/i';
            preg_match_all($regex, $cleaned_content, $matches);
            if (isset($matches[1]) && is_array($matches[1])) {
                foreach ($matches[1] as $full_url) {
                    $base_path_segment = '/images/';
                    $pos = strpos($full_url, $base_path_segment);
                    if ($pos !== false) {
                        $relative_path_from_images = substr($full_url, $pos + strlen($base_path_segment));
                        $file_to_delete = IMGBS . $relative_path_from_images;
                        if (file_exists($file_to_delete) && is_file($file_to_delete)) {
                            @unlink($file_to_delete);
                            writeLog('staff', $_SESSION['uid'], 'system', 'DELETE content image file: ' . $relative_path_from_images . ' for content: ' . $content_title);
                        }
                    }
                }
            }

            if (!$sql_op->delete('content', "content_id='$itemID'")) {
                $error_num++;
            } else {
                writeLog('staff', $_SESSION['uid'], 'system', $_SESSION['realname'].' DELETE content ('.$content_title.')','Content', 'Delete');
            }
        }
    }

    if ($error_num == 0) {
        utility::jsToastr('Delete', __('All Data Successfully Deleted'), 'success');
        echo '<script type="text/javascript">parent.$(\'#mainContent\').simbioAJAX(\''.$_SERVER['PHP_SELF'].'?'.($_POST['lastQueryStr']??$_SERVER['QUERY_STRING']).'\');</script>';
    } else {
        utility::jsToastr('Error', __('Some or All Data NOT deleted successfully!\nPlease contact system administrator'), 'error');
        echo '<script type="text/javascript">parent.$(\'#mainContent\').simbioAJAX(\''.$_SERVER['PHP_SELF'].'?'.($_POST['lastQueryStr']??$_SERVER['QUERY_STRING']).'\');</script>';
    }
    exit();
}

/* UI HEADER */
?>
<div class="menuBox">
    <div class="menuBoxInner systemIcon">
        <div class="per_title">
            <h2><?php echo __('Content'); ?></h2>
        </div>
        <div class="sub_section">
            <div class="btn-group mb-3">
                <a href="<?php echo MWB; ?>system/content.php" class="btn btn-default"><?php echo __('Content List'); ?></a>
                <a href="<?php echo MWB; ?>system/content.php?action=detail" class="btn btn-default"><?php echo __('Add New Content'); ?></a>
            </div>
            
            <!-- SEARCH FORM -->
            <form name="search" action="<?php echo MWB; ?>system/content.php" id="search" method="get" class="form-inline mb-3" onsubmit="return false;">
                <?php if ($is_super_admin): ?>
                    <!-- Super Admin dapat memilih perpustakaan mana saja -->
                    <?php echo __('Perpustakaan'); ?> 
                    <select name="library_id" id="libraryFilter" class="form-control col-md-3 mr-2 ml-1" onchange="$('#doSearch').trigger('click')">
                        <option value=""><?= __('Semua Perpustakaan') ?></option>
                        <?php
                        $libs = $dbs->query("SELECT library_id, library_name FROM mst_library ORDER BY library_name");
                        while ($lib = $libs->fetch_assoc()) {
                            $selected = (isset($_GET['library_id']) && $_GET['library_id'] == $lib['library_id']) ? 'selected' : '';
                            echo '<option value="' . $lib['library_id'] . '" ' . $selected . '>' . htmlspecialchars($lib['library_name']) . '</option>';
                        }
                        ?>
                    </select>
                <?php else: ?>
                    <!-- Pustakawan Unit: Hanya menampilkan info nama perpustakaannya (tanpa dropdown pilihan) -->
                    <?php
                    $user_lib_name = 'Perpustakaan Unit';
                    $lib_info = $dbs->query("SELECT library_name FROM mst_library WHERE library_id = " . intval($user_lib_id));
                    if ($lib_info && $lib_d = $lib_info->fetch_assoc()) {
                        $user_lib_name = $lib_d['library_name'];
                    }
                    ?>
                    <input type="hidden" name="library_id" id="libraryFilter" value="<?= $user_lib_id ?>">
                    <span class="badge badge-info p-2 mr-3" style="font-size: 0.9rem;">Unit: <?= htmlspecialchars($user_lib_name) ?></span>
                <?php endif; ?>

                <?php echo __('Search'); ?> 
                <input type="text" name="keywords" id="keywords" value="<?php echo isset($_GET['keywords']) ? htmlspecialchars($_GET['keywords']) : ''; ?>" class="form-control col-md-3 mr-2 ml-1" />
                <input type="button" id="doSearch" value="<?php echo __('Search'); ?>" class="btn btn-default" />
            </form>

            <script type="text/javascript">
            $(document).ready(function() {
                $('#doSearch').on('click', function() {
                    var libId = $('#libraryFilter').val();
                    var kw = $('#keywords').val();
                    var url = '<?php echo MWB; ?>system/content.php?library_id=' + encodeURIComponent(libId) + '&keywords=' + encodeURIComponent(kw);
                    $('#mainContent').simbioAJAX(url);
                });

                $('#keywords').on('keypress', function(e) {
                    if (e.which == 13) {
                        e.preventDefault();
                        $('#doSearch').trigger('click');
                    }
                });
            });
            </script>

<?php
/* MAIN CONTENT ROUTING */
if (isset($_POST['detail']) OR (isset($_GET['action']) AND $_GET['action'] == 'detail')) {
    if (!($can_read AND $can_write)) {
        die('<div class="errorBox">'.__('You don\'t have enough privileges to view this section').'</div>');
    }
    
    $itemID = (integer)(isset($_POST['itemID']) ? $_POST['itemID'] : 0);
    $rec_q = $dbs->query('SELECT * FROM content WHERE content_id='.$itemID);
    $rec_d = $rec_q->fetch_assoc();

    // Validasi Keamanan saat buka form Edit: Cegah edit konten unit lain
    if ($rec_d && !$is_super_admin && $rec_d['library_id'] != $user_lib_id) {
        die('<div class="alert alert-danger">'.__('Anda tidak memiliki izin untuk mengedit konten milik unit perpustakaan lain.').'</div>');
    }

    $editor_content = $rec_d['content_desc'] ?? '';
    if (!empty($editor_content)) {
        $editor_content = stripslashes($editor_content);
        $editor_content = html_entity_decode($editor_content, ENT_QUOTES, 'UTF-8');
    }
    ?>
    <form class="d-flex px-3" id="contentForm" method="POST" action="<?= $_SERVER['PHP_SELF'] ?>" target="submitExec">
        <?php if ($rec_q && $rec_q->num_rows > 0): ?>
            <input type="hidden" name="updateRecordID" value="<?= $rec_d['content_id']??0 ?>"/>
        <?php endif; ?>
        
        <div id="editor" class="col-8">
            <div id="titleContent" class="my-3">
                <label class="font-weight-bold"><?= __('Content Title') ?>*</label>
                <input id="setPath" type="text" name="contentTitle" value="<?= $rec_d['content_title']??'' ?>" class="form-control"/>
            </div>
            <div id="toolbarContainer"></div>
            <div id="outerContent" style="background-color: #e1e1e1; padding: 30px">
                <div id="contentDesc" class="rounded-lg px-5" style="background-color: white; min-height: 800px"><?= $editor_content ?></div>
            </div>
        </div>
        <div id="detail" class="col-4">
            <fieldset>
                <div class="d-flex justify-content-between">
                    <label><?= __('Content Settings') ?></label>
                    <button type="submit" name="saveData" class="btn btn-primary"><?= ($rec_q && $rec_q->num_rows > 0) ? __("Update") : __("Save") ?></button>
                </div>
                <hr>
                <label class="m-0 font-weight-bold"><?= __('Publish at') ?></label>
                <input type="date" name="publishDate" class="form-control" value="<?= $rec_d['publish_date']??''?>"/>
                
                <label class="m-0 font-weight-bold mt-2"><?= __('This is News') ?>*</label>
                <?= simbio_form_element::selectList('isNews', [[1, __('Yes')],[0,__('No')]], $rec_d['is_news']??'', 'class="form-control"') . '&nbsp;'; ?>
                
                <label class="m-0 font-weight-bold"><?= __('Path (Must be unique)') ?>*</label>
                <input type="text" name="contentPath" value="<?= $rec_d['content_path']??'' ?>" id="path" class="form-control"/>
                <small id="warningChar" class="text-danger d-none"><?= __('Max 20 character') ?></small>
                
                <label class="m-0 font-weight-bold mt-2"><?= __('Draft?') ?>*</label><br>
                <?= simbio_form_element::selectList('isDraft', [[0, __('No')],[1,__('Yes')]], $rec_d['is_draft']??'', 'class="form-control"') . '&nbsp;'; ?>
                
                <label class="m-0 font-weight-bold mt-3"><?= __('Perpustakaan') ?>*</label>
                <?php if ($is_super_admin): ?>
                    <!-- Super Admin bebas memilih unit -->
                    <select name="library_id" class="form-control">
                        <option value="1" <?= ($rec_d['library_id'] ?? 1) == 1 ? 'selected' : '' ?>>
                            <?= __('Perpustakaan Pusat') ?>
                        </option>
                        <?php
                        $libs = $dbs->query("SELECT library_id, library_name FROM mst_library ORDER BY library_name");
                        while ($lib = $libs->fetch_assoc()) {
                            $selected = ($rec_d['library_id'] ?? 0) == $lib['library_id'] ? 'selected' : '';
                            echo '<option value="' . $lib['library_id'] . '" ' . $selected . '>' . htmlspecialchars($lib['library_name']) . '</option>';
                        }
                        ?>
                    </select>
                <?php else: ?>
                    <!-- Pustakawan Unit: Terkunci pada unitnya sendiri -->
                    <?php
                    $unit_id = $rec_d['library_id'] ?? $user_lib_id;
                    $lib_q = $dbs->query("SELECT library_name FROM mst_library WHERE library_id = " . intval($unit_id));
                    $lib_d = $lib_q->fetch_assoc();
                    $unit_name = $lib_d['library_name'] ?? 'Unit Anda';
                    ?>
                    <input type="hidden" name="library_id" value="<?= $unit_id ?>">
                    <input type="text" class="form-control" value="<?= htmlspecialchars($unit_name) ?>" disabled readonly>
                <?php endif; ?>
                <small class="text-muted"><?= __('Konten akan ditampilkan di perpustakaan ini') ?></small>
            </fieldset>
        </div>
    </form>
    <iframe name="submitExec" class="d-none"></iframe>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#setPath').on('keyup', function(){
                let text = $(this).val().replace(/[^a-zA-Z0-9]/g, '-');
                let path = $('#path');
                if (text.length <= 20) {
                    path.val(text.toLowerCase());
                }
            });

            $('#path').keyup(function(e){
                $(this).removeClass('border border-danger');
                $('#warningChar').removeClass('d-block');
                $(this).removeAttr('maxlength');

                try {
                    if ($(this).val().length > 20) throw "Stop";
                    let filter = $(this).val().replace(/[^a-zA-Z0-9]/g, '-');
                    $(this).val(filter.toLowerCase());
                } catch (error) {
                    $(this).addClass('border border-danger');
                    $(this).attr('maxlength', '20');
                    $('#warningChar').addClass('d-block');
                }
            });

            let editorInstance = '';
            DecoupledEditor
                .create(document.querySelector('#contentDesc'),{   
                    toolbar: {shouldNotGroupWhenFull: true},
                    ckfinder: {uploadUrl: '<?php echo $_SERVER['PHP_SELF'];?>'}
                })
                .then( editor => {
                    const toolbarContainer = document.querySelector('#toolbarContainer');
                    toolbarContainer.appendChild( editor.ui.view.toolbar.element );
                    editorInstance = editor;
                    const contentElement = editor.ui.view.editable.element;
                    let initialImageUrls = [];
                    contentElement.querySelectorAll('img').forEach(img => {
                        initialImageUrls.push(img.getAttribute('src'));
                    });
                    
                    const observer = new MutationObserver((mutationsList, observer) => {
                        for (const mutation of mutationsList) {
                            if (mutation.type === 'childList') {
                                mutation.removedNodes.forEach(removedNode => {
                                    const imgElement = removedNode.tagName === 'IMG' ? removedNode : removedNode.querySelector('img');
                                    if (imgElement) {
                                        const removedImageUrl = imgElement.getAttribute('src');
                                        if (initialImageUrls.includes(removedImageUrl)) {
                                            initialImageUrls = initialImageUrls.filter(url => url !== removedImageUrl);
                                            $.ajax({
                                                url: '<?php echo $_SERVER['PHP_SELF'];?>',
                                                type: 'POST',
                                                dataType: 'json',
                                                data: {
                                                    action: 'deleteImage',
                                                    imageURL: removedImageUrl
                                                },
                                                success: function(response) {
                                                    if (response.status === 'success') {
                                                        toastr.success('<?= __('Image file successfully deleted:')?>', 'Content', {timeOut: 5000});
                                                    } else {
                                                        toastr.error('<?= __('Failed to delete file:')?>' + response.message, 'Content', {timeOut: 5000});
                                                    }
                                                },
                                                error: function(xhr) {
                                                    toastr.error('<?= __('Failed to delete file:')?>', 'Content', {timeOut: 5000});
                                                }
                                            });
                                        }
                                    }
                                });
                            }
                        }
                    });
                    observer.observe(contentElement, { childList: true, subtree: true });
                })
                .catch( error => {
                    console.log(error);
                });

            $('#contentForm').submit(function(){
                $(this).append('<textarea name="contentDesc" class="d-none">' + editorInstance.getData() + '</textarea>');
            });
        });
    </script>
    <?php
} else {
    /* DATAGRID CONTENT LIST */
    $table_spec = 'content AS c';
    $datagrid = new simbio_datagrid();

    if ($can_read AND $can_write) {
        $datagrid->setSQLColumn('c.content_id',
            'c.content_title AS \''.__('Content Title').'\'',
            'c.content_path AS \''.__('Path (Must be unique)').'\'',
            'c.last_update AS \''.__('Last Updated').'\'',
            '(SELECT library_name FROM mst_library WHERE library_id = c.library_id) AS \''.__('Perpustakaan').'\'');
    } else {
        $datagrid->setSQLColumn('c.content_title AS \''.__('Content Title').'\'',
            'c.content_path AS \''.__('Path (Must be unique)').'\'',
            'c.last_update AS \''.__('Last Updated').'\'',
            '(SELECT library_name FROM mst_library WHERE library_id = c.library_id) AS \''.__('Perpustakaan').'\'');
    }
    $datagrid->setSQLorder('c.last_update DESC');

    $criteria = 'c.content_id IS NOT NULL ';
    
    // PUSTAKAWAN UNIT: Hanya tampilkan data unitnya sendiri
    if (!$is_super_admin) {
        $criteria .= " AND c.library_id = " . intval($user_lib_id);
    } else {
        if (isset($_GET['library_id']) && $_GET['library_id'] !== '') {
            $criteria .= " AND c.library_id = " . intval($_GET['library_id']);
        }
    }
    
    if (isset($_GET['keywords']) AND $_GET['keywords']) {
       $keywords = utility::filterData('keywords', 'get', true, true, true);
       $criteria .= " AND MATCH(content_title, content_desc) AGAINST('{$dbs->escape_string($keywords)}')";
    }
    $datagrid->setSQLCriteria($criteria);

    $datagrid->table_attr = 'id="dataList" class="s-table table"';
    $datagrid->table_header_attr = 'class="dataListHeader" style="font-weight: bold;"';
    $datagrid->chbox_form_URL = $_SERVER['PHP_SELF'];

    $datagrid_result = $datagrid->createDataGrid($dbs, $table_spec, 20, ($can_read AND $can_write));

    if ($datagrid->num_rows == 0) {
        $library_name = '';
        $target_lib_id = !$is_super_admin ? $user_lib_id : ($_GET['library_id'] ?? '');
        
        if (!empty($target_lib_id)) {
            $lib_q = $dbs->query("SELECT library_name FROM mst_library WHERE library_id = " . intval($target_lib_id));
            $lib_d = $lib_q->fetch_assoc();
            $library_name = $lib_d['library_name'] ?? '';
        }
        
        if (!empty($library_name)) {
            echo '<div class="alert alert-info text-center" style="padding: 30px; margin: 20px 0;">';
            echo '<i class="fa-solid fa-circle-info" style="font-size: 2rem; display: block; margin-bottom: 10px;"></i>';
            echo '<h4>' . __('No Content on This Library') . '</h4>';
            echo '<p>' . sprintf(__('There is no content available for <strong>%s</strong> yet. Please add content from the "Add New Content" button.'), htmlspecialchars($library_name)) . '</p>';
            echo '<a href="' . MWB . 'system/content.php?action=detail" class="btn btn-primary">' . __('Add New Content') . '</a>';
            echo '</div>';
        } else {
            echo '<div class="alert alert-info text-center" style="padding: 30px; margin: 20px 0;">';
            echo '<i class="fa-solid fa-circle-info" style="font-size: 2rem; display: block; margin-bottom: 10px;"></i>';
            echo '<h4>' . __('No Content Available') . '</h4>';
            echo '<p>' . __('There is no content available yet. Please add content from the "Add New Content" button.') . '</p>';
            echo '<a href="' . MWB . 'system/content.php?action=detail" class="btn btn-primary">' . __('Add New Content') . '</a>';
            echo '</div>';
        }
    } else {
        if (isset($_GET['keywords']) AND $_GET['keywords']) {
            $msg = str_replace('{result->num_rows}', $datagrid->num_rows, __('Found <strong>{result->num_rows}</strong> from your keywords'));
            echo '<div class="infoBox">'.$msg.' : "'.htmlspecialchars($_GET['keywords']).'"</div>';
        }
        echo $datagrid_result;
    }
}
?>
        </div> <!-- sub_section -->
    </div> <!-- menuBoxInner -->
</div> <!-- menuBox -->