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

$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,
    '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['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="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="exportData('inventory_transaction', getFilters())" style="display: block; width: 100%; padding: 8px 12px; text-align: left; border: none; background: none; cursor: pointer;">Excel (.xlsx)</button>
                    <button onclick="exportToCSV('inventory_transaction', getFilters())" 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('inventory_transaction', 'xlsx')" style="display: block; width: 100%; padding: 8px 12px; text-align: left; border: none; background: none; cursor: pointer;">Excel (.xlsx)</button>
                    <button onclick="showImportModal('inventory_transaction', '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>
    </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">
                <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>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="10" 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['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>

<script>
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/export.php?' + params.toString() + '&type=transactions';
}

function getFilters() {
    return {
        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 || ''
    };
}
</script>

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