<?php
/**
 * Manajemen Perpustakaan (CRUD mst_library)
 * Untuk Superadmin
 *
 * Copyright (C) 2025  SLiMS Multi-Library
 */

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

// main system configuration
require '../../../sysconfig.inc.php';
// IP based access limitation
require LIB . 'ip_based_access.inc.php';
do_checkIP('smc');
do_checkIP('smc-masterfile');

// start the session
require SB . 'admin/default/session.inc.php';
require SB . 'admin/default/session_check.inc.php';

// wajibkan library
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_DB/simbio_dbop.inc.php';

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

// HANYA SUPERADMIN YANG BOLEH AKSES
if (!isset($_SESSION['uid']) || $_SESSION['uid'] != 1) {
    die('<div class="errorBox">' . __('Access Denied! Hanya Superadmin yang dapat mengakses modul ini.') . '</div>');
}

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

/* ============================================================
    RECORD OPERATION (SAVE / DELETE)
   ============================================================ */

// SAVE (INSERT or UPDATE)
if (isset($_POST['saveData']) && $can_read && $can_write) {
    $library_code = trim(strip_tags($_POST['library_code']));
    $library_name = trim(strip_tags($_POST['library_name']));
    $address = trim(strip_tags($_POST['address'] ?? ''));
    $phone = trim(strip_tags($_POST['phone'] ?? ''));
    $email = trim(strip_tags($_POST['email'] ?? ''));
    $head_name = trim(strip_tags($_POST['head_name'] ?? ''));
    $head_nip = trim(strip_tags($_POST['head_nip'] ?? ''));
    $head_phone = trim(strip_tags($_POST['head_phone'] ?? ''));
    $head_email = trim(strip_tags($_POST['head_email'] ?? ''));
    $opac_color = trim(strip_tags($_POST['opac_color'] ?? '#004db6'));
    
    // Ambil nilai is_active dari form radio button
    $is_active = (isset($_POST['is_active']) && $_POST['is_active'] === 'yes') ? 1 : 0;
    
    // Validasi
    if (empty($library_code)) {
        utility::jsToastr(__('Library'), __('Library Code can\'t be empty'), 'error');
        exit();
    }
    if (empty($library_name)) {
        utility::jsToastr(__('Library'), __('Library Name can\'t be empty'), 'error');
        exit();
    }
    
    // Cek duplikat library_code (KECUALI untuk update record yang sama)
    $edit_id = isset($_POST['updateRecordID']) ? (int)$_POST['updateRecordID'] : 0;
    
    // Query cek duplikat
    $dup_check = "SELECT library_id FROM mst_library WHERE library_code = '" . $dbs->escape_string($library_code) . "'";
    if ($edit_id > 0) {
        $dup_check .= " AND library_id != " . $edit_id;
    }
    $dup_result = $dbs->query($dup_check);
    if ($dup_result && $dup_result->num_rows > 0) {
        utility::jsToastr(__('Library'), __('Library Code "' . $library_code . '" already exists'), 'error');
        exit();
    }
    
    // Prepare data
    $data = array(
        'library_code' => $dbs->escape_string($library_code),
        'library_name' => $dbs->escape_string($library_name),
        'address' => $dbs->escape_string($address),
        'phone' => $dbs->escape_string($phone),
        'email' => $dbs->escape_string($email),
        'head_name' => $dbs->escape_string($head_name),
        'head_nip' => $dbs->escape_string($head_nip),
        'head_phone' => $dbs->escape_string($head_phone),
        'head_email' => $dbs->escape_string($head_email),
        'opac_color' => $dbs->escape_string($opac_color),
        'is_active' => $is_active,
        'last_update' => date('Y-m-d H:i:s')
    );
    
    // create sql op object
    $sql_op = new simbio_dbop($dbs);
    
    if ($edit_id > 0) {
        // UPDATE RECORD MODE
        unset($data['input_date']); // remove input_date for update
        
        $update = $sql_op->update('mst_library', $data, 'library_id=' . $edit_id);
        if ($update) {
            utility::jsToastr(__('Library'), __('Library Data Successfully Updated'), 'success');
            echo '<script type="text/javascript">parent.jQuery(\'#mainContent\').simbioAJAX(parent.jQuery.ajaxHistory[0].url);</script>';
        } else {
            utility::jsToastr(__('Library'), __('Library Data FAILED to Updated. Please Contact System Administrator') . "\nDEBUG : " . $sql_op->error, 'error');
        }
        exit();
    } else {
        // INSERT RECORD MODE
        $data['input_date'] = date('Y-m-d H:i:s');
        
        $insert = $sql_op->insert('mst_library', $data);
        if ($insert) {
            utility::jsToastr(__('Library'), __('New Library Data Successfully Saved'), 'success');
            echo '<script type="text/javascript">parent.jQuery(\'#mainContent\').simbioAJAX(\'' . $_SERVER['PHP_SELF'] . '\');</script>';
        } else {
            utility::jsToastr(__('Library'), __('Library Data FAILED to Save. Please Contact System Administrator') . "\nDEBUG : " . $sql_op->error, 'error');
        }
        exit();
    }
    exit();
}

