<?php
// Start session
session_start();

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

// Redirect if not admin - using functions from connection.php
if (!is_logged_in() || !is_user_type('admin')) {
    header("Location: ../login.php");
    exit();
}

// Get admin data
$admin_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM admin_users WHERE id = ?");
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$admin_data = $stmt->get_result()->fetch_assoc();
$stmt->close();

// Check if account is active, redirect to logout if not
if ($admin_data['status'] == 'nonactive') {
    // Log this attempt
    error_log("Nonactive admin attempted to access color data: " . $_SESSION['username']);
    
    // Clear all session variables
    $_SESSION = array();
    
    // Destroy the session
    session_destroy();
    
    // Redirect to login with message
    header("Location: ../login.php?error=inactive");
    exit();
}

// Set page title
$page_title = "Data Color Panel";

// Log activity
log_activity($conn, $admin_id, 'admin', 'Color Data Access', 'Admin accessed color data page');

// Get all buyers for filter
$buyer_query = "SELECT id, nama_buyer FROM buyers ORDER BY nama_buyer";
$buyer_result = $conn->query($buyer_query);

// Get all components for filter
$component_query = "SELECT id, component_name FROM color_components ORDER BY component_name";
$component_result = $conn->query($component_query);

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

<!-- Main Content Area -->
<main class="flex-1 p-6 overflow-auto bg-gradient-to-br from-blue-100 via-teal-100 to-green-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">Data Color Panel</h2>
        <p class="text-gray-600">Kelola dan lihat data warna dan komponennya</p>
    </div>
    
    <!-- Filters Section -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold text-gray-700">Filter Data</h3>
            <button id="filter_help" class="bg-blue-100 hover:bg-blue-200 text-blue-700 font-medium py-1 px-3 rounded-md transition duration-150 ease-in-out flex items-center">
                <i class="fas fa-question-circle mr-2"></i>Petunjuk Filter
            </button>
        </div>
        
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <!-- Buyer Filter -->
            <div>
                <label for="buyer_filter" class="block text-sm font-medium text-gray-700 mb-1">Buyer</label>
                <select id="buyer_filter" class="w-full rounded-md border border-gray-300 shadow-sm px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    <option value="">Semua Buyer</option>
                    <?php while ($buyer = $buyer_result->fetch_assoc()): ?>
                        <option value="<?php echo $buyer['id']; ?>"><?php echo htmlspecialchars($buyer['nama_buyer']); ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            
            <!-- Color Code Filter -->
            <div>
                <label for="color_filter" class="block text-sm font-medium text-gray-700 mb-1">Kode Warna</label>
                <select id="color_filter" class="w-full rounded-md border border-gray-300 shadow-sm px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500" disabled>
                    <option value="">Pilih Buyer Terlebih Dahulu</option>
                </select>
            </div>
            
            <!-- Component Filter -->
            <div>
                <label for="component_filter" class="block text-sm font-medium text-gray-700 mb-1">Component</label>
                <select id="component_filter" class="w-full rounded-md border border-gray-300 shadow-sm px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500" disabled>
                    <option value="">Pilih Color Code Terlebih Dahulu</option>
                </select>
            </div>
            
            <!-- Status Filter - Updated with new status options -->
            <div>
                <label for="status_filter" class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                <select id="status_filter" class="w-full rounded-md border border-gray-300 shadow-sm px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    <option value="">Semua Status</option>
                    <option value="Tersedia">Tersedia</option>
                    <option value="Dipinjam">Dipinjam</option>
                    <option value="Rusak">Rusak</option>
                    <option value="Expired">Expired</option>
                    <option value="Renew">Renew</option>
                    <option value="Hilang">Hilang</option>
                </select>
            </div>
        </div>
        
        <!-- Apply and Reset Filters Button -->
        <div class="mt-4 flex space-x-2">
            <button id="apply_filters" class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-md transition duration-150 ease-in-out">
                <i class="fas fa-filter mr-2"></i>Terapkan Filter
            </button>
            <button id="reset_filters" class="bg-gray-500 hover:bg-gray-600 text-white font-medium py-2 px-4 rounded-md transition duration-150 ease-in-out">
                <i class="fas fa-undo mr-2"></i>Reset Filter
            </button>
        </div>
    </div>
    
    <!-- Color Data Grid -->
    <div class="bg-white rounded-lg shadow-md p-6">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-xl font-semibold text-gray-800">Data Color & Component</h3>
            <div id="data_count" class="bg-blue-100 text-blue-800 font-medium py-1 px-3 rounded-md">
                Loading...
            </div>
        </div>
        
        <div id="color_data_container" class="overflow-x-auto">
            <!-- Data will be loaded here via AJAX -->
            <div class="flex justify-center items-center h-40">
                <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
                <span class="ml-2 text-gray-500">Memuat data...</span>
            </div>
        </div>
    </div>
</main>

