<?php
session_start();

// Error reporting untuk debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../../DataBase/koneksi.php';

// Cek Login & Role
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    header("Location: ../../index.html?error=session");
    exit;
}

$userRole = strtoupper(trim($_SESSION['role'] ?? ''));
$canAddEdit = ($userRole === 'A');

$backPage = ($userRole === 'A') ? '../admin/home_admin.php' : (($userRole === 'M') ? '../manager/home_manager.php' : '../staff/home_staff.php');

// Pagination Settings
$itemsPerPage = 20; // Jumlah item per halaman
$currentPage = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;

// Fungsi Upload Foto
function uploadFoto($file) {
    $uploadDir = __DIR__ . '/../../uploads/inventory/';
    
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
    
    $allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
    $maxSize = 5 * 1024 * 1024; // 5MB
    
    if (!in_array($file['type'], $allowedTypes)) {
        throw new Exception('Format file tidak didukung. Gunakan JPG, PNG, atau GIF.');
    }
    
    if ($file['size'] > $maxSize) {
        throw new Exception('Ukuran file maksimal 5MB.');
    }
    
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $fileName = 'asset_' . time() . '_' . uniqid() . '.' . $extension;
    $targetPath = $uploadDir . $fileName;
    
    if (move_uploaded_file($file['tmp_name'], $targetPath)) {
        return $fileName;
    } else {
        throw new Exception('Gagal mengupload file.');
    }
}

// Fungsi Hapus Foto Lama
function deleteFoto($fileName) {
    if ($fileName && $fileName != '') {
        $filePath = __DIR__ . '/../../uploads/inventory/' . $fileName;
        if (file_exists($filePath)) {
            unlink($filePath);
        }
    }
}