// DELETE
if (isset($_POST['itemID']) && !empty($_POST['itemID']) && isset($_POST['itemAction'])) {
    if (!($can_read && $can_write)) {
        die();
    }
    
    $sql_op = new simbio_dbop($dbs);
    $error_num = 0;
    $still_have_data = array();
    
    if (!is_array($_POST['itemID'])) {
        $_POST['itemID'] = array((integer)$_POST['itemID']);
    }
    
    foreach ($_POST['itemID'] as $itemID) {
        $itemID = (integer)$itemID;
        $delete = true;
        $used_in = array();
        
        // Cek apakah library_id digunakan di tabel lain
        $check_tables = array('biblio', 'item', 'member', 'user', 'loan', 'fines', 'reserve');
        foreach ($check_tables as $table) {
            $check_query = "SELECT COUNT(*) as total FROM `$table` WHERE library_id = $itemID";
            $check_result = $dbs->query($check_query);
            if ($check_result && $row = $check_result->fetch_assoc()) {
                if ($row['total'] > 0) {
                    $delete = false;
                    $used_in[] = $table . ' (' . $row['total'] . ' data)';
                }
            }
        }
        
        if ($delete) {
            if (!$sql_op->delete('mst_library', 'library_id=' . $itemID)) {
                $error_num++;
            }
        } else {
            $lib_query = "SELECT library_name FROM mst_library WHERE library_id = $itemID";
            $lib_result = $dbs->query($lib_query);
            $lib_data = $lib_result->fetch_assoc();
            $still_have_data[] = sprintf(
                __('%s still has data in: %s <br/>'),
                substr($lib_data['library_name'] ?? 'ID:' . $itemID, 0, 45),
                implode(', ', $used_in)
            );
            $error_num++;
        }
    }
    
    if ($still_have_data) {
        $titles = '';
        foreach ($still_have_data as $title) {
            $titles .= $title . "\n";
        }
        utility::jsToastr(__('Library'), __('Below data can not be deleted:') . "\n" . $titles, 'error');
        echo '<script type="text/javascript">parent.jQuery(\'#mainContent\').simbioAJAX(\'' . $_SERVER['PHP_SELF'] . '\', {addData: \'' . $_POST['lastQueryStr'] . '\'});</script>';
        exit();
    }
    
    if ($error_num == 0) {
        utility::jsToastr(__('Library'), __('All Data Successfully Deleted'), 'success');
        echo '<script type="text/javascript">parent.jQuery(\'#mainContent\').simbioAJAX(\'' . $_SERVER['PHP_SELF'] . '?' . $_POST['lastQueryStr'] . '\');</script>';
    } else {
        utility::jsToastr(__('Library'), __('Some or All Data NOT deleted successfully!\nPlease contact system administrator'), 'warning');
        echo '<script type="text/javascript">parent.jQuery(\'#mainContent\').simbioAJAX(\'' . $_SERVER['PHP_SELF'] . '?' . $_POST['lastQueryStr'] . '\');</script>';
    }
    exit();
}

/* ============================================================
    TAMPILAN UTAMA & ATAS
   ============================================================ */
?>
<div class="menuBox">
    <div class="menuBoxInner masterFileIcon">
        <div class="per_title">
            <h2><?php echo __('Library Management'); ?></h2>
        </div>
        <div class="sub_section">
            <div class="btn-group">
                <a href="<?php echo MWB; ?>master_file/library.php" class="btn btn-default"><?php echo __('Library List'); ?></a>
                <a href="<?php echo MWB; ?>master_file/library.php?action=detail" class="btn btn-default"><?php echo __('Add New Library'); ?></a>
            </div>
            <form name="search" action="<?php echo MWB; ?>master_file/library.php" id="search" method="get" class="form-inline">
                <?php echo __('Search'); ?>
                <input type="text" name="keywords" class="form-control col-md-3" />
                <input type="submit" id="doSearch" value="<?php echo __('Search'); ?>" class="s-btn btn btn-default" />
            </form>
        </div>
    </div>
</div>
<?php

/* ============================================================
    ADOP CARA CUSTOM: FORM TAMBAH / EDIT DENGAN PURE HTML
   ============================================================ */
