<?php
$page_title = 'Manajemen Aset & Inventaris';
require_once('includes/load.php');
page_require_level(4);

$db = MySqli_DB::getInstance();

// --- Paginasi, Pencarian, dan Filter ---
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 25;
$search_term = isset($_GET['search']) ? $db->escape($_GET['search']) : '';
$category_id = isset($_GET['category']) ? (int)$_GET['category'] : 0;
$employee_id = isset($_GET['employee']) ? (int)$_GET['employee'] : 0;
$condition_filter = isset($_GET['condition']) ? $db->escape($_GET['condition']) : '';

// Query untuk menghitung total baris
$sql_count = "SELECT COUNT(*) AS total FROM assets AS a";
$where_clauses = [];

if (!empty($search_term)) {
    $where_clauses[] = " (a.asset_name LIKE '%{$search_term}%' OR a.serial_number LIKE '%{$search_term}%') ";
}
if ($category_id > 0) {
    $where_clauses[] = " a.category_id = '{$category_id}' ";
}
if ($employee_id > 0) {
    $where_clauses[] = " a.employee_id = '{$employee_id}' ";
}
if (!empty($condition_filter)) {
    $where_clauses[] = " a.condition = '{$condition_filter}' ";
}

if (!empty($where_clauses)) {
    $sql_count .= " WHERE " . implode(' AND ', $where_clauses);
}

$result_count = $db->query($sql_count);
$total_assets_filtered = $db->fetch_assoc($result_count)['total'];
$total_pages = ceil($total_assets_filtered / $per_page);
$start = ($page - 1) * $per_page;

// Query utama untuk menampilkan data
$sql = "SELECT 
            a.id, 
            a.asset_name, 
            c.category_name, 
            a.serial_number, 
            a.purchase_date, 
            a.condition, 
            a.location,
            CONCAT(e.first_name, ' ', e.last_name) AS employee_name
        FROM assets AS a
        LEFT JOIN assets_categories AS c ON a.category_id = c.id
        LEFT JOIN employees AS e ON a.employee_id = e.id";

if (!empty($where_clauses)) {
    $sql .= " WHERE " . implode(' AND ', $where_clauses);
}
$sql .= " ORDER BY a.asset_name ASC LIMIT {$per_page} OFFSET {$start}";
$assets = find_by_sql($sql);

// Ambil data untuk dropdown filter
$categories = find_by_sql("SELECT * FROM assets_categories ORDER BY category_name ASC");
$employees_list = find_by_sql("SELECT id, CONCAT(first_name, ' ', last_name) AS full_name FROM employees ORDER BY first_name ASC");

?>

<?php include_once('layouts/header.php'); ?>

