<?php
// Start session
session_start();

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

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

// Get IT user data
$it_id = $_SESSION['user_id'];

// Set page title
$page_title = "Kelola Component Panel";

// Log activity using audit_logs
create_audit_log($conn, 'Component Panel Access', $it_id, 'it', 'IT user accessed component panel management');

// Get filter parameters
$filter_buyer = isset($_GET['buyer_id']) ? $_GET['buyer_id'] : '';
$search_color = isset($_GET['search_color']) ? $_GET['search_color'] : '';

// Get buyers for filter dropdown
$buyers_query = "SELECT id, nama_buyer, kode_buyer FROM buyers ORDER BY nama_buyer";
$buyers_result = $conn->query($buyers_query);

// Include header
include '../template_it/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">Kelola Component Panel</h2>
        <p class="text-gray-600">Kelola stock components untuk setiap color panel, tambah atau hapus stock items</p>
    </div>

    <!-- Filter Section -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">Filter & Pencarian</h3>
        
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <!-- Filter Buyer -->
            <div>
                <label for="filter_buyer" class="block text-sm font-medium text-gray-700 mb-2">Filter Buyer</label>
                <select id="filter_buyer" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">Semua Buyer</option>
                    <?php 
                    $buyers_result->data_seek(0);
                    while($buyer_row = $buyers_result->fetch_assoc()): 
                    ?>
                        <option value="<?php echo $buyer_row['id']; ?>" 
                                <?php echo ($filter_buyer == $buyer_row['id']) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($buyer_row['nama_buyer'] . ' (' . $buyer_row['kode_buyer'] . ')'); ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>

            <!-- Search Color -->
            <div>
                <label for="search_color" class="block text-sm font-medium text-gray-700 mb-2">Cari Color Code</label>
                <input type="text" id="search_color" placeholder="Masukkan kode color..." 
                       value="<?php echo htmlspecialchars($search_color); ?>"
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <!-- Action Buttons -->
            <div class="flex items-end space-x-2">
                <button onclick="applyFilters()" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors">
                    <i class="fas fa-search mr-2"></i>Filter
                </button>
                <button onclick="resetFilters()" 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>

    <!-- Color Panels -->
    <div id="color-panels-container">
        <!-- Color panels will be loaded here -->
        <div class="flex justify-center items-center p-8">
            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            <span class="ml-2 text-gray-600">Memuat data...</span>
        </div>
    </div>
</main>

<!-- Add Component Modal -->
<div id="addComponentModal" 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-md w-full">
            <div class="p-4 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800">Tambah Component Baru</h3>
            </div>
            <form id="addComponentForm">
                <div class="p-4 space-y-4">
                    <input type="hidden" id="modal_color_id" name="color_id">
                    
                    <div>
                        <label for="component_id" class="block text-sm font-medium text-gray-700 mb-2">Pilih Component</label>
                        <select id="component_id" name="component_id" required class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">Pilih Component</option>
                        </select>
                    </div>
                    
                    <div>
                        <label for="quantity" class="block text-sm font-medium text-gray-700 mb-2">Jumlah Stock</label>
                        <input type="number" id="quantity" name="quantity" min="1" required 
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>
                <div class="p-4 border-t border-gray-200 flex justify-end space-x-2">
                    <button type="button" onclick="closeAddComponentModal()" class="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 transition-colors">
                        Batal
                    </button>
                    <button type="submit" class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors">
                        Tambah Component
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add Stock Modal -->
<div id="addStockModal" 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-md w-full">
            <div class="p-4 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800">Tambah Stock Item</h3>
            </div>
            <form id="addStockForm">
                <div class="p-4 space-y-4">
                    <input type="hidden" id="stock_color_id" name="color_id">
                    <input type="hidden" id="stock_component_id" name="component_id">
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Component</label>
                        <div id="stock_component_name" class="px-3 py-2 bg-gray-100 border border-gray-300 rounded-md text-gray-700"></div>
                    </div>
                    
                    <div>
                        <label for="stock_quantity" class="block text-sm font-medium text-gray-700 mb-2">Jumlah Stock yang Ditambah</label>
                        <input type="number" id="stock_quantity" name="quantity" min="1" required 
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label for="tanggal_pembuatan" class="block text-sm font-medium text-gray-700 mb-2">Tanggal Pembuatan</label>
                        <input type="date" id="tanggal_pembuatan" name="tanggal_pembuatan" required 
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label for="tanggal_kedaluwarsa" class="block text-sm font-medium text-gray-700 mb-2">Tanggal Kedaluwarsa</label>
                        <input type="date" id="tanggal_kedaluwarsa" name="tanggal_kedaluwarsa" required 
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label for="keterangan" class="block text-sm font-medium text-gray-700 mb-2">Keterangan</label>
                        <textarea id="keterangan" name="keterangan" rows="3" 
                                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                    </div>
                </div>
                <div class="p-4 border-t border-gray-200 flex justify-end space-x-2">
                    <button type="button" onclick="closeAddStockModal()" class="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 transition-colors">
                        Batal
                    </button>
                    <button type="submit" class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors">
                        Tambah Stock
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Load data on page load
document.addEventListener('DOMContentLoaded', function() {
    loadColorPanels();
    loadAvailableComponents();
    
    // Set default dates
    const today = new Date().toISOString().split('T')[0];
    document.getElementById('tanggal_pembuatan').value = today;
    
    // Set default expiry date (6 months from today)
    const expiryDate = new Date();
    expiryDate.setMonth(expiryDate.getMonth() + 6);
    document.getElementById('tanggal_kedaluwarsa').value = expiryDate.toISOString().split('T')[0];
});