if (isset($_POST['detail']) || (isset($_GET['action']) && $_GET['action'] == 'detail')) {
    if (!($can_read && $can_write)) {
        die('<div class="errorBox">' . __('You don\'t have enough privileges to access this area!') . '</div>');
    }
    
    $itemID = isset($_POST['itemID']) ? (int)$_POST['itemID'] : 0;
    $rec_q = $dbs->query('SELECT * FROM mst_library WHERE library_id = ' . $itemID);
    $rec_d = $rec_q->fetch_assoc();
    
    $is_edit = ($rec_q->num_rows > 0);
    
    if ($is_edit) {
        echo '<div class="infoBox">' . __('You are going to edit library data') . ' : <b>' . htmlspecialchars($rec_d['library_name']) . '</b>  <br />' . __('Last Update') . ' ' . $rec_d['last_update'] . '</div>';
    }
    
    // Mulai render HTML Form Mandiri ala SLiMS grid agar tetap sejajar dan konsisten dengan halaman SLiMS
    ?>
    <form id="mainForm" method="post" action="<?php echo $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING']; ?>" class="form-horizontal">
        <?php if ($is_edit): ?>
            <input type="hidden" name="updateRecordID" value="<?php echo $itemID; ?>">
        <?php endif; ?>
        
        <table id="dataList" class="s-table table table-striped">
            <tbody>
                <!-- Library Code -->
                <tr>
                    <td class="alterCell font-weight-bold" style="width: 25%; vertical-align: middle;"><?php echo __('Library Code'); ?>*</td>
                    <td class="alterCell2">
                        <input type="text" name="library_code" value="<?php echo htmlspecialchars($rec_d['library_code'] ?? ''); ?>" style="width: 60%; text-transform:uppercase;" class="form-control" required>
                    </td>
                </tr>
                <!-- Library Name -->
                <tr>
                    <td class="alterCell font-weight-bold" style="vertical-align: middle;"><?php echo __('Library Name'); ?>*</td>
                    <td class="alterCell2">
                        <input type="text" name="library_name" value="<?php echo htmlspecialchars($rec_d['library_name'] ?? ''); ?>" style="width: 60%;" class="form-control" required>
                    </td>
                </tr>
                <!-- Address -->
                <tr>
                    <td class="alterCell font-weight-bold" style="vertical-align: middle;"><?php echo __('Address'); ?></td>
                    <td class="alterCell2">
                        <textarea name="address" style="width: 60%; height:60px;" class="form-control"><?php echo htmlspecialchars($rec_d['address'] ?? ''); ?></textarea>
                    </td>
                </tr>
                <!-- Phone -->
                <tr>
                    <td class="alterCell font-weight-bold" style="vertical-align: middle;"><?php echo __('Phone'); ?></td>
                    <td class="alterCell2">
                        <input type="text" name="phone" value="<?php echo htmlspecialchars($rec_d['phone'] ?? ''); ?>" style="width: 60%;" class="form-control">
                    </td>
                </tr>
                <!-- Email -->
                <tr>
                    <td class="alterCell font-weight-bold" style="vertical-align: middle;"><?php echo __('Email'); ?></td>
                    <td class="alterCell2">
                        <input type="email" name="email" value="<?php echo htmlspecialchars($rec_d['email'] ?? ''); ?>" style="width: 60%;" class="form-control">
                    </td>
                </tr>
                <!-- Head Name -->
                <tr>
                    <td class="alterCell font-weight-bold" style="vertical-align: middle;"><?php echo __('Head Name'); ?></td>
                    <td class="alterCell2">
                        <input type="text" name="head_name" value="<?php echo htmlspecialchars($rec_d['head_name'] ?? ''); ?>" style="width: 60%;" class="form-control">
                    </td>
                </tr>
                <!-- Head NIP -->
                <tr>
                    <td class="alterCell font-weight-bold" style="vertical-align: middle;"><?php echo __('Head NIP/NIDN'); ?></td>
                    <td class="alterCell2">
                        <input type="text" name="head_nip" value="<?php echo htmlspecialchars($rec_d['head_nip'] ?? ''); ?>" style="width: 60%;" class="form-control">
                    </td>
                </tr>
                <!-- Head Phone -->
                <tr>
                    <td class="alterCell font-weight-bold" style="vertical-align: middle;"><?php echo __('Head Phone'); ?></td>
                    <td class="alterCell2">
                        <input type="text" name="head_phone" value="<?php echo htmlspecialchars($rec_d['head_phone'] ?? ''); ?>" style="width: 60%;" class="form-control">
                    </td>
                </tr>
                <!-- Head Email -->
                <tr>
                    <td class="alterCell font-weight-bold" style="vertical-align: middle;"><?php echo __('Head Email'); ?></td>
                    <td class="alterCell2">
                        <input type="email" name="head_email" value="<?php echo htmlspecialchars($rec_d['head_email'] ?? ''); ?>" style="width: 60%;" class="form-control">
                    </td>
                </tr>
                <!-- OPAC Color (ADOP CARA PURE HTML KUSTOM) -->
                <tr>
                    <td class="alterCell font-weight-bold" style="vertical-align: middle;"><?php echo __('OPAC Color'); ?></td>
                    <td class="alterCell2">
                        <input type="color" name="opac_color" class="form-control" value="<?php echo htmlspecialchars($rec_d['opac_color'] ?? '#004db6'); ?>" style="width: 60px; height: 40px; padding: 0; cursor: pointer;">
                        <small class="help-block" style="color: #666; margin-top: 5px; display: block;">Pilih warna tema header untuk halaman OPAC perpustakaan cabang ini.</small>
                    </td>
                </tr>
                <!-- Status -->
                <tr>
                    <td class="alterCell font-weight-bold" style="vertical-align: middle;"><?php echo __('Status'); ?></td>
                    <td class="alterCell2">
                        <?php 
                        $status_active = (!isset($rec_d['is_active']) || $rec_d['is_active'] == 1);
                        ?>
                        <label style="font-weight: normal; margin-right: 15px; cursor: pointer;">
                            <input type="radio" name="is_active" value="yes" <?php echo $status_active ? 'checked' : ''; ?>> <?php echo __('Active'); ?>
                        </label>
                        <label style="font-weight: normal; cursor: pointer;">
                            <input type="radio" name="is_active" value="no" <?php echo !$status_active ? 'checked' : ''; ?>> <?php echo __('Inactive'); ?>
                        </label>
                    </td>
                </tr>
                <!-- Tombol Submit Form -->
                <tr>
                    <td class="alterCell"></td>
                    <td class="alterCell2">
                        <input type="submit" name="saveData" value="<?php echo $is_edit ? __('Update') : __('Save'); ?>" class="s-btn btn <?php echo $is_edit ? 'btn-primary' : 'btn-default'; ?>">
                        <a href="<?php echo MWB; ?>master_file/library.php" class="btn btn-default" style="margin-left: 5px;"><?php echo __('Cancel'); ?></a>
                    </td>
                </tr>
            </tbody>
        </table>
    </form>
    
    <!-- Ikat Form dengan Handler AJAX SLiMS agar Submit tetap Asynchronous lancar -->
    <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('#mainForm').on('submit', function(e) {
                e.preventDefault();
                var formAction = $(this).attr('action');
                var formData = $(this).serialize() + '&saveData=true';
                $('#mainContent').simbioAJAX(formAction, { method: 'post', addData: formData });
            });
        });
    </script>
    <?php
    
} else {
    /* ============================================================
        LIST DATA (TETAP PAKAI DATAGRID SLiMS YANG SUDAH OKE)
       ============================================================ */
    
    $sql_criteria = '1=1';
    $table_spec = 'mst_library';
    
    // create datagrid
    $datagrid = new simbio_datagrid();
    if ($can_read && $can_write) {
        $datagrid->setSQLColumn(
            'library_id',
            'library_code AS \'' . __('Code') . '\'',
            'library_name AS \'' . __('Library Name') . '\'',
            'head_name AS \'' . __('Head') . '\'',
            'opac_color AS \'' . __('Color') . '\'',
            'is_active AS \'' . __('Status') . '\'',
            'last_update AS \'' . __('Last Update') . '\''
        );
    } else {
        $datagrid->setSQLColumn(
            'library_code AS \'' . __('Code') . '\'',
            'library_name AS \'' . __('Library Name') . '\'',
            'head_name AS \'' . __('Head') . '\'',
            'last_update AS \'' . __('Last Update') . '\''
        );
    }
    $datagrid->setSQLorder('library_id ASC');
    
    // is there any search
    if (isset($_GET['keywords']) && $_GET['keywords']) {
        $keywords = utility::filterData('keywords', 'get', true, true, true);
        $sql_criteria .= " AND (library_code LIKE '%$keywords%' OR library_name LIKE '%$keywords%' OR head_name LIKE '%$keywords%')";
    }
    
    $datagrid->setSQLCriteria($sql_criteria);
    
    // set table and table header attributes
    $datagrid->table_attr = 'id="dataList" class="s-table table"';
    $datagrid->table_header_attr = 'class="dataListHeader" style="font-weight: bold;"';
    // set delete process URL
    $datagrid->chbox_form_URL = trim($_SERVER['PHP_SELF']);
    
    // Custom column untuk menampilkan warna dan status
    $datagrid->custom_column = array(
        4 => '<span style="display:inline-block;width:30px;height:20px;background:{opac_color};border:1px solid #ccc;border-radius:3px;vertical-align:middle;margin-right:5px;"></span> {opac_color}',
        5 => '{if:is_active==1}<span class="label label-success">Active</span>{else}<span class="label label-danger">Inactive</span>{/if}'
    );
    
    // put the result into variable
    $datagrid_result = $datagrid->createDataGrid($dbs, $table_spec, 20, ($can_read && $can_write));
    
    if (isset($_GET['keywords']) && $_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;
}
?>