<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading clearfix">
                <strong>
                    <span class="glyphicon glyphicon-th"></span>
                    <span>Daftar Aset & Inventaris</span>
                </strong>
                <a href="add_asset.php" class="btn btn-info pull-right">Tambah Aset Baru</a>
                <a href="assets_categories.php" class="btn btn-info pull-right" style="margin-right: 5px;">Kelola Kategori</a>
            </div>
            <div class="panel-body">
                <form action="" method="GET" class="form-horizontal mb-4">
                    <div class="form-group clearfix">
                        <div class="col-md-3">
                            <input type="text" name="search" class="form-control" placeholder="Cari aset atau serial..." value="<?php echo htmlspecialchars($search_term); ?>">
                        </div>
                        <div class="col-md-3">
                            <select name="category" class="form-control">
                                <option value="0">Semua Kategori</option>
                                <?php foreach ($categories as $cat) : ?>
                                    <option value="<?php echo (int)$cat['id']; ?>" <?php if ($category_id == $cat['id']) echo 'selected'; ?>>
                                        <?php echo remove_junk($cat['category_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select name="employee" class="form-control">
                                <option value="0">Semua Karyawan</option>
                                <?php foreach ($employees_list as $emp) : ?>
                                    <option value="<?php echo (int)$emp['id']; ?>" <?php if ($employee_id == $emp['id']) echo 'selected'; ?>>
                                        <?php echo remove_junk($emp['full_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select name="condition" class="form-control">
                                <option value="">Semua Kondisi</option>
                                <option value="Baik" <?php if ($condition_filter == 'Baik') echo 'selected'; ?>>Baik</option>
                                <option value="Rusak" <?php if ($condition_filter == 'Rusak') echo 'selected'; ?>>Rusak</option>
                                <option value="Perbaikan" <?php if ($condition_filter == 'Perbaikan') echo 'selected'; ?>>Perbaikan</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group clearfix">
                         <div class="col-md-12 text-right">
                             <button type="submit" class="btn btn-primary">Filter</button>
                             <a href="asset_management.php" class="btn btn-default">Reset</a>
                         </div>
                    </div>
                </form>

                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th class="text-center" style="width: 50px;">#</th>
                                <th>Nama Aset</th>
                                <th class="text-center">Nomor Seri</th>
                                <th class="text-center">Kategori</th>
                                <th class="text-center">Penanggung Jawab</th>
                                <th class="text-center">Kondisi</th>
                                <th class="text-center">Tanggal Beli</th>
                                <th class="text-center" style="width: 120px;">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($assets)): ?>
                                <?php $i = $start + 1; ?>
                                <?php foreach ($assets as $asset) : ?>
                                    <tr>
                                        <td class="text-center"><?php echo (int)$i++; ?></td>
                                        <td><?php echo remove_junk($asset['asset_name']); ?></td>
                                        <td class="text-center"><?php echo remove_junk($asset['serial_number']); ?></td>
                                        <td class="text-center"><?php echo remove_junk($asset['category_name']); ?></td>
                                        <td class="text-center"><?php echo remove_junk($asset['employee_name']); ?></td>
                                        <td class="text-center"><?php echo remove_junk($asset['condition']); ?></td>
                                        <td class="text-center"><?php echo htmlspecialchars($asset['purchase_date']); ?></td>
                                        <td class="text-center">
                                            <div class="btn-group">
                                                <a href="edit_asset.php?id=<?php echo (int)$asset['id'];?>" class="btn btn-xs btn-warning" title="Edit" data-toggle="tooltip">
                                                    <i class="glyphicon glyphicon-pencil"></i>
                                                </a>
                                                <a href="print_barcode_asset.php?id=<?php echo (int)$asset['id'];?>" class="btn btn-xs btn-info" title="Cetak Barcode" data-toggle="tooltip">
                                                    <i class="glyphicon glyphicon-barcode"></i>
                                                </a>
                                                <a href="delete_asset.php?id=<?php echo (int)$asset['id'];?>" class="btn btn-xs btn-danger" title="Hapus" data-toggle="tooltip" onclick="return confirm('Apakah Anda yakin ingin menghapus aset ini?');">
                                                    <i class="glyphicon glyphicon-remove"></i>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="8" class="text-center">Tidak ada data aset ditemukan.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($total_pages > 1): ?>
                    <nav aria-label="Page navigation">
                        <ul class="pagination pull-right">
                            <li class="page-item <?php if ($page <= 1) echo 'disabled'; ?>">
                                <a class="page-link" href="?page=<?php echo $page - 1; ?>&per_page=<?php echo $per_page; ?>&search=<?php echo urlencode($search_term); ?>&category=<?php echo urlencode($category_id); ?>&employee=<?php echo urlencode($employee_id); ?>&condition=<?php echo urlencode($condition_filter); ?>">Prev</a>
                            </li>
                            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                <li class="page-item <?php if ($i == $page) echo 'active'; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>&per_page=<?php echo $per_page; ?>&search=<?php echo urlencode($search_term); ?>&category=<?php echo urlencode($category_id); ?>&employee=<?php echo urlencode($employee_id); ?>&condition=<?php echo urlencode($condition_filter); ?>"><?php echo $i; ?></a>
                                </li>
                            <?php endfor; ?>
                            <li class="page-item <?php if ($page >= $total_pages) echo 'disabled'; ?>">
                                <a class="page-link" href="?page=<?php echo $page + 1; ?>&per_page=<?php echo $per_page; ?>&search=<?php echo urlencode($search_term); ?>&category=<?php echo urlencode($category_id); ?>&employee=<?php echo urlencode($employee_id); ?>&condition=<?php echo urlencode($condition_filter); ?>">Next</a>
                            </li>
                        </ul>
                    </nav>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php include_once('layouts/footer.php'); ?>