// Handle CRUD Operations
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'delete' && $canAddEdit) {
        try {
            $id = intval($_POST['id']);
            
            $checkStmt = $conn->prepare("SELECT id, jenis_barang, foto FROM inventory WHERE id = ?");
            $checkStmt->bind_param("i", $id);
            $checkStmt->execute();
            $result = $checkStmt->get_result();
            
            if ($result->num_rows === 0) {
                $_SESSION['error_msg'] = 'Data tidak ditemukan!';
                header("Location: " . $_SERVER['PHP_SELF'] . "?error=not_found");
                exit;
            }
            
            $row = $result->fetch_assoc();
            
            $stmt = $conn->prepare("DELETE FROM inventory WHERE id = ?");
            $stmt->bind_param("i", $id);
            
            if ($stmt->execute()) {
                deleteFoto($row['foto']);
                $_SESSION['success_msg'] = 'Data berhasil dihapus!';
                header("Location: " . $_SERVER['PHP_SELF'] . "?success=deleted");
                exit;
            } else {
                $_SESSION['error_msg'] = 'Gagal menghapus data: ' . $stmt->error;
                header("Location: " . $_SERVER['PHP_SELF'] . "?error=delete_failed");
                exit;
            }
        } catch (Exception $e) {
            error_log("Error deleting inventory: " . $e->getMessage());
            $_SESSION['error_msg'] = 'Terjadi kesalahan: ' . $e->getMessage();
            header("Location: " . $_SERVER['PHP_SELF'] . "?error=delete_exception");
            exit;
        }
    }
    
    if ($action === 'add' && $canAddEdit) {
        try {
            $kode = trim($_POST['kode_aset']);
            $nama = trim($_POST['nama_barang']);
            $kategori = trim($_POST['kategori'] ?? '');
            $spek = trim($_POST['spesifikasi'] ?? '');
            $harga = floatval($_POST['harga'] ?? 0);
            $tgl = trim($_POST['tanggal_perolehan'] ?? '');
            $sumber = trim($_POST['sumber_dana'] ?? '');
            $kantor = trim($_POST['kantor'] ?? '');
            $kondisi = trim($_POST['kondisi'] ?? '');
            $status = trim($_POST['status'] ?? 'aktif');
            $ket = trim($_POST['keterangan'] ?? '');
            $merk = trim($_POST['merk'] ?? '');
            
            if (!isset($_FILES['foto']) || $_FILES['foto']['error'] === UPLOAD_ERR_NO_FILE) {
                $_SESSION['error_msg'] = 'Foto barang wajib diupload!';
                header("Location: " . $_SERVER['PHP_SELF'] . "?error=no_photo");
                exit;
            }
            
            $fotoName = uploadFoto($_FILES['foto']);
            
            $stmt = $conn->prepare("INSERT INTO inventory (kode_aset, jenis_barang, kategori, spesifikasi, harga_perolehan, tanggal_perolehan, sumber_dana, kantor, kondisi, status, keterangan_keluar, foto, merk) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("ssssdssssssss", $kode, $nama, $kategori, $spek, $harga, $tgl, $sumber, $kantor, $kondisi, $status, $ket, $fotoName, $merk);
            
            if ($stmt->execute()) {
                $_SESSION['success_msg'] = 'Data berhasil ditambahkan!';
                header("Location: " . $_SERVER['PHP_SELF'] . "?success=added");
                exit;
            } else {
                deleteFoto($fotoName);
                $_SESSION['error_msg'] = 'Gagal menambahkan data: ' . $stmt->error;
                header("Location: " . $_SERVER['PHP_SELF'] . "?error=add_failed");
                exit;
            }
        } catch (Exception $e) {
            error_log("Error adding inventory: " . $e->getMessage());
            $_SESSION['error_msg'] = 'Terjadi kesalahan: ' . $e->getMessage();
            header("Location: " . $_SERVER['PHP_SELF'] . "?error=add_exception");
            exit;
        }
    }
    
    if ($action === 'edit' && $canAddEdit) {
        try {
            $id = intval($_POST['id']);
            $kode = trim($_POST['kode_aset']);
            $nama = trim($_POST['nama_barang']);
            $kategori = trim($_POST['kategori'] ?? '');
            $spek = trim($_POST['spesifikasi'] ?? '');
            $harga = floatval($_POST['harga'] ?? 0);
            $tgl = trim($_POST['tanggal_perolehan'] ?? '');
            $sumber = trim($_POST['sumber_dana'] ?? '');
            $kantor = trim($_POST['kantor'] ?? '');
            $kondisi = trim($_POST['kondisi'] ?? '');
            $status = trim($_POST['status'] ?? 'aktif');
            $ket = trim($_POST['keterangan'] ?? '');
            $merk = trim($_POST['merk'] ?? '');
            
            $stmt = $conn->prepare("SELECT foto FROM inventory WHERE id = ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $result = $stmt->get_result();
            $oldData = $result->fetch_assoc();
            $oldFoto = $oldData['foto'];
            
            $fotoName = $oldFoto;
            
            if (isset($_FILES['foto']) && $_FILES['foto']['error'] !== UPLOAD_ERR_NO_FILE) {
                $fotoName = uploadFoto($_FILES['foto']);
                deleteFoto($oldFoto);
            }
            
            $stmt = $conn->prepare("UPDATE inventory SET kode_aset=?, jenis_barang=?, kategori=?, spesifikasi=?, harga_perolehan=?, tanggal_perolehan=?, sumber_dana=?, kantor=?, kondisi=?, status=?, keterangan_kelur=?, foto=?, merk=? WHERE id=?");
            $stmt->bind_param("ssssdssssssssi", $kode, $nama, $kategori, $spek, $harga, $tgl, $sumber, $kantor, $kondisi, $status, $ket, $fotoName, $merk, $id);
            
            if ($stmt->execute()) {
                $_SESSION['success_msg'] = 'Data berhasil diperbarui!';
                header("Location: " . $_SERVER['PHP_SELF'] . "?success=updated");
                exit;
            } else {
                $_SESSION['error_msg'] = 'Gagal memperbarui data: ' . $stmt->error;
                header("Location: " . $_SERVER['PHP_SELF'] . "?error=update_failed");
                exit;
            }
        } catch (Exception $e) {
            error_log("Error updating inventory: " . $e->getMessage());
            $_SESSION['error_msg'] = 'Terjadi kesalahan: ' . $e->getMessage();
            header("Location: " . $_SERVER['PHP_SELF'] . "?error=update_exception");
            exit;
        }
    }
}

// Data Dropdown
$kantorList = $conn->query("SELECT DISTINCT kantor FROM inventory WHERE kantor IS NOT NULL AND kantor != '' ORDER BY kantor");
$kategoriList = $conn->query("SELECT DISTINCT kategori FROM inventory WHERE kategori IS NOT NULL AND kategori != '' ORDER BY kategori");
$sumberDanaList = $conn->query("SELECT DISTINCT sumber_dana FROM inventory WHERE sumber_dana IS NOT NULL AND sumber_dana != '' ORDER BY sumber_dana");
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inventory Aset - ACF EDU HUB</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-teal: #7AB2B2;
            --secondary-teal: #4D869C;
            --light-mint: #CDE8E5;
            --lightest-mint: #EEF7FF;
            --bg-light: #f8fafc;
            --text-dark: #2d3748;
            --text-medium: #4a5568;
            --text-light: #718096;
            --border-color: #e2e8f0;
            --white: #ffffff;
        }

        * { 
            margin: 0; 
            padding: 0; 
            box-sizing: border-box; 
        }
        
        body { 
            font-family: 'Inter', sans-serif; 
            background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
            color: var(--text-dark); 
            line-height: 1.6;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 24px;
        }

        /* Alert Messages */
        .alert {
            padding: 14px 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-weight: 600;
            font-size: 14px;
            animation: slideDown 0.3s ease;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }

        @keyframes slideDown {
            from { transform: translateY(-20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }

        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border-left: 4px solid #10b981;
        }

        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }

        /* Page Header */
        .page-header { 
            background: var(--white); 
            padding: 24px 28px; 
            border-radius: 12px; 
            margin-bottom: 24px; 
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 16px;
        }

        .page-header h1 {
            font-size: 24px;
            font-weight: 700;
            color: var(--text-dark);
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .page-header h1 i {
            color: var(--primary-teal);
        }

        .header-actions {
            display: flex;
            gap: 12px;
            align-items: center;
        }

        /* Status Tabs */
        .status-tabs {
            background: var(--white);
            padding: 16px 20px;
            border-radius: 12px;
            margin-bottom: 24px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }

        .status-tabs-container {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }

        .status-tab {
            padding: 10px 18px;
            border: 2px solid var(--border-color);
            border-radius: 8px;
            background: var(--white);
            color: var(--text-medium);
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .status-tab:hover {
            border-color: var(--primary-teal);
            background: var(--lightest-mint);
            color: var(--primary-teal);
        }

        .status-tab.active {
            background: var(--primary-teal);
            color: var(--white);
            border-color: var(--primary-teal);
        }
        
        /* Filters */
        .filters { 
            background: var(--white); 
            padding: 24px; 
            border-radius: 12px; 
            margin-bottom: 24px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }

        .filter-grid { 
            display: grid; 
            grid-template-columns: 2fr 1fr 1fr 1fr; 
            gap: 16px; 
        }

        .filter-group label { 
            display: block; 
            font-size: 11px; 
            font-weight: 700; 
            color: var(--text-medium); 
            text-transform: uppercase; 
            margin-bottom: 8px;
            letter-spacing: 0.5px;
        }

        .filter-input-wrapper { 
            position: relative; 
        }

        .filter-input-wrapper i { 
            position: absolute; 
            left: 14px; 
            top: 50%; 
            transform: translateY(-50%); 
            color: var(--text-light); 
            font-size: 14px;
        }
        
        .filter-input, .filter-select { 
            width: 100%; 
            padding: 11px 14px 11px 42px; 
            border: 2px solid var(--border-color); 
            border-radius: 8px; 
            font-size: 14px; 
            font-weight: 500;
            transition: all 0.2s ease; 
            outline: none;
            background: var(--white);
            color: var(--text-dark);
        }

        .filter-select {
            padding-left: 14px;
        }

        .filter-input:focus, .filter-select:focus { 
            border-color: var(--primary-teal); 
            box-shadow: 0 0 0 3px rgba(122, 178, 178, 0.1);
        }

        /* Table Wrapper */
        .table-wrapper {
            background: var(--white);
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
            overflow: hidden;
            margin-bottom: 24px;
        }

        .table-container { 
            overflow-x: auto;
        }

        .table-container::-webkit-scrollbar {
            height: 8px;
        }

        .table-container::-webkit-scrollbar-track {
            background: #f1f5f9;
        }

        .table-container::-webkit-scrollbar-thumb {
            background: var(--primary-teal);
            border-radius: 4px;
        }

        table { 
            width: 100%; 
            border-collapse: collapse;
        }

        thead { 
            background: var(--primary-teal);
        }

        th { 
            padding: 14px 16px; 
            text-align: left; 
            font-size: 11px; 
            text-transform: uppercase; 
            letter-spacing: 0.5px;
            font-weight: 700;
            color: var(--white);
            white-space: nowrap;
            position: sticky;
            top: 0;
            z-index: 10;
        }

        td { 
            padding: 14px 16px; 
            border-bottom: 1px solid var(--border-color); 
            font-size: 13px;
            font-weight: 500;
            color: var(--text-dark);
            vertical-align: middle;
        }

        /* Column Widths */
        th:nth-child(1), td:nth-child(1) { width: 50px; text-align: center; }
        th:nth-child(2), td:nth-child(2) { width: 60px; text-align: center; }
        th:nth-child(3), td:nth-child(3) { width: 120px; }
        th:nth-child(4), td:nth-child(4) { min-width: 180px; }
        th:nth-child(5), td:nth-child(5) { min-width: 200px; }
        th:nth-child(6), td:nth-child(6) { width: 120px; text-align: right; }
        th:nth-child(7), td:nth-child(7) { width: 140px; }
        th:nth-child(8), td:nth-child(8) { width: 70px; text-align: center; }

        tbody tr:last-child td {
            border-bottom: none;
        }

        tbody tr {
            transition: background 0.15s ease;
        }

        tbody tr:hover {
            background: #f8fafc;
        }

        /* Badges */
        .kode-badge { 
            background: var(--secondary-teal);
            color: var(--white); 
            padding: 4px 10px; 
            border-radius: 6px; 
            font-family: 'Courier New', monospace; 
            font-weight: 700; 
            font-size: 11px;
            display: inline-block;
            letter-spacing: 0.5px;
        }

        .status-badge {
            padding: 4px 10px;
            border-radius: 5px;
            font-size: 10px;
            font-weight: 700;
            text-transform: uppercase;
            display: inline-block;
            letter-spacing: 0.3px;
        }

        .status-aktif { background: #d1fae5; color: #065f46; }
        .status-rusak { background: #fed7aa; color: #92400e; }
        .status-lelang { background: #ddd6fe; color: #5b21b6; }
        .status-hilang { background: #fecaca; color: #991b1b; }
        .status-dihapus { background: #f3f4f6; color: #374151; }
        
        /* Buttons */
        .btn { 
            padding: 11px 20px; 
            border-radius: 8px; 
            text-decoration: none; 
            font-weight: 600; 
            font-size: 14px; 
            display: inline-flex; 
            align-items: center; 
            gap: 8px; 
            border: none; 
            cursor: pointer; 
            transition: all 0.2s ease;
            white-space: nowrap;
        }

        .btn-secondary { 
            background: var(--white); 
            border: 2px solid var(--border-color); 
            color: var(--text-dark); 
        }

        .btn-secondary:hover {
            background: var(--bg-light);
            border-color: var(--primary-teal);
            color: var(--primary-teal);
        }

        .btn-success {
            background: #10b981;
            color: var(--white);
            box-shadow: 0 2px 4px rgba(16, 185, 129, 0.2);
        }

        .btn-success:hover {
            background: #059669;
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(16, 185, 129, 0.3);
        }

        /* Pagination */
        .pagination-wrapper {
            background: var(--white);
            padding: 20px 24px;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 16px;
        }

        .pagination-info {
            color: var(--text-medium);
            font-size: 14px;
            font-weight: 500;
        }

        .pagination-info strong {
            color: var(--text-dark);
            font-weight: 700;
        }

        .pagination {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .pagination-btn {
            padding: 9px 16px;
            border: 2px solid var(--border-color);
            border-radius: 8px;
            background: var(--white);
            color: var(--text-dark);
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        .pagination-btn:hover:not(:disabled) {
            border-color: var(--primary-teal);
            background: var(--lightest-mint);
            color: var(--primary-teal);
        }

        .pagination-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .pagination-pages {
            display: flex;
            align-items: center;
            gap: 4px;
        }

        .pagination-page {
            min-width: 40px;
            height: 40px;
            padding: 0 12px;
            border: 2px solid var(--border-color);
            border-radius: 8px;
            background: var(--white);
            color: var(--text-dark);
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .pagination-page:hover {
            border-color: var(--primary-teal);
            background: var(--lightest-mint);
            color: var(--primary-teal);
        }

        .pagination-page.active {
            background: var(--primary-teal);
            border-color: var(--primary-teal);
            color: var(--white);
        }

        .pagination-ellipsis {
            padding: 0 8px;
            color: var(--text-light);
            font-weight: 600;
        }

        /* Thumbnail */
        .table-thumbnail {
            width: 48px;
            height: 48px;
            object-fit: cover;
            border-radius: 6px;
            border: 2px solid var(--border-color);
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .table-thumbnail:hover {
            transform: scale(1.2);
            border-color: var(--primary-teal);
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
            z-index: 100;
        }

        /* Action Dropdown */
        .action-dropdown {
            position: relative;
            display: inline-block;
        }

        .action-btn {
            width: 34px;
            height: 34px;
            border-radius: 6px;
            background: var(--lightest-mint);
            border: 1px solid var(--light-mint);
            color: var(--secondary-teal);
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
            font-size: 16px;
        }

        .action-btn:hover {
            background: var(--light-mint);
            border-color: var(--primary-teal);
            color: var(--primary-teal);
        }

        .action-menu {
            position: absolute;
            right: 0;
            top: calc(100% + 6px);
            background: var(--white);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
            min-width: 140px;
            display: none;
            z-index: 1000;
            overflow: hidden;
        }

        .action-menu.show {
            display: block;
            animation: menuSlide 0.2s ease;
        }

        @keyframes menuSlide {
            from { 
                opacity: 0;
                transform: translateY(-8px);
            }
            to { 
                opacity: 1;
                transform: translateY(0);
            }
        }

        .action-menu-item {
            padding: 11px 14px;
            cursor: pointer;
            transition: all 0.15s ease;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 13px;
            font-weight: 600;
            border-left: 3px solid transparent;
        }

        .action-menu-item i {
            width: 16px;
            text-align: center;
            font-size: 14px;
        }

        .action-menu-item:hover {
            background: var(--lightest-mint);
            border-left-color: var(--primary-teal);
        }

        .action-menu-item.detail { color: #3b82f6; }
        .action-menu-item.edit { color: #f59e0b; }
        .action-menu-item.delete { color: #ef4444; }

        /* Modal */
        .modal {
            display: none;
            position: fixed;
            z-index: 2000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            backdrop-filter: blur(4px);
        }

        .modal.show {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: var(--white);
            border-radius: 12px;
            width: 90%;
            max-width: 850px;
            max-height: 90vh;
            overflow-y: auto;
            animation: slideIn 0.3s ease;
            box-shadow: 0 20px 40px rgba(0,0,0,0.2);
        }

        @keyframes slideIn {
            from { transform: translateY(-30px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }

        .modal-header {
            background: var(--primary-teal);
            color: var(--white);
            padding: 20px 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-radius: 12px 12px 0 0;
        }

        .modal-header h2 {
            font-size: 18px;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .modal-close {
            background: rgba(255,255,255,0.2);
            border: none;
            color: var(--white);
            width: 32px;
            height: 32px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 20px;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-close:hover {
            background: rgba(255,255,255,0.3);
            transform: rotate(90deg);
        }

        .modal-body {
            padding: 24px;
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 18px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .form-group.full {
            grid-column: 1 / -1;
        }

        .form-label {
            font-size: 13px;
            font-weight: 700;
            color: var(--text-dark);
        }

        .form-label .required {
            color: #ef4444;
        }

        .form-input, .form-select, .form-textarea {
            padding: 11px 14px;
            border: 2px solid var(--border-color);
            border-radius: 8px;
            font-size: 14px;
            font-family: 'Inter', sans-serif;
            transition: all 0.2s ease;
            font-weight: 500;
        }

        .form-input:focus, .form-select:focus, .form-textarea:focus {
            outline: none;
            border-color: var(--primary-teal);
            box-shadow: 0 0 0 3px rgba(122, 178, 178, 0.1);
        }

        .form-textarea {
            min-height: 80px;
            resize: vertical;
        }

        /* Upload Area */
        .photo-upload-area {
            border: 2px dashed var(--border-color);
            border-radius: 8px;
            padding: 24px;
            text-align: center;
            background: var(--lightest-mint);
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .photo-upload-area:hover {
            border-color: var(--primary-teal);
            background: var(--light-mint);
        }

        .photo-upload-area i {
            font-size: 48px;
            color: var(--primary-teal);
            margin-bottom: 12px;
        }

        .photo-upload-area p {
            color: var(--text-medium);
            font-size: 14px;
            margin: 6px 0;
        }

        .photo-preview {
            margin-top: 16px;
            text-align: center;
        }

        .photo-preview img {
            max-width: 100%;
            max-height: 300px;
            border-radius: 8px;
            border: 2px solid var(--border-color);
        }

        .remove-photo {
            margin-top: 12px;
            background: #ef4444;
            color: var(--white);
            border: none;
            padding: 9px 18px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 13px;
            font-weight: 600;
        }

        .remove-photo:hover {
            background: #dc2626;
        }

        .modal-footer {
            padding: 18px 24px;
            border-top: 2px solid var(--border-color);
            display: flex;
            gap: 12px;
            justify-content: flex-end;
        }

        .detail-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 16px;
        }

        .detail-item {
            display: flex;
            flex-direction: column;
            gap: 6px;
        }

        .detail-item.full {
            grid-column: 1 / -1;
        }

        .detail-label {
            font-size: 11px;
            font-weight: 700;
            color: var(--text-medium);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .detail-value {
            font-size: 14px;
            font-weight: 600;
            color: var(--text-dark);
            padding: 10px 14px;
            background: var(--lightest-mint);
            border-radius: 6px;
        }

        .detail-photo {
            text-align: center;
            padding: 20px;
            background: var(--lightest-mint);
            border-radius: 8px;
        }

        .detail-photo img {
            max-width: 100%;
            max-height: 400px;
            border-radius: 8px;
            border: 2px solid var(--border-color);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }

        .detail-section-title {
            grid-column: 1 / -1;
            font-size: 14px;
            font-weight: 700;
            color: var(--primary-teal);
            padding: 12px 0 8px 0;
            border-bottom: 2px solid var(--light-mint);
            margin-top: 12px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .detail-section-title:first-of-type {
            margin-top: 0;
        }

        .detail-section-title i {
            font-size: 16px;
        }

        .no-photo {
            padding: 60px;
            background: var(--border-color);
            border-radius: 8px;
            color: var(--text-light);
            text-align: center;
        }

        .no-photo i {
            font-size: 48px;
            color: var(--text-light);
        }

        .no-photo p {
            margin-top: 12px;
            font-weight: 500;
        }

        /* Table Cell Styling */
        .td-center {
            text-align: center;
        }

        .td-no {
            font-weight: 700;
            color: var(--text-medium);
        }

        .td-barang {
            min-width: 200px;
        }

        .barang-nama {
            font-weight: 700;
            color: var(--text-dark);
            margin-bottom: 4px;
        }

        .barang-merk {
            font-size: 12px;
            color: var(--text-light);
            margin-bottom: 6px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .barang-merk i {
            font-size: 11px;
        }

        .barang-status {
            margin-top: 6px;
        }

        .td-spek {
            color: var(--text-medium);
            font-size: 13px;
            line-height: 1.5;
        }

        .td-harga {
            text-align: right;
            font-weight: 700;
            color: var(--secondary-teal);
            white-space: nowrap;
        }

        .td-lokasi {
            color: var(--text-medium);
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .td-lokasi i {
            color: var(--primary-teal);
            font-size: 12px;
        }

        .photo-placeholder {
            width: 48px;
            height: 48px;
            background: var(--border-color);
            border-radius: 6px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--text-light);
            margin: 0 auto;
        }

        .photo-placeholder i {
            font-size: 20px;
        }

        /* Empty State */
        .td-empty {
            padding: 60px 20px !important;
        }

        .empty-state {
            text-align: center;
        }

        .empty-state i {
            font-size: 64px;
            color: var(--border-color);
            display: block;
            margin-bottom: 16px;
        }

        .empty-title {
            font-size: 18px;
            font-weight: 700;
            color: var(--text-dark);
            margin-bottom: 8px;
        }

        .empty-desc {
            font-size: 14px;
            color: var(--text-light);
        }

        /* Responsive */
        @media (max-width: 768px) {
            .container {
                padding: 16px;
            }
            
            .filter-grid, .form-grid, .detail-grid { 
                grid-template-columns: 1fr; 
            }
            
            .page-header {
                flex-direction: column;
                align-items: flex-start;
            }

            .header-actions {
                width: 100%;
                flex-direction: column;
            }
            
            .header-actions .btn {
                width: 100%;
                justify-content: center;
            }

            table {
                min-width: 700px;
            }

            .pagination-wrapper {
                flex-direction: column;
                text-align: center;
            }

            .pagination {
                width: 100%;
                justify-content: center;
                flex-wrap: wrap;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <?php
        if (isset($_SESSION['success_msg'])) {
            echo "<div class='alert alert-success'><i class='fas fa-check-circle'></i> " . htmlspecialchars($_SESSION['success_msg']) . "</div>";
            unset($_SESSION['success_msg']);
        }
        
        if (isset($_SESSION['error_msg'])) {
            echo "<div class='alert alert-error'><i class='fas fa-exclamation-circle'></i> " . htmlspecialchars($_SESSION['error_msg']) . "</div>";
            unset($_SESSION['error_msg']);
        }
        ?>

        <div class="page-header">
            <h1><i class="fas fa-boxes"></i> Inventory Aset</h1>
            <div class="header-actions">
                <?php if($canAddEdit): ?>
                <button onclick="openAddModal()" class="btn btn-success">
                    <i class="fas fa-plus"></i> Tambah Aset
                </button>
                <?php endif; ?>
                <a href="<?= $backPage ?>" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Kembali
                </a>
            </div>
        </div>

        <div class="status-tabs">
            <div class="status-tabs-container">
                <button class="status-tab active" data-status="" onclick="filterByStatus(event, '')">
                    <i class="fas fa-layer-group"></i> Semua
                </button>
                <button class="status-tab" data-status="aktif" onclick="filterByStatus(event, 'aktif')">
                    <i class="fas fa-check-circle"></i> Aktif
                </button>
                <button class="status-tab" data-status="tidak-ada" onclick="filterByStatus(event, 'tidak-ada')">
                    <i class="fas fa-times-circle"></i> Non Aktif
                </button>
            </div>
        </div>

        <form id="filterForm" class="filters">
            <div class="filter-grid">
                <div class="filter-group">
                    <label>Pencarian</label>
                    <div class="filter-input-wrapper">
                        <i class="fas fa-search"></i>
                        <input type="text" name="search" class="filter-input" placeholder="Cari nama, kode, spesifikasi...">
                    </div>
                </div>

                <div class="filter-group">
                    <label>Kantor</label>
                    <select name="kantor" class="filter-select">
                        <option value="">Semua</option>
                        <?php 
                        if ($kantorList && $kantorList->num_rows > 0) {
                            while($k = $kantorList->fetch_assoc()): 
                        ?>
                            <option value="<?= htmlspecialchars($k['kantor']) ?>"><?= htmlspecialchars($k['kantor']) ?></option>
                        <?php 
                            endwhile;
                        }
                        ?>
                    </select>
                </div>

                <div class="filter-group">
                    <label>Kategori</label>
                    <select name="kategori" class="filter-select">
                        <option value="">Semua</option>
                        <?php 
                        if ($kategoriList && $kategoriList->num_rows > 0) {
                            while($cat = $kategoriList->fetch_assoc()): 
                        ?>
                            <option value="<?= htmlspecialchars($cat['kategori']) ?>"><?= htmlspecialchars($cat['kategori']) ?></option>
                        <?php 
                            endwhile;
                        }
                        ?>
                    </select>
                </div>

                <div class="filter-group">
                    <label>Sumber Dana</label>
                    <select name="sumber_dana" class="filter-select">
                        <option value="">Semua</option>
                        <?php 
                        if ($sumberDanaList && $sumberDanaList->num_rows > 0) {
                            while($sd = $sumberDanaList->fetch_assoc()): 
                        ?>
                            <option value="<?= htmlspecialchars($sd['sumber_dana']) ?>"><?= htmlspecialchars($sd['sumber_dana']) ?></option>
                        <?php 
                            endwhile;
                        }
                        ?>
                    </select>
                </div>
            </div>
        </form>

        <div class="table-wrapper">
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>NO</th>
                            <th>FOTO</th>
                            <th>KODE</th>
                            <th>BARANG</th>
                            <th>SPESIFIKASI</th>
                            <th>HARGA</th>
                            <th>LOKASI</th>
                            <th>AKSI</th>
                        </tr>
                    </thead>
                    <tbody id="inventoryTableBody">
                        <tr>
                            <td colspan="8" style="text-align: center; padding: 40px;">
                                <i class="fas fa-spinner fa-spin" style="font-size: 24px; color: var(--primary-teal);"></i>
                                <p style="margin-top: 12px; color: var(--text-medium); font-weight: 500;">Memuat data...</p>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Pagination -->
        <div class="pagination-wrapper" id="paginationWrapper" style="display: none;">
            <div class="pagination-info">
                Menampilkan <strong id="showingFrom">1</strong> - <strong id="showingTo">20</strong> dari <strong id="totalItems">0</strong> data
            </div>
            <nav class="pagination" id="paginationNav">
                <!-- Pagination buttons akan di-generate oleh JavaScript -->
            </nav>
        </div>
    </div>

    <!-- Detail Modal -->
    <div id="detailModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2><i class="fas fa-info-circle"></i> Detail Aset</h2>
                <button class="modal-close" onclick="closeModal('detailModal')">&times;</button>
            </div>
            <div class="modal-body" id="detailContent"></div>
        </div>
    </div>

    <!-- Form Modal -->
    <div id="formModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="formTitle"><i class="fas fa-edit"></i> Form Aset</h2>
                <button class="modal-close" onclick="closeModal('formModal')">&times;</button>
            </div>
            <form id="assetForm" method="POST" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>" enctype="multipart/form-data">
                <input type="hidden" name="action" id="formAction">
                <input type="hidden" name="id" id="formId">
                <div class="modal-body">
                    <div class="form-grid">
                        <div class="form-group full">
                            <label class="form-label">
                                <i class="fas fa-camera"></i> Foto Barang <span class="required">*</span>
                            </label>
                            <input type="file" name="foto" id="foto" accept="image/*" style="display:none;">
                            <div class="photo-upload-area" onclick="document.getElementById('foto').click()">
                                <i class="fas fa-cloud-upload-alt"></i>
                                <p><strong>Klik untuk upload foto</strong></p>
                                <p>atau drag & drop disini</p>
                                <p style="font-size: 12px; color: var(--text-light); margin-top: 8px;">Format: JPG, PNG, GIF (Max 5MB)</p>
                                <div class="file-name" id="fileName" style="color: var(--primary-teal); font-weight: 600; margin-top: 10px;"></div>
                            </div>
                            <div class="photo-preview" id="photoPreview" style="display:none;">
                                <img id="previewImage" src="" alt="Preview">
                                <br>
                                <button type="button" class="remove-photo" onclick="removePhoto()">
                                    <i class="fas fa-trash"></i> Hapus Foto
                                </button>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Kode Aset <span class="required">*</span></label>
                            <input type="text" name="kode_aset" id="kode_aset" class="form-input" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Nama Barang <span class="required">*</span></label>
                            <input type="text" name="nama_barang" id="nama_barang" class="form-input" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Merk</label>
                            <input type="text" name="merk" id="merk" class="form-input">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Kategori</label>
                            <input type="text" name="kategori" id="kategori" class="form-input">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Harga (Rp)</label>
                            <input type="number" name="harga" id="harga" class="form-input" min="0" step="0.01">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Tanggal Perolehan</label>
                            <input type="date" name="tanggal_perolehan" id="tanggal_perolehan" class="form-input">
                        </div>
                        <div class="form-group full">
                            <label class="form-label">Spesifikasi</label>
                            <textarea name="spesifikasi" id="spesifikasi" class="form-textarea"></textarea>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Sumber Dana</label>
                            <input type="text" name="sumber_dana" id="sumber_dana" class="form-input">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Kantor</label>
                            <input type="text" name="kantor" id="kantor" class="form-input">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Kondisi</label>
                            <select name="kondisi" id="kondisi" class="form-select">
                                <option value="">Pilih Kondisi</option>
                                <option value="Baik">Baik</option>
                                <option value="Rusak Ringan">Rusak Ringan</option>
                                <option value="Rusak Berat">Rusak Berat</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Status</label>
                            <select name="status" id="status" class="form-select">
                                <option value="">Pilih Status</option>
                                <option value="aktif">Aktif</option>
                                <option value="rusak">Rusak</option>
                                <option value="lelang">Lelang</option>
                                <option value="hilang">Hilang</option>
                                <option value="dihapus">Dihapus</option>
                            </select>
                        </div>
                        <div class="form-group full">
                            <label class="form-label">Keterangan</label>
                            <textarea name="keterangan" id="keterangan" class="form-textarea"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeModal('formModal')">Batal</button>
                    <button type="submit" class="btn btn-success"><i class="fas fa-save"></i> Simpan</button>
                </div>
            </form>
        </div>
    </div>

    <script>
    const canAddEdit = <?= $canAddEdit ? 'true' : 'false' ?>;
    const itemsPerPage = <?= $itemsPerPage ?>;
    let currentStatusFilter = '';
    let selectedFile = null;
    let currentPage = 1;
    let totalPages = 1;
    let totalItems = 0;

    // Auto-hide alerts
    setTimeout(() => {
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => {
            alert.style.transition = 'opacity 0.5s ease';
            alert.style.opacity = '0';
            setTimeout(() => alert.remove(), 500);
        });
    }, 5000);

    // Photo Upload Handler
    const photoInput = document.getElementById('foto');
    const uploadArea = document.querySelector('.photo-upload-area');
    const photoPreview = document.getElementById('photoPreview');
    const previewImage = document.getElementById('previewImage');
    const fileName = document.getElementById('fileName');

    photoInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) handleFileSelect(file);
    });

    uploadArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        uploadArea.style.borderColor = 'var(--primary-teal)';
        uploadArea.style.background = 'var(--light-mint)';
    });

    uploadArea.addEventListener('dragleave', function(e) {
        e.preventDefault();
        uploadArea.style.borderColor = 'var(--border-color)';
        uploadArea.style.background = 'var(--lightest-mint)';
    });

    uploadArea.addEventListener('drop', function(e) {
        e.preventDefault();
        uploadArea.style.borderColor = 'var(--border-color)';
        uploadArea.style.background = 'var(--lightest-mint)';
        const file = e.dataTransfer.files[0];
        if (file && file.type.startsWith('image/')) {
            photoInput.files = e.dataTransfer.files;
            handleFileSelect(file);
        }
    });

    function handleFileSelect(file) {
        selectedFile = file;
        fileName.textContent = file.name;
        
        const reader = new FileReader();
        reader.onload = function(e) {
            previewImage.src = e.target.result;
            photoPreview.style.display = 'block';
        };
        reader.readAsDataURL(file);
    }

    function removePhoto() {
        photoInput.value = '';
        selectedFile = null;
        fileName.textContent = '';
        photoPreview.style.display = 'none';
        previewImage.src = '';
    }

    function filterByStatus(event, status) {
        currentStatusFilter = status;
        currentPage = 1; // Reset ke halaman pertama saat filter berubah
        document.querySelectorAll('.status-tab').forEach(tab => tab.classList.remove('active'));
        event.target.classList.add('active');
        loadData();
    }

    function loadData() {
        const formData = new FormData(document.getElementById('filterForm'));
        if (currentStatusFilter) formData.append('status_filter', currentStatusFilter);
        formData.append('page', currentPage);
        formData.append('per_page', itemsPerPage);
        const params = new URLSearchParams(formData).toString();

        fetch('load_table.php?' + params)
            .then(response => {
                if (!response.ok) throw new Error('Network error');
                return response.json();
            })
            .then(data => {
                document.getElementById('inventoryTableBody').innerHTML = data.html;
                totalItems = data.total;
                totalPages = data.total_pages;
                updatePagination(data.total, data.total_pages);
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('inventoryTableBody').innerHTML = 
                    '<tr><td colspan="8" style="text-align:center; color:#ef4444; padding:40px;">Gagal memuat data</td></tr>';
            });
    }

    function updatePagination(total, pages) {
        const paginationWrapper = document.getElementById('paginationWrapper');
        const paginationNav = document.getElementById('paginationNav');
        
        if (total === 0) {
            paginationWrapper.style.display = 'none';
            return;
        }
        
        paginationWrapper.style.display = 'flex';
        
        // Update info
        const from = (currentPage - 1) * itemsPerPage + 1;
        const to = Math.min(currentPage * itemsPerPage, total);
        document.getElementById('showingFrom').textContent = from;
        document.getElementById('showingTo').textContent = to;
        document.getElementById('totalItems').textContent = total;
        
        // Generate pagination buttons
        let paginationHTML = '';
        
        // Previous button
        paginationHTML += `
            <button type="button" class="pagination-btn" ${currentPage === 1 ? 'disabled' : ''} onclick="goToPage(${currentPage - 1})">
                <i class="fas fa-chevron-left"></i> Previous
            </button>
        `;
        
        // Page numbers
        paginationHTML += '<div class="pagination-pages">';
        
        // Always show first page
        if (pages > 0) {
            paginationHTML += `
                <button type="button" class="pagination-page ${currentPage === 1 ? 'active' : ''}" onclick="goToPage(1)">
                    1
                </button>
            `;
        }
        
        // Show ellipsis if needed
        if (currentPage > 3) {
            paginationHTML += '<span class="pagination-ellipsis">...</span>';
        }
        
        // Show pages around current page
        for (let i = Math.max(2, currentPage - 1); i <= Math.min(pages - 1, currentPage + 1); i++) {
            paginationHTML += `
                <button type="button" class="pagination-page ${currentPage === i ? 'active' : ''}" onclick="goToPage(${i})">
                    ${i}
                </button>
            `;
        }
        
        // Show ellipsis if needed
        if (currentPage < pages - 2) {
            paginationHTML += '<span class="pagination-ellipsis">...</span>';
        }
        
        // Always show last page
        if (pages > 1) {
            paginationHTML += `
                <button type="button" class="pagination-page ${currentPage === pages ? 'active' : ''}" onclick="goToPage(${pages})">
                    ${pages}
                </button>
            `;
        }
        
        paginationHTML += '</div>';
        
        // Next button
        paginationHTML += `
            <button type="button" class="pagination-btn" ${currentPage === pages ? 'disabled' : ''} onclick="goToPage(${currentPage + 1})">
                Next <i class="fas fa-chevron-right"></i>
            </button>
        `;
        
        paginationNav.innerHTML = paginationHTML;
    }

    function goToPage(page) {
        if (page < 1 || page > totalPages) return;
        currentPage = page;
        loadData();
        // Scroll to top of table
        document.querySelector('.table-wrapper').scrollIntoView({ behavior: 'smooth', block: 'start' });
    }

    document.getElementById('filterForm').addEventListener('change', () => {
        currentPage = 1; // Reset ke halaman pertama saat filter berubah
        loadData();
    });
    
    let typingTimer;
    document.querySelector('input[name="search"]').addEventListener('input', () => {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(() => {
            currentPage = 1; // Reset ke halaman pertama saat search berubah
            loadData();
        }, 500);
    });

    function toggleActionMenu(event, btn) {
        event.stopPropagation();
        const menu = btn.nextElementSibling;
        document.querySelectorAll('.action-menu').forEach(m => {
            if (m !== menu) m.classList.remove('show');
        });
        menu.classList.toggle('show');
    }

    document.addEventListener('click', () => {
        document.querySelectorAll('.action-menu').forEach(m => m.classList.remove('show'));
    });

    function openModal(id) {
        document.getElementById(id).classList.add('show');
    }

    function closeModal(id) {
        document.getElementById(id).classList.remove('show');
        if (id === 'formModal') removePhoto();
    }

    function openAddModal() {
        document.getElementById('formTitle').innerHTML = '<i class="fas fa-plus"></i> Tambah Aset';
        document.getElementById('formAction').value = 'add';
        document.getElementById('assetForm').reset();
        document.getElementById('formId').value = '';
        removePhoto();
        openModal('formModal');
    }

    function viewDetail(id) {
        fetch('load_table.php?action=detail&id=' + id)
            .then(response => response.text())
            .then(data => {
                document.getElementById('detailContent').innerHTML = data;
                openModal('detailModal');
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Gagal memuat detail');
            });
    }

    function editAsset(id) {
        fetch('load_table.php?action=get&id=' + id)
            .then(response => response.json())
            .then(data => {
                document.getElementById('formTitle').innerHTML = '<i class="fas fa-edit"></i> Edit Aset';
                document.getElementById('formAction').value = 'edit';
                document.getElementById('formId').value = data.id;
                document.getElementById('kode_aset').value = data.kode_aset || '';
                document.getElementById('nama_barang').value = data.jenis_barang || '';
                document.getElementById('merk').value = data.merk || '';
                document.getElementById('kategori').value = data.kategori || '';
                document.getElementById('spesifikasi').value = data.spesifikasi || '';
                document.getElementById('harga').value = data.harga_perolehan || '';
                document.getElementById('tanggal_perolehan').value = data.tanggal_perolehan || '';
                document.getElementById('sumber_dana').value = data.sumber_dana || '';
                document.getElementById('kantor').value = data.kantor || '';
                document.getElementById('kondisi').value = data.kondisi || '';
                document.getElementById('status').value = data.status || '';
                document.getElementById('keterangan').value = data.keterangan_keluar || '';
                
                if (data.foto) {
                    fileName.textContent = 'Foto saat ini: ' + data.foto;
                    previewImage.src = '../../uploads/inventory/' + data.foto;
                    photoPreview.style.display = 'block';
                }
                
                openModal('formModal');
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Gagal memuat data');
            });
    }

    function deleteAsset(id, nama) {
        if (confirm('Hapus aset "' + nama + '"?\n\nData dan foto yang dihapus tidak dapat dikembalikan.')) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = '<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>';
            form.innerHTML = '<input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="' + id + '">';
            document.body.appendChild(form);
            form.submit();
        }
    }

    function viewPhoto(src) {
        const modal = document.createElement('div');
        modal.className = 'modal show';
        modal.innerHTML = `
            <div class="modal-content" style="max-width: 90%; max-height: 90%;">
                <div class="modal-header">
                    <h2><i class="fas fa-image"></i> Preview Foto</h2>
                    <button class="modal-close" onclick="this.closest('.modal').remove()">&times;</button>
                </div>
                <div class="modal-body" style="text-align: center; padding: 24px;">
                    <img src="${src}" style="max-width: 100%; max-height: 70vh; border-radius: 8px;">
                </div>
            </div>
        `;
        document.body.appendChild(modal);
        
        modal.addEventListener('click', function(e) {
            if (e.target === modal) modal.remove();
        });
    }

    window.addEventListener('DOMContentLoaded', loadData);
    </script>
</body>
</html>