<?php
require_once __DIR__ . '/../config.php';
requireRole(['admin']);

$pageTitle = 'Inventory Transactions';
require_once __DIR__ . '/../includes/admin-header.php';

require_once __DIR__ . '/../lib/logic.php';

$filters = [
    'start_date' => $_GET['start_date'] ?? null,
    'end_date' => $_GET['end_date'] ?? null,
    'item_code' => $_GET['item_code'] ?? null,
    'source_type' => $_GET['source_type'] ?? null,
    'trans_type' => $_GET['trans_type'] ?? null
];

$pdo = getDBConnection();
$sql = "SELECT * FROM inventory_transaction WHERE 1=1";
$params = [];

if (!empty($filters['start_date'])) {
    $sql .= " AND transaction_date >= ?";
    $params[] = $filters['start_date'];
}
if (!empty($filters['end_date'])) {
    $sql .= " AND transaction_date <= ?";
    $params[] = $filters['end_date'];
}
if (!empty($filters['item_code'])) {
    $sql .= " AND item_code = ?";
    $params[] = $filters['item_code'];
}
if (!empty($filters['source_type'])) {
    $sql .= " AND source_type = ?";
    $params[] = $filters['source_type'];
}
if (!empty($filters['trans_type'])) {
    $sql .= " AND trans_type = ?";
    $params[] = $filters['trans_type'];
}

$sql .= " ORDER BY transaction_date DESC, id DESC LIMIT 500";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$transactions = $stmt->fetchAll();
?>

<div class="card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Inventory Transactions</h5>
        <div class="btn-group">
            <button class="btn btn-sm btn-outline-success" onclick="exportTransactions()">
                <i class="bi bi-download"></i> Export XLSX
            </button>
            <button class="btn btn-sm btn-outline-primary" onclick="showImportModal()">
                <i class="bi bi-upload"></i> Import
            </button>
        </div>
    </div>
    <div class="card-body">
        <form method="get" class="row g-3 mb-3">
            <div class="col-md-2">
                <input type="date" name="start_date" class="form-control" placeholder="Start Date" value="<?php echo $filters['start_date']; ?>">
            </div>
            <div class="col-md-2">
                <input type="date" name="end_date" class="form-control" placeholder="End Date" value="<?php echo $filters['end_date']; ?>">
            </div>
            <div class="col-md-2">
                <input type="text" name="item_code" class="form-control" placeholder="Item Code" value="<?php echo sanitize($filters['item_code'] ?? ''); ?>">
            </div>
            <div class="col-md-2">
                <select name="source_type" class="form-select">
                    <option value="">All Categories</option>
                    <option value="Chemical" <?php echo $filters['source_type'] === 'Chemical' ? 'selected' : ''; ?>>Chemical</option>
                    <option value="Consumable" <?php echo $filters['source_type'] === 'Consumable' ? 'selected' : ''; ?>>Consumable</option>
                    <option value="Feed" <?php echo $filters['source_type'] === 'Feed' ? 'selected' : ''; ?>>Feed</option>
                    <option value="Fuel" <?php echo $filters['source_type'] === 'Fuel' ? 'selected' : ''; ?>>Fuel</option>
                </select>
            </div>
            <div class="col-md-2">
                <select name="trans_type" class="form-select">
                    <option value="">All Types</option>
                    <option value="Purchase" <?php echo $filters['trans_type'] === 'Purchase' ? 'selected' : ''; ?>>Purchase</option>
                    <option value="Usage" <?php echo $filters['trans_type'] === 'Usage' ? 'selected' : ''; ?>>Usage</option>
                    <option value="Adjustment" <?php echo $filters['trans_type'] === 'Adjustment' ? 'selected' : ''; ?>>Adjustment</option>
                    <option value="Transfer" <?php echo $filters['trans_type'] === 'Transfer' ? 'selected' : ''; ?>>Transfer</option>
                    <option value="Return" <?php echo $filters['trans_type'] === 'Return' ? 'selected' : ''; ?>>Return</option>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100">Filter</button>
            </div>
        </form>

        <div class="table-responsive">
            <table class="table table-sm table-striped">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Date</th>
                        <th>Item Code</th>
                        <th>Description</th>
                        <th>Category</th>
                        <th>Type</th>
                        <th>In</th>
                        <th>Out</th>
                        <th>Unit Cost</th>
                        <th>Warehouse</th>
                        <th>Reference</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($transactions)): ?>
                    <tr><td colspan="11" class="text-center text-muted">No transactions found</td></tr>
                    <?php else: ?>
                        <?php foreach ($transactions as $t): ?>
                        <tr>
                            <td><?php echo $t['id']; ?></td>
                            <td><?php echo $t['transaction_date']; ?></td>
                            <td><?php echo sanitize($t['item_code']); ?></td>
                            <td><?php echo sanitize($t['item_description'] ?? '-'); ?></td>
                            <td><?php echo sanitize($t['source_type']); ?></td>
                            <td><?php echo sanitize($t['trans_type']); ?></td>
                            <td class="text-success"><?php echo $t['quantity_in'] > 0 ? number_format($t['quantity_in'], 2) : '-'; ?></td>
                            <td class="text-danger"><?php echo $t['quantity_out'] > 0 ? number_format($t['quantity_out'], 2) : '-'; ?></td>
                            <td><?php echo number_format($t['unit_cost'], 2); ?></td>
                            <td><?php echo sanitize($t['warehouse'] ?? '-'); ?></td>
                            <td><?php echo sanitize($t['reference'] ?? '-'); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal-overlay" id="importModal">
    <div class="modal">
        <div class="modal-header">
            <h3 class="modal-title">Import Inventory Transactions</h3>
            <button type="button" class="modal-close" onclick="closeModal('importModal')">&times;</button>
        </div>
        <div class="modal-body">
            <form id="importForm" enctype="multipart/form-data">
                <div class="form-group">
                    <label class="form-label">Select XLSX File</label>
                    <input type="file" name="file" class="form-control" accept=".xlsx" required>
                    <div class="form-hint">File must be in XLSX format with columns matching the inventory transaction table.</div>
                </div>
                <div class="form-group">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="dryRun" name="dry_run" value="1" checked>
                        <label class="form-check-label" for="dryRun">Dry Run (preview only)</label>
                    </div>
                </div>
                <div id="importResult"></div>
            </form>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" onclick="closeModal('importModal')">Close</button>
            <button type="button" class="btn btn-primary" onclick="importTransactions()">Import</button>
        </div>
    </div>
