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

$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="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('grv', getFilters())" style="display: block; width: 100%; padding: 8px 12px; text-align: left; border: none; background: none; cursor: pointer;">Excel (.xlsx)</button>
                    <button onclick="exportToCSV('grv', 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('grv', 'xlsx')" style="display: block; width: 100%; padding: 8px 12px; text-align: left; border: none; background: none; cursor: pointer;">Excel (.xlsx)</button>
                    <button onclick="showImportModal('grv', '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">
                <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</th>
                        <th>Tax Total Incl</th>
                        <th>Invoice</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($grvRecords)): ?>
                    <tr><td colspan="12" 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['Tax'] ?? 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>

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

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