// Real-time search for color
let searchTimeout;
document.getElementById('search_color').addEventListener('input', function() {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(function() {
        loadColorPanels();
    }, 500);
});

// Load color panels with AJAX
function loadColorPanels() {
    const buyerId = document.getElementById('filter_buyer').value;
    const searchColor = document.getElementById('search_color').value;
    
    const params = new URLSearchParams();
    if (buyerId) params.append('buyer_id', buyerId);
    if (searchColor) params.append('search_color', searchColor);
    
    // Show loading
    document.getElementById('color-panels-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-blue-600"></div>' +
        '<span class="ml-2 text-gray-600">Memuat data...</span>' +
        '</div>';
    
    fetch('ajax_color_panels.php?' + params.toString())
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('color-panels-container').innerHTML = data.html;
            } else {
                document.getElementById('color-panels-container').innerHTML = 
                    '<div class="p-8 text-center text-red-600">Terjadi kesalahan: ' + data.message + '</div>';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('color-panels-container').innerHTML = 
                '<div class="p-8 text-center text-red-600">Terjadi kesalahan saat memuat data</div>';
        });
}

// Load available components for dropdown
function loadAvailableComponents() {
    fetch('ajax_get_components.php')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const select = document.getElementById('component_id');
                select.innerHTML = '<option value="">Pilih Component</option>';
                data.components.forEach(component => {
                    select.innerHTML += `<option value="${component.id}">${component.component_name}</option>`;
                });
            }
        })
        .catch(error => {
            console.error('Error loading components:', error);
        });
}

// Apply filters
function applyFilters() {
    loadColorPanels();
}

// Reset filters
function resetFilters() {
    document.getElementById('filter_buyer').value = '';
    document.getElementById('search_color').value = '';
    loadColorPanels();
}

// Show add component modal
function showAddComponentModal(colorId, colorCode) {
    document.getElementById('modal_color_id').value = colorId;
    document.getElementById('addComponentModal').querySelector('h3').textContent = 
        'Tambah Component Baru untuk ' + colorCode;
    document.getElementById('addComponentModal').classList.remove('hidden');
}

// Close add component modal
function closeAddComponentModal() {
    document.getElementById('addComponentModal').classList.add('hidden');
    document.getElementById('addComponentForm').reset();
}

// Show add stock modal
function showAddStockModal(colorId, componentId, componentName) {
    document.getElementById('stock_color_id').value = colorId;
    document.getElementById('stock_component_id').value = componentId;
    document.getElementById('stock_component_name').textContent = componentName;
    document.getElementById('addStockModal').classList.remove('hidden');
}

// Close add stock modal
function closeAddStockModal() {
    document.getElementById('addStockModal').classList.add('hidden');
    document.getElementById('addStockForm').reset();
    
    // Reset default dates
    const today = new Date().toISOString().split('T')[0];
    document.getElementById('tanggal_pembuatan').value = today;
    
    const expiryDate = new Date();
    expiryDate.setMonth(expiryDate.getMonth() + 6);
    document.getElementById('tanggal_kedaluwarsa').value = expiryDate.toISOString().split('T')[0];
}

// Handle add component form submission
document.getElementById('addComponentForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    fetch('ajax_add_component.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Component berhasil ditambahkan!');
            closeAddComponentModal();
            loadColorPanels();
        } else {
            alert('Error: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Terjadi kesalahan saat menambah component');
    });
});

// Handle add stock form submission
document.getElementById('addStockForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    fetch('ajax_add_stock.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Stock berhasil ditambahkan!');
            closeAddStockModal();
            loadColorPanels();
        } else {
            alert('Error: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Terjadi kesalahan saat menambah stock');
    });
});

// Delete stock item
function deleteStockItem(stockId, itemCode) {
    if (confirm('Apakah Anda yakin ingin menghapus stock item ' + itemCode + '?')) {
        fetch('ajax_delete_stock.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                stock_id: stockId
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Stock item berhasil dihapus!');
                loadColorPanels();
            } else {
                alert('Error: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Terjadi kesalahan saat menghapus stock item');
        });
    }
}

// Close modals when clicking outside
document.getElementById('addComponentModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeAddComponentModal();
    }
});

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

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