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

$pageTitle = 'GRV (Goods Received)';
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,
    'order_no' => $_GET['order_no'] ?? null,
    'supplier' => $_GET['supplier'] ?? null
];

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

if (!empty($filters['start_date'])) {
    $sql .= " AND GRV_Date >= ?";
    $params[] = $filters['start_date'];
}
if (!empty($filters['end_date'])) {
    $sql .= " AND GRV_Date <= ?";
    $params[] = $filters['end_date'];
}
if (!empty($filters['order_no'])) {
    $sql .= " AND Order_No LIKE ?";
    $params[] = '%' . $filters['order_no'] . '%';
}
if (!empty($filters['supplier'])) {
    $sql .= " AND Supplier_Account LIKE ?";
    $params[] = '%' . $filters['supplier'] . '%';
}

$sql .= " ORDER BY GRV_Date DESC, GRV_ID DESC LIMIT 500";

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

<div class="card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">GRV Records</h5>
        <div class="btn-group">
            <button class="btn btn-sm btn-outline-success" onclick="exportGRV()">
                <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="order_no" class="form-control" placeholder="Order No" value="<?php echo sanitize($filters['order_no'] ?? ''); ?>">
            </div>
            <div class="col-md-2">
                <input type="text" name="supplier" class="form-control" placeholder="Supplier" value="<?php echo sanitize($filters['supplier'] ?? ''); ?>">
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100">Filter</button>
            </div>
            <div class="col-md-2">
                <a href="grv.php" class="btn btn-outline-secondary w-100">Clear</a>
            </div>
        </form>

        <div class="table-responsive">
            <table class="table table-sm table-striped">
                <thead>
                    <tr>
                        <th>GRV ID</th>
                        <th>GRV Date</th>
                        <th>Order No</th>
                        <th>Supplier</th>
                        <th>Item Code</th>
                        <th>Description</th>
                        <th>Ordered Qty</th>
                        <th>Received Qty</th>
                        <th>Unit Price</th>
                        <th>Tax Total</th>
                        <th>Invoice</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($grvRecords)): ?>
                    <tr><td colspan="11" class="text-center text-muted">No GRV records found</td></tr>
                    <?php else: ?>
                        <?php foreach ($grvRecords as $g): ?>
                        <tr>
                            <td><?php echo $g['GRV_ID']; ?></td>
                            <td><?php echo $g['GRV_Date']; ?></td>
                            <td><?php echo sanitize($g['Order_No']); ?></td>
                            <td><?php echo sanitize($g['Supplier_Account'] ?? '-'); ?></td>
                            <td><?php echo sanitize($g['Item_Code']); ?></td>
                            <td><?php echo sanitize($g['Item_Description'] ?? '-'); ?></td>
                            <td class="text-end"><?php echo number_format($g['Ordered_Qty'] ?? 0, 2); ?></td>
                            <td class="text-end"><?php echo number_format($g['Quantity_Received'] ?? 0, 2); ?></td>
                            <td class="text-end"><?php echo number_format($g['Unit_Price'] ?? 0, 2); ?></td>
                            <td class="text-end"><?php echo number_format($g['TaxTotal_Incl'] ?? 0, 2); ?></td>
                            <td><?php echo sanitize($g['Supplier_Invoice'] ?? '-'); ?></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 GRV</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: Order_No, GRV_Date (required), and other matching GRV columns.</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="importGRV()">Import</button>
        </div>
    </div>
</div>

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

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

function exportGRV() {
    const params = new URLSearchParams({
        start_date: document.querySelector('input[name="start_date"]').value,
        end_date: document.querySelector('input[name="end_date"]').value,
        order_no: document.querySelector('input[name="order_no"]').value,
        supplier: document.querySelector('input[name="supplier"]').value
    });
    window.location.href = '../api/grv-export.php?' + params.toString();
}

async function importGRV() {
    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/grv-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>

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