</div>

<script>
function showImportModal() {
    document.getElementById('importModal').classList.add('show');
}

function closeModal(modalId) {
    document.getElementById(modalId).classList.remove('show');
}

function exportTransactions() {
    const params = new URLSearchParams({
        start_date: document.querySelector('input[name="start_date"]').value,
        end_date: document.querySelector('input[name="end_date"]').value,
        item_code: document.querySelector('input[name="item_code"]').value,
        source_type: document.querySelector('select[name="source_type"]').value,
        trans_type: document.querySelector('select[name="trans_type"]').value
    });
    window.location.href = '../api/transactions-export.php?' + params.toString();
}

async function importTransactions() {
    const form = document.getElementById('importForm');
    const formData = new FormData(form);
    const resultDiv = document.getElementById('importResult');
    
    resultDiv.innerHTML = '<div class="alert alert-info">Processing...</div>';
    
    try {
        const response = await fetch('../api/transactions-import.php', {
            method: 'POST',
            body: formData
        });
        const result = await response.json();
        
        if (result.error) {
            resultDiv.innerHTML = '<div class="alert alert-danger">' + result.error + '</div>';
            return;
        }
        
        let html = '<div class="alert alert-' + (result.errors?.length ? 'warning' : 'success') + '">';
        html += '<strong>' + result.message + '</strong><br>';
        html += 'Imported: ' + (result.imported || result.would_import || 0);
        html += ', Skipped: ' + (result.skipped || result.would_skip || 0);
        if (result.errors?.length) {
            html += '<hr><strong>Errors:</strong><ul class="mb-0">';
            result.errors.slice(0, 5).forEach(e => html += '<li>' + e + '</li>');
            if (result.errors.length > 5) html += '<li>...and ' + (result.errors.length - 5) + ' more</li>';
            html += '</ul>';
        }
        html += '</div>';
        resultDiv.innerHTML = html;
        
        if (!form.dry_run.checked && !result.errors?.length) {
            setTimeout(() => location.reload(), 2000);
        }
    } catch (e) {
        resultDiv.innerHTML = '<div class="alert alert-danger">Error: ' + e.message + '</div>';
    }
}
</script>

require_once __DIR__ . '/../includes/admin-footer.php';