<!-- Filter Help Modal -->
<div id="filter_help_modal" class="fixed z-10 inset-0 overflow-y-auto hidden">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <div class="sm:flex sm:items-start">
                    <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-blue-100 sm:mx-0 sm:h-10 sm:w-10">
                        <i class="fas fa-info-circle text-blue-600"></i>
                    </div>
                    <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                        <h3 class="text-lg leading-6 font-medium text-gray-900">
                            Petunjuk Penggunaan Filter
                        </h3>
                        <div class="mt-2">
                            <p class="text-sm text-gray-500">
                                Untuk mempermudah pencarian, gunakan filter dengan urutan sebagai berikut:
                            </p>
                            <ul class="list-disc list-inside mt-2 text-sm text-gray-500">
                                <li>Pilih filter pembeli terlebih dahulu</li>
                                <li>Lalu pilih filter color code</li>
                                <li>Lalu pilih filter component</li>
                                <li>Baru klik tombol "Terapkan Filter" untuk mencari data sesuai yang dicari</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <button type="button" id="close_filter_help" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                    Tutup
                </button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Load initial data
    loadColorData();
    
    // Filter help modal controls
    const filterHelpButton = document.getElementById('filter_help');
    const filterHelpModal = document.getElementById('filter_help_modal');
    const closeFilterHelp = document.getElementById('close_filter_help');
    
    filterHelpButton.addEventListener('click', function() {
        filterHelpModal.classList.remove('hidden');
    });
    
    closeFilterHelp.addEventListener('click', function() {
        filterHelpModal.classList.add('hidden');
    });
    
    // Close modal when clicking outside
    filterHelpModal.addEventListener('click', function(e) {
        if (e.target === filterHelpModal) {
            filterHelpModal.classList.add('hidden');
        }
    });
    
    // Add event listeners for filter buttons
    document.getElementById('apply_filters').addEventListener('click', loadColorData);
    document.getElementById('reset_filters').addEventListener('click', function() {
        document.getElementById('buyer_filter').value = '';
        document.getElementById('color_filter').value = '';
        document.getElementById('color_filter').disabled = true;
        document.getElementById('color_filter').innerHTML = '<option value="">Pilih Buyer Terlebih Dahulu</option>';
        document.getElementById('component_filter').value = '';
        document.getElementById('component_filter').disabled = true;
        document.getElementById('component_filter').innerHTML = '<option value="">Pilih Color Code Terlebih Dahulu</option>';
        document.getElementById('status_filter').value = '';
        loadColorData();
    });
    
    // Add event listener for buyer filter change
    document.getElementById('buyer_filter').addEventListener('change', function() {
        const buyerId = this.value;
        const colorFilter = document.getElementById('color_filter');
        const componentFilter = document.getElementById('component_filter');
        
        // Reset component filter
        componentFilter.innerHTML = '<option value="">Pilih Color Code Terlebih Dahulu</option>';
        componentFilter.disabled = true;
        
        if (buyerId) {
            // Enable color filter and fetch color codes for the selected buyer
            colorFilter.disabled = false;
            colorFilter.innerHTML = '<option value="">Loading...</option>';
            
            fetch('get_color_codes_admin.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `buyer_id=${buyerId}`
            })
            .then(response => response.json())
            .then(data => {
                colorFilter.innerHTML = '<option value="">Semua Kode Warna</option>';
                data.forEach(color => {
                    const option = document.createElement('option');
                    option.value = color.id;
                    option.textContent = color.code_color + ' - ' + color.deskripsi;
                    colorFilter.appendChild(option);
                });
            })
            .catch(error => {
                colorFilter.innerHTML = '<option value="">Error loading color codes</option>';
                console.error('Error:', error);
            });
        } else {
            // Reset color filter if no buyer is selected
            colorFilter.innerHTML = '<option value="">Pilih Buyer Terlebih Dahulu</option>';
            colorFilter.disabled = true;
        }
    });
    
    // Add event listener for color filter change
    document.getElementById('color_filter').addEventListener('change', function() {
        const colorId = this.value;
        const componentFilter = document.getElementById('component_filter');
        
        if (colorId) {
            // Enable component filter and fetch components for the selected color
            componentFilter.disabled = false;
            componentFilter.innerHTML = '<option value="">Loading...</option>';
            
            fetch('get_color_components_admin.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `color_id=${colorId}`
            })
            .then(response => response.json())
            .then(data => {
                componentFilter.innerHTML = '<option value="">Semua Component</option>';
                data.forEach(component => {
                    const option = document.createElement('option');
                    option.value = component.id;
                    option.textContent = component.component_name;
                    componentFilter.appendChild(option);
                });
            })
            .catch(error => {
                componentFilter.innerHTML = '<option value="">Error loading components</option>';
                console.error('Error:', error);
            });
        } else {
            // Reset component filter if no color is selected
            componentFilter.innerHTML = '<option value="">Pilih Color Code Terlebih Dahulu</option>';
            componentFilter.disabled = true;
        }
    });
    
    // Function to load color data with filters
    function loadColorData() {
        const buyer = document.getElementById('buyer_filter').value;
        const color = document.getElementById('color_filter').value;
        const component = document.getElementById('component_filter').value;
        const status = document.getElementById('status_filter').value;
        
        const container = document.getElementById('color_data_container');
        container.innerHTML = `
            <div class="flex justify-center items-center h-40">
                <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
                <span class="ml-2 text-gray-500">Memuat data...</span>
            </div>
        `;
        
        // AJAX request to get filtered data
        fetch('get_filtered_data.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `buyer=${buyer}&color=${color}&component=${component}&status=${status}`
        })
        .then(response => response.text())
        .then(data => {
            container.innerHTML = data;
            updateDataCount();
        })
        .catch(error => {
            container.innerHTML = `<div class="text-red-500 text-center p-4">Error loading data: ${error.message}</div>`;
        });
    }
    
    // Function to update the data count display
    function updateDataCount() {
        const dataCount = document.getElementById('data_count');
        const colorItems = document.querySelectorAll('.color-item');
        const totalComponents = document.querySelectorAll('.component-row').length;
        
        dataCount.textContent = `${colorItems.length} Warna, ${totalComponents} Komponen`;
    }
});
</script>

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