<?php
// Start session
session_start();

// Include database connection
require_once "../config/connection.php";

// Redirect if not admin user
if (!is_logged_in() || !is_user_type('admin')) {
    header("Location: ../login.php");
    exit();
}

// Get admin user data
$admin_id = $_SESSION['user_id'];

// Check if account is active
$stmt = $conn->prepare("SELECT status FROM admin_users_surabaya WHERE id = ?");
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$admin_data = $stmt->get_result()->fetch_assoc();
$stmt->close();

if ($admin_data['status'] == 'nonactive') {
    $_SESSION = array();
    session_destroy();
    header("Location: ../login.php?error=inactive");
    exit();
}

// Set page title
$page_title = "Cek Code Barang Terakhir Dipinjam";

// Log activity (if log_activity function exists)
if (function_exists('log_activity')) {
    log_activity($conn, $admin_id, 'admin', 'Code Check Access', 'Admin accessed cek code barang terakhir dipinjam');
}

// Get search parameters
$search_code = isset($_GET['search_code']) ? $_GET['search_code'] : '';

// Include header
include '../template_admin/header.php';
?>

<!-- Main Content Area -->
<main class="flex-1 p-6 overflow-auto bg-gradient-to-br from-purple-100 via-blue-100 to-indigo-100">
    <!-- Page Header -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">Cek Code Barang Terakhir Dipinjam</h2>
        <p class="text-gray-600">Cari dan lihat status terakhir peminjaman barang berdasarkan kode barang</p>
        <div class="mt-4 bg-blue-50 border border-blue-200 rounded-lg p-3">
            <div class="flex items-center">
                <i class="fas fa-info-circle text-blue-600 mr-2"></i>
                <span class="text-sm text-blue-800">Panel Admin - Akses penuh untuk monitoring semua barang</span>
            </div>
        </div>
    </div>

    <!-- Search Section -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">Pencarian Kode Barang</h3>
        
        <!-- Quick Stats -->
        <div id="quick-stats" class="grid grid-cols-4 gap-4 mb-6">
            <!-- Stats will be loaded here -->
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <!-- Search Code Barang -->
            <div>
                <label for="search_code" class="block text-sm font-medium text-gray-700 mb-2">Cari Kode Barang</label>
                <input type="text" id="search_code" placeholder="Masukkan kode barang (contoh: CP.0001)..." 
                       value="<?php echo htmlspecialchars($search_code); ?>"
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-purple-500">
                <p class="text-xs text-gray-500 mt-1">Ketik minimal 3 karakter untuk mencari</p>
            </div>

            <!-- Action Buttons -->
            <div class="flex items-end space-x-2">
                <button onclick="searchBarang()" class="px-4 py-2 bg-purple-600 text-white rounded-md hover:bg-purple-700 transition-colors">
                    <i class="fas fa-search mr-2"></i>Cari
                </button>
                <button onclick="resetSearch()" class="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 transition-colors">
                    <i class="fas fa-refresh mr-2"></i>Reset
                </button>
            </div>
        </div>
    </div>

    <!-- Result Table -->
    <div class="bg-white rounded-lg shadow-md">
        <div class="p-6 border-b border-gray-200">
            <div class="flex justify-between items-center">
                <h3 class="text-lg font-semibold text-gray-800">Data Peminjaman Barang</h3>
                <div class="flex items-center space-x-2">
                    <span class="text-sm text-gray-500">Admin Panel</span>
                    <div class="w-2 h-2 bg-green-500 rounded-full"></div>
                </div>
            </div>
        </div>
        
        <div class="overflow-x-auto">
            <div id="result-table-container">
                <!-- Table content will be loaded here -->
                <div class="flex flex-col justify-center items-center p-12 text-gray-500">
                    <i class="fas fa-search text-6xl mb-4 text-gray-300"></i>
                    <h3 class="text-lg font-medium text-gray-600 mb-2">Mulai Pencarian</h3>
                    <p class="text-center">Masukkan kode barang di atas untuk melihat riwayat peminjaman</p>
                </div>
            </div>
        </div>
        
        <!-- Pagination Container -->
        <div id="pagination-container" class="p-4 border-t border-gray-200 hidden">
            <!-- Pagination will be loaded here -->
        </div>
    </div>
</main>

