<?php
require_once __DIR__ . '/../config.php';
requireLogin();

$pageTitle = 'Inventory Valuation';
include __DIR__ . '/../includes/admin-header.php';
?>

        <div class="row g-4 mb-4">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">Inventory Valuations</h5>
                            <div class="d-flex gap-2">
                                <div class="dropdown-container" style="position: relative;">
                                    <button class="btn btn-sm btn-outline-success dropdown-toggle" onclick="toggleExportDropdown(this)">
                                        <i class="bi bi-download"></i> Export
                                    </button>
                                    <div class="export-dropdown hidden" style="position: absolute; right: 0; top: 100%; margin-top: 4px; background: white; border: 1px solid #ddd; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.15); z-index: 100; min-width: 140px;">
                                        <button onclick="exportValuation()" style="display: block; width: 100%; padding: 8px 12px; text-align: left; border: none; background: none; cursor: pointer;">Excel (.xlsx)</button>
                                        <button onclick="exportValuationCSV()" style="display: block; width: 100%; padding: 8px 12px; text-align: left; border: none; background: none; cursor: pointer; border-top: 1px solid #eee;">CSV (.csv)</button>
                                    </div>
                                </div>
                                <div class="dropdown-container" style="position: relative;">
                                    <button class="btn btn-sm btn-outline-primary dropdown-toggle" onclick="toggleImportDropdown(this)">
                                        <i class="bi bi-upload"></i> Import
                                    </button>
                                    <div class="import-dropdown hidden" style="position: absolute; right: 0; top: 100%; margin-top: 4px; background: white; border: 1px solid #ddd; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.15); z-index: 100; min-width: 140px;">
                                        <button onclick="showImportModal('valuation', 'xlsx')" style="display: block; width: 100%; padding: 8px 12px; text-align: left; border: none; background: none; cursor: pointer;">Excel (.xlsx)</button>
                                        <button onclick="showImportModal('valuation', 'csv')" style="display: block; width: 100%; padding: 8px 12px; text-align: left; border: none; background: none; cursor: pointer; border-top: 1px solid #eee;">CSV (.csv)</button>
                                    </div>
                                </div>
                                <div class="input-group" style="width: auto;">
                                    <input type="date" class="form-control form-control-sm" id="valuationDate" value="<?php echo date('Y-m-d'); ?>">
                                    <button class="btn btn-sm btn-outline-secondary" onclick="loadValuation()">Load</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card-body">
                        <div class="table-responsive table-container">
                            <table class="table table-sm table-striped table-hover" id="valuationTable">
                                <thead class="table-light">
                                    <tr>
                                        <th>Item Code</th>
                                        <th>Item Description</th>
                                        <th>Item Group</th>
                                        <th>Group Category</th>
                                        <th>Qty</th>
                                        <th>Unit Cost</th>
                                        <th>Value</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="valuationBody">
                                    <tr><td colspan="8" class="text-center">Loading...</td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <script>
        let currentDate = '<?php echo date('Y-m-d'); ?>';

        function loadValuation() {
            currentDate = document.getElementById('valuationDate').value;
            fetch('../api/valuation.php?date=' + currentDate)
                .then(r => r.json())
                .then(response => {
                    const tbody = document.getElementById('valuationBody');
                    if (!response.data || response.data.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="8" class="text-center">No records found</td></tr>';
                        return;
                    }
                    tbody.innerHTML = response.data.map(item => {
                        return '<tr>' +
                            '<td><input type="text" class="form-control form-control-sm" name="item_code" value="' + item.ItemCode + '" style="width: 120px;"></td>' +
                            '<td><input type="text" class="form-control form-control-sm" name="item_description" value="' + (item.ItemDescription || '') + '" style="width: 200px;"></td>' +
                            '<td><input type="text" class="form-control form-control-sm" name="item_group" value="' + (item.ItemGroup || '') + '" style="width: 100px;"></td>' +
                            '<td><input type="text" class="form-control form-control-sm" name="group_category" value="' + (item.GroupCategory || '') + '" style="width: 100px;"></td>' +
                            '<td><input type="number" class="form-control form-control-sm" name="qty" value="' + item.Qty + '" style="width: 80px;"></td>' +
                            '<td><input type="number" step="0.01" class="form-control form-control-sm" name="unit_cost" value="' + item.UnitCost.toFixed(2) + '" style="width: 100px;"></td>' +
                            '<td>$' + item.Value.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}) + '</td>' +
                            '<td>' +
                                '<input type="hidden" name="id" value="' + item.id + '">' +
                                '<input type="hidden" name="valuation_date" value="' + item.ValuationDate + '">' +
                                '<button class="btn btn-sm btn-outline-primary" onclick="updateValuation(this)">Update</button>' +
                            '</td>' +
                        '</tr>';
                    }).join('');
                });
        }

        function updateValuation(btn) {
            const row = btn.closest('tr');
            const formData = new FormData();
            formData.append('action', 'update');
            formData.append('id', row.querySelector('input[name="id"]').value);
            formData.append('item_code', row.querySelector('input[name="item_code"]').value);
            formData.append('item_description', row.querySelector('input[name="item_description"]').value);
            formData.append('item_group', row.querySelector('input[name="item_group"]').value);
            formData.append('group_category', row.querySelector('input[name="group_category"]').value);
            formData.append('qty', row.querySelector('input[name="qty"]').value);
            formData.append('unit_cost', row.querySelector('input[name="unit_cost"]').value);
            formData.append('valuation_date', row.querySelector('input[name="valuation_date"]').value);

            fetch('../api/valuation.php', {
                method: 'POST',
                body: formData
            })
            .then(r => r.json())
            .then(response => {
                if (response.success) {
                    loadValuation();
                } else {
                    alert('Error: ' + (response.error || 'Failed to update'));
                }
            });
        }

        function exportValuation() {
            window.location.href = '../api/export_import.php?type=valuation&format=xlsx&date=' + currentDate;
        }

        function exportValuationCSV() {
            window.location.href = '../api/export_import.php?type=valuation&format=csv&date=' + currentDate;
        }

        document.getElementById('valuationDate').addEventListener('change', loadValuation);
        loadValuation();
        </script>

<?php include __DIR__ . '/../includes/admin-footer.php'; ?>