<?php
session_start();
require_once __DIR__ . '/../../DataBase/koneksi.php';

// Cek Login
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

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

$action = $_GET['action'] ?? '';

// Handle Detail Request
if ($action === 'detail') {
    $id = intval($_GET['id']);
    $stmt = $conn->prepare("SELECT * FROM inventory WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = $result->fetch_assoc();
    
    if ($data) {
        $statusClass = 'status-' . strtolower($data['status'] ?? 'aktif');
        $statusText = ucfirst($data['status'] ?? 'Aktif');
        
        echo '<div class="detail-grid">';
        
        // === FOTO (Full Width) ===
        echo '<div class="detail-item full">';
        echo '<div class="detail-label"><i class="fas fa-camera"></i> Foto Barang</div>';
        echo '<div class="detail-photo">';
        if ($data['foto'] && file_exists(__DIR__ . '/../../uploads/inventory/' . $data['foto'])) {
            echo '<img src="../../uploads/inventory/' . htmlspecialchars($data['foto']) . '" alt="Foto Aset" onclick="viewPhoto(this.src)" style="cursor:zoom-in;">';
        } else {
            echo '<div class="no-photo">';
            echo '<i class="fas fa-image"></i>';
            echo '<p>Tidak ada foto</p>';
            echo '</div>';
        }
        echo '</div>';
        echo '</div>';
        
        // === INFORMASI UTAMA ===
        echo '<div class="detail-section-title"><i class="fas fa-info-circle"></i> Informasi Utama</div>';
        
        echo '<div class="detail-item">';
        echo '<div class="detail-label">Kode Aset</div>';
        echo '<div class="detail-value"><strong>' . htmlspecialchars($data['kode_aset_auto'] ?? $data['kode_aset'] ?? '-') . '</strong></div>';
        echo '</div>';
        
        echo '<div class="detail-item">';
        echo '<div class="detail-label">Status</div>';
        echo '<div class="detail-value"><span class="status-badge ' . $statusClass . '">' . $statusText . '</span></div>';
        echo '</div>';
        
        echo '<div class="detail-item">';
        echo '<div class="detail-label">Jenis Barang</div>';
        echo '<div class="detail-value">' . htmlspecialchars($data['jenis_barang'] ?? '-') . '</div>';
        echo '</div>';
        
        echo '<div class="detail-item">';
        echo '<div class="detail-label">Merk / Brand</div>';
        echo '<div class="detail-value">' . htmlspecialchars($data['merk'] ?? '-') . '</div>';
        echo '</div>';
        
        echo '<div class="detail-item">';
        echo '<div class="detail-label">Kategori</div>';
        echo '<div class="detail-value">' . htmlspecialchars($data['kategori'] ?? '-') . '</div>';
        echo '</div>';
        
        echo '<div class="detail-item">';
        echo '<div class="detail-label">Kondisi</div>';
        echo '<div class="detail-value">' . htmlspecialchars($data['kondisi'] ?? '-') . '</div>';
        echo '</div>';
        
        // === SPESIFIKASI ===
        if (!empty($data['spesifikasi'])) {
            echo '<div class="detail-section-title"><i class="fas fa-list-ul"></i> Spesifikasi</div>';
            echo '<div class="detail-item full">';
            echo '<div class="detail-value" style="white-space: pre-line;">' . htmlspecialchars($data['spesifikasi']) . '</div>';
            echo '</div>';
        }
        
        // === INFORMASI KEUANGAN ===
        echo '<div class="detail-section-title"><i class="fas fa-money-bill-wave"></i> Informasi Keuangan</div>';
        
        echo '<div class="detail-item">';
        echo '<div class="detail-label">Harga Perolehan</div>';
        echo '<div class="detail-value"><strong style="color: #10b981;">Rp ' . number_format($data['harga_perolehan'] ?? 0, 0, ',', '.') . '</strong></div>';
        echo '</div>';
        
        echo '<div class="detail-item">';
        echo '<div class="detail-label">Tanggal Perolehan</div>';
        echo '<div class="detail-value">' . ($data['tanggal_perolehan'] ? date('d F Y', strtotime($data['tanggal_perolehan'])) : '-') . '</div>';
        echo '</div>';
        
        echo '<div class="detail-item full">';
        echo '<div class="detail-label">Sumber Dana</div>';
        echo '<div class="detail-value">' . htmlspecialchars($data['sumber_dana'] ?? '-') . '</div>';
        echo '</div>';
        
        // === LOKASI ===
        echo '<div class="detail-section-title"><i class="fas fa-map-marker-alt"></i> Lokasi</div>';
        
        echo '<div class="detail-item full">';
        echo '<div class="detail-label">Kantor / Lokasi</div>';
        echo '<div class="detail-value">' . htmlspecialchars($data['kantor'] ?? '-') . '</div>';
        echo '</div>';
        
        // === KETERANGAN ===
        if (!empty($data['keterangan_keluar'])) {
            echo '<div class="detail-section-title"><i class="fas fa-sticky-note"></i> Keterangan Tambahan</div>';
            echo '<div class="detail-item full">';
            echo '<div class="detail-value" style="white-space: pre-line;">' . htmlspecialchars($data['keterangan_keluar']) . '</div>';
            echo '</div>';
        }
        
        echo '</div>';
    }
    exit;
}

// Handle Get Data Request (for Edit)
if ($action === 'get') {
    $id = intval($_GET['id']);
    $stmt = $conn->prepare("SELECT * FROM inventory WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = $result->fetch_assoc();
    
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

// Load Table Data with Pagination
$search = trim($_GET['search'] ?? '');
$filterKantor = trim($_GET['kantor'] ?? '');
$filterKategori = trim($_GET['kategori'] ?? '');
$filterSumberDana = trim($_GET['sumber_dana'] ?? '');
$statusFilter = trim($_GET['status_filter'] ?? '');

// Pagination parameters
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$perPage = isset($_GET['per_page']) ? max(1, intval($_GET['per_page'])) : 20;
$offset = ($page - 1) * $perPage;

$where = [];
$params = [];
$types = '';

// Filter Status
if (!empty($statusFilter)) {
    if ($statusFilter === 'tidak-ada') {
        $where[] = "status IN ('rusak', 'lelang', 'hilang', 'dihapus')";
    } else {
        $where[] = "status = ?";
        $params[] = $statusFilter;
        $types .= "s";
    }
}

// Filter Search
if (!empty($search)) {
    $where[] = "(jenis_barang LIKE ? OR kode_aset LIKE ? OR kode_aset_auto LIKE ? OR spesifikasi LIKE ? OR merk LIKE ?)";
    $searchParam = "%{$search}%";
    $params[] = $searchParam;
    $params[] = $searchParam;
    $params[] = $searchParam;
    $params[] = $searchParam;
    $params[] = $searchParam;
    $types .= "sssss";
}

// Filter Kantor
if (!empty($filterKantor)) {
    $where[] = "kantor = ?";
    $params[] = $filterKantor;
    $types .= "s";
}

// Filter Kategori
if (!empty($filterKategori)) {
    $where[] = "kategori = ?";
    $params[] = $filterKategori;
    $types .= "s";
}

// Filter Sumber Dana
if (!empty($filterSumberDana)) {
    $where[] = "sumber_dana = ?";
    $params[] = $filterSumberDana;
    $types .= "s";
}

$whereClause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

// Get total count
$countSql = "SELECT COUNT(*) as total FROM inventory $whereClause";
if (!empty($params)) {
    $countStmt = $conn->prepare($countSql);
    $countStmt->bind_param($types, ...$params);
    $countStmt->execute();
    $countResult = $countStmt->get_result();
    $totalRows = $countResult->fetch_assoc()['total'];
} else {
    $totalRows = $conn->query($countSql)->fetch_assoc()['total'];
}

$totalPages = ceil($totalRows / $perPage);

// Get paginated data
$sql = "SELECT * FROM inventory $whereClause ORDER BY id DESC LIMIT ? OFFSET ?";
$limitParams = $params;
$limitParams[] = $perPage;
$limitParams[] = $offset;
$limitTypes = $types . 'ii';

$stmt = $conn->prepare($sql);
if (!empty($limitParams)) {
    $stmt->bind_param($limitTypes, ...$limitParams);
}
$stmt->execute();
$result = $stmt->get_result();

// Generate HTML
$html = '';

if ($result->num_rows > 0) {
    $no = $offset + 1;
    while ($row = $result->fetch_assoc()) {
        $id = $row['id'];
        $kodeAset = htmlspecialchars($row['kode_aset_auto'] ?? $row['kode_aset'] ?? '-');
        $jenisBarang = htmlspecialchars($row['jenis_barang'] ?? '-');
        $merk = htmlspecialchars($row['merk'] ?? '');
        $spesifikasi = htmlspecialchars($row['spesifikasi'] ?? '-');
        $hargaPerolehan = number_format($row['harga_perolehan'] ?? 0, 0, ',', '.');
        $lokasiKantor = htmlspecialchars($row['kantor'] ?? '-');
        $status = $row['status'] ?? 'aktif';
        $statusClass = 'status-' . $status;
        $statusText = ucfirst($status);
        
        $html .= "<tr>";
        
        // === NO ===
        $html .= "<td class='td-center td-no'>$no</td>";
        
        // === FOTO ===
        $html .= '<td class="td-center">';
        if ($row['foto'] && file_exists(__DIR__ . '/../../uploads/inventory/' . $row['foto'])) {
            $html .= '<img src="../../uploads/inventory/' . htmlspecialchars($row['foto']) . '" class="table-thumbnail" alt="Foto" onclick="viewPhoto(this.src)" title="Klik untuk memperbesar">';
        } else {
            $html .= '<div class="photo-placeholder">';
            $html .= '<i class="fas fa-image"></i>';
            $html .= '</div>';
        }
        $html .= '</td>';
        
        // === KODE ASET ===
        $html .= "<td class='td-center'><span class='kode-badge'>$kodeAset</span></td>";
        
        // === BARANG (Nama + Merk) ===
        $html .= "<td class='td-barang'>";
        $html .= "<div class='barang-nama'>$jenisBarang</div>";
        if ($merk) {
            $html .= "<div class='barang-merk'><i class='fas fa-tag'></i> $merk</div>";
        }
        $html .= "<div class='barang-status'><span class='status-badge $statusClass'>$statusText</span></div>";
        $html .= "</td>";
        
        // === SPESIFIKASI ===
        $html .= "<td class='td-spek'>";
        $spekShort = substr($spesifikasi, 0, 80);
        if (strlen($spesifikasi) > 80) {
            $spekShort .= '...';
        }
        $html .= $spekShort;
        $html .= "</td>";
        
        // === HARGA ===
        $html .= "<td class='td-harga'>Rp $hargaPerolehan</td>";
        
        // === LOKASI ===
        $html .= "<td class='td-lokasi'><i class='fas fa-map-marker-alt'></i> $lokasiKantor</td>";
        
        // === AKSI ===
        $html .= "<td class='td-center'>";
        $html .= "<div class='action-dropdown'>";
        $html .= "<button type='button' class='action-btn' onclick='toggleActionMenu(event, this)' title='Menu Aksi'>";
        $html .= "<i class='fas fa-ellipsis-v'></i>";
        $html .= "</button>";
        $html .= "<div class='action-menu'>";
        
        $html .= "<div class='action-menu-item detail' onclick=\"viewDetail($id)\">";
        $html .= "<i class='fas fa-eye'></i><span>Detail</span>";
        $html .= "</div>";
        
        if ($canAddEdit) {
            $html .= "<div class='action-menu-item edit' onclick=\"editAsset($id)\">";
            $html .= "<i class='fas fa-edit'></i><span>Edit</span>";
            $html .= "</div>";
            
            $html .= "<div class='action-menu-item delete' onclick=\"deleteAsset($id, '" . addslashes($jenisBarang) . "')\">";
            $html .= "<i class='fas fa-trash-alt'></i><span>Hapus</span>";
            $html .= "</div>";
        }
        
        $html .= "</div>";
        $html .= "</div>";
        $html .= "</td>";
        $html .= "</tr>";
        
        $no++;
    }
} else {
    $html = "<tr>";
    $html .= "<td colspan='8' class='td-empty'>";
    $html .= "<div class='empty-state'>";
    $html .= "<i class='fas fa-inbox'></i>";
    $html .= "<p class='empty-title'>Tidak ada data</p>";
    $html .= "<p class='empty-desc'>Silakan tambahkan data inventaris atau sesuaikan filter pencarian.</p>";
    $html .= "</div>";
    $html .= "</td>";
    $html .= "</tr>";
}

$stmt->close();
$conn->close();

// Return JSON response
header('Content-Type: application/json');
echo json_encode([
    'html' => $html,
    'total' => $totalRows,
    'total_pages' => $totalPages,
    'current_page' => $page,
    'per_page' => $perPage
]);