<!-- Detail Modal -->
<div id="detailModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-lg max-w-4xl max-h-full overflow-auto w-full">
            <div class="p-4 border-b border-gray-200 flex justify-between items-center">
                <h3 id="modalTitle" class="text-lg font-semibold text-gray-800">Detail Peminjaman Barang</h3>
                <button onclick="closeDetailModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <div class="p-6" id="modalContent">
                <!-- Modal content will be loaded here -->
            </div>
        </div>
    </div>
</div>

<!-- Status Modal (untuk card dipinjam dan bermasalah) -->
<div id="statusModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-lg max-w-6xl max-h-[90vh] overflow-hidden w-full">
            <div class="p-4 border-b border-gray-200 flex justify-between items-center">
                <h3 id="statusModalTitle" class="text-lg font-semibold text-gray-800"></h3>
                <button onclick="closeStatusModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <div class="p-6 max-h-[75vh] overflow-y-auto" id="statusModalContent">
                <!-- Status modal content will be loaded here -->
            </div>
            <div class="p-4 border-t border-gray-200 bg-gray-50">
                <div class="flex justify-between items-center">
                    <div id="statusModalInfo" class="text-sm text-gray-600"></div>
                    <div class="flex space-x-2">
                        <button onclick="closeStatusModal()" class="px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700">
                            Tutup
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Photo Modal -->
<div id="photoModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-lg max-w-4xl max-h-full overflow-auto">
            <div class="p-4 border-b border-gray-200 flex justify-between items-center">
                <h3 id="photoModalTitle" class="text-lg font-semibold text-gray-800"></h3>
                <button onclick="closePhotoModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <div class="p-4">
                <img id="modalImage" src="" alt="" class="max-w-full h-auto">
            </div>
            <div class="p-4 border-t border-gray-200">
                <p id="modalDescription" class="text-gray-600"></p>
            </div>
        </div>
    </div>
</div>

<script>
// Current page tracking
let currentPage = 1;
let currentSearch = '';
let currentStatusType = '';

// Load stats on page load
document.addEventListener('DOMContentLoaded', function() {
    loadQuickStats();
});

// Real-time search for Code Barang
let searchTimeout;
document.getElementById('search_code').addEventListener('input', function() {
    const searchValue = this.value.trim();
    
    clearTimeout(searchTimeout);
    
    if (searchValue.length >= 3) {
        searchTimeout = setTimeout(function() {
            currentPage = 1;
            currentSearch = searchValue;
            loadBarangData();
        }, 500);
    } else if (searchValue.length === 0) {
        // Clear results when search is empty
        document.getElementById('result-table-container').innerHTML = 
            '<div class="flex flex-col justify-center items-center p-12 text-gray-500">' +
            '<i class="fas fa-search text-6xl mb-4 text-gray-300"></i>' +
            '<h3 class="text-lg font-medium text-gray-600 mb-2">Mulai Pencarian</h3>' +
            '<p class="text-center">Masukkan kode barang di atas untuk melihat riwayat peminjaman</p>' +
            '</div>';
        document.getElementById('pagination-container').classList.add('hidden');
    }
});

// Load barang data with AJAX
function loadBarangData(page = currentPage) {
    const searchCode = document.getElementById('search_code').value.trim();
    
    if (searchCode.length < 3) {
        return;
    }
    
    const params = new URLSearchParams();
    params.append('search_code', searchCode);
    params.append('page', page);
    params.append('limit', 25);
    params.append('user_type', 'admin'); // Specify admin user
    
    // Show loading
    document.getElementById('result-table-container').innerHTML = 
        '<div class="flex justify-center items-center p-8">' +
        '<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"></div>' +
        '<span class="ml-2 text-gray-600">Mencari data...</span>' +
        '</div>';
    
    fetch('ajax_cek_code_admin.php?' + params.toString())
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('result-table-container').innerHTML = data.html;
                if (data.totalPages > 1) {
                    generatePagination(data.totalPages, data.currentPage, data.totalData);
                    document.getElementById('pagination-container').classList.remove('hidden');
                } else {
                    document.getElementById('pagination-container').classList.add('hidden');
                }
                currentPage = data.currentPage;
            } else {
                document.getElementById('result-table-container').innerHTML = 
                    '<div class="p-8 text-center text-red-600">Terjadi kesalahan: ' + data.message + '</div>';
                document.getElementById('pagination-container').classList.add('hidden');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('result-table-container').innerHTML = 
                '<div class="p-8 text-center text-red-600">Terjadi kesalahan saat memuat data</div>';
            document.getElementById('pagination-container').classList.add('hidden');
        });
}

// Generate pagination HTML
function generatePagination(totalPages, currentPage, totalData) {
    if (totalPages <= 1) {
        document.getElementById('pagination-container').innerHTML = 
            '<div class="text-sm text-gray-600">Total: ' + totalData + ' data</div>';
        return;
    }
    
    let paginationHtml = '<div class="flex flex-col sm:flex-row justify-between items-center space-y-2 sm:space-y-0">';
    
    // Info text
    const startItem = ((currentPage - 1) * 25) + 1;
    const endItem = Math.min(currentPage * 25, totalData);
    paginationHtml += '<div class="text-sm text-gray-600">';
    paginationHtml += 'Menampilkan ' + startItem + ' - ' + endItem + ' dari ' + totalData + ' data';
    paginationHtml += '</div>';
    
    // Pagination buttons
    paginationHtml += '<div class="flex items-center space-x-1">';
    
    // Previous button
    if (currentPage > 1) {
        paginationHtml += '<button onclick="goToPage(' + (currentPage - 1) + ')" class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition-colors">';
        paginationHtml += '<i class="fas fa-chevron-left"></i>';
        paginationHtml += '</button>';
    }
    
    // Page numbers
    const maxVisiblePages = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
    
    if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }
    
    // First page if not visible
    if (startPage > 1) {
        paginationHtml += '<button onclick="goToPage(1)" class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition-colors">1</button>';
        if (startPage > 2) {
            paginationHtml += '<span class="px-2 text-gray-500">...</span>';
        }
    }
    
    // Visible page numbers
    for (let i = startPage; i <= endPage; i++) {
        if (i === currentPage) {
            paginationHtml += '<button class="px-3 py-1 bg-purple-600 text-white rounded">' + i + '</button>';
        } else {
            paginationHtml += '<button onclick="goToPage(' + i + ')" class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition-colors">' + i + '</button>';
        }
    }
    
    // Last page if not visible
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            paginationHtml += '<span class="px-2 text-gray-500">...</span>';
        }
        paginationHtml += '<button onclick="goToPage(' + totalPages + ')" class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition-colors">' + totalPages + '</button>';
    }
    
    // Next button
    if (currentPage < totalPages) {
        paginationHtml += '<button onclick="goToPage(' + (currentPage + 1) + ')" class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition-colors">';
        paginationHtml += '<i class="fas fa-chevron-right"></i>';
        paginationHtml += '</button>';
    }
    
    paginationHtml += '</div></div>';
    
    document.getElementById('pagination-container').innerHTML = paginationHtml;
}

// Go to specific page
function goToPage(page) {
    currentPage = page;
    loadBarangData(page);
}

// Search barang
function searchBarang() {
    const searchCode = document.getElementById('search_code').value.trim();
    if (searchCode.length < 3) {
        alert('Masukkan minimal 3 karakter untuk pencarian');
        return;
    }
    currentPage = 1;
    currentSearch = searchCode;
    loadBarangData();
}

// Reset search
function resetSearch() {
    document.getElementById('search_code').value = '';
    currentPage = 1;
    currentSearch = '';
    document.getElementById('result-table-container').innerHTML = 
        '<div class="flex flex-col justify-center items-center p-12 text-gray-500">' +
        '<i class="fas fa-search text-6xl mb-4 text-gray-300"></i>' +
        '<h3 class="text-lg font-medium text-gray-600 mb-2">Mulai Pencarian</h3>' +
        '<p class="text-center">Masukkan kode barang di atas untuk melihat riwayat peminjaman</p>' +
        '</div>';
    document.getElementById('pagination-container').classList.add('hidden');
    loadQuickStats();
}

// Load quick statistics
function loadQuickStats() {
    fetch('ajax_cek_code_admin.php?stats_only=1&user_type=admin')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.stats) {
                let statsHtml = `
                    <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <div class="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
                                    <i class="fas fa-box text-blue-600"></i>
                                </div>
                            </div>
                            <div class="ml-3">
                                <p class="text-sm font-medium text-blue-800">Total Barang</p>
                                <p class="text-2xl font-bold text-blue-900">${data.stats.total_barang}</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <div class="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
                                    <i class="fas fa-check-circle text-green-600"></i>
                                </div>
                            </div>
                            <div class="ml-3">
                                <p class="text-sm font-medium text-green-800">Tersedia</p>
                                <p class="text-2xl font-bold text-green-900">${data.stats.tersedia}</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-orange-50 border border-orange-200 rounded-lg p-4 cursor-pointer hover:bg-orange-100 transition-colors" onclick="showStatusData('dipinjam')">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <div class="w-8 h-8 bg-orange-100 rounded-full flex items-center justify-center">
                                    <i class="fas fa-hand-holding text-orange-600"></i>
                                </div>
                            </div>
                            <div class="ml-3">
                                <p class="text-sm font-medium text-orange-800">Dipinjam</p>
                                <p class="text-2xl font-bold text-orange-900">${data.stats.dipinjam}</p>
                                <p class="text-xs text-orange-600 mt-1"><i class="fas fa-mouse-pointer mr-1"></i>Klik untuk detail</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-red-50 border border-red-200 rounded-lg p-4 cursor-pointer hover:bg-red-100 transition-colors" onclick="showStatusData('bermasalah')">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <div class="w-8 h-8 bg-red-100 rounded-full flex items-center justify-center">
                                    <i class="fas fa-exclamation-triangle text-red-600"></i>
                                </div>
                            </div>
                            <div class="ml-3">
                                <p class="text-sm font-medium text-red-800">Bermasalah</p>
                                <p class="text-2xl font-bold text-red-900">${data.stats.bermasalah}</p>
                                <p class="text-xs text-red-600 mt-1"><i class="fas fa-mouse-pointer mr-1"></i>Klik untuk detail</p>
                            </div>
                        </div>
                    </div>
                `;
                document.getElementById('quick-stats').innerHTML = statsHtml;
            }
        })
        .catch(error => {
            console.error('Error loading stats:', error);
        });
}

// Show status data (untuk card dipinjam dan bermasalah)
function showStatusData(type) {
    currentStatusType = type;
    
    // Show loading
    document.getElementById('statusModalContent').innerHTML = 
        '<div class="flex justify-center items-center p-8">' +
        '<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-600"></div>' +
        '<span class="ml-2 text-gray-600">Memuat data...</span>' +
        '</div>';
    
    let title = '';
    if (type === 'dipinjam') {
        title = 'Data Barang Sedang Dipinjam';
        document.getElementById('statusModalTitle').innerHTML = '<i class="fas fa-hand-holding text-orange-600 mr-2"></i>' + title;
    } else if (type === 'bermasalah') {
        title = 'Data Barang Bermasalah';
        document.getElementById('statusModalTitle').innerHTML = '<i class="fas fa-exclamation-triangle text-red-600 mr-2"></i>' + title;
    }
    
    document.getElementById('statusModal').classList.remove('hidden');
    
    fetch('ajax_cek_code_admin.php?status_data=' + type + '&user_type=admin')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('statusModalContent').innerHTML = data.html;
                document.getElementById('statusModalInfo').textContent = `Total: ${data.total} barang`;
            } else {
                document.getElementById('statusModalContent').innerHTML = 
                    '<div class="p-8 text-center text-red-600">Terjadi kesalahan: ' + data.message + '</div>';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('statusModalContent').innerHTML = 
                '<div class="p-8 text-center text-red-600">Terjadi kesalahan saat memuat data</div>';
        });
}

// Show detail modal
function showDetail(stockItemId) {
    fetch('ajax_cek_code_admin.php?detail_id=' + stockItemId + '&user_type=admin')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('modalContent').innerHTML = data.html;
                document.getElementById('detailModal').classList.remove('hidden');
            } else {
                alert('Gagal memuat detail: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Terjadi kesalahan saat memuat detail');
        });
}
// Close modals
function closeDetailModal() {
    document.getElementById('detailModal').classList.add('hidden');
}

function closeStatusModal() {
    document.getElementById('statusModal').classList.add('hidden');
    currentStatusType = '';
}

function closePhotoModal() {
    document.getElementById('photoModal').classList.add('hidden');
}

// Show photo modal
function showPhoto(imageSrc, title, description) {
    document.getElementById('modalImage').src = imageSrc;
    document.getElementById('photoModalTitle').textContent = title;
    document.getElementById('modalDescription').textContent = description;
    document.getElementById('photoModal').classList.remove('hidden');
}
// Close modals when clicking outside
document.getElementById('detailModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeDetailModal();
    }
});

document.getElementById('statusModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeStatusModal();
    }
});

document.getElementById('photoModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closePhotoModal();
    }
});
</script>

<?php include '../template_admin/footer.php'; ?>