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

$pageTitle = 'Orders';
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,
    'supplier' => $_GET['supplier'] ?? null,
    'status' => $_GET['status'] ?? null
];

$pdo = getDBConnection();
$sql = "SELECT o.*, 
        (SELECT SUM(Quantity_Received) FROM grv WHERE Order_No = o.Reference) as Quantity_Received,
        (SELECT MAX(GRV_Date) FROM grv WHERE Order_No = o.Reference) as GRV_Date,
        CASE WHEN o.PO_DateApproved IS NULL THEN 'Pending'
             WHEN (SELECT COUNT(*) FROM grv WHERE Order_No = o.Reference) = 0 THEN 'Approved'
             WHEN (SELECT SUM(Quantity_Received) FROM grv WHERE Order_No = o.Reference) >= o.Quantity THEN 'Received'
             ELSE 'Partial' END as Status
        FROM orders o
        WHERE 1=1";
$params = [];

if (!empty($filters['start_date'])) {
    $sql .= " AND o.PO_Date >= ?";
    $params[] = $filters['start_date'];
}
if (!empty($filters['end_date'])) {
    $sql .= " AND o.PO_Date <= ?";
    $params[] = $filters['end_date'];
}
if (!empty($filters['supplier'])) {
    $sql .= " AND o.Supplier = ?";
    $params[] = $filters['supplier'];
}
    if (!empty($filters['status'])) {
    $status = $filters['status'];
    if ($status === 'Pending') {
        $sql .= " AND o.PO_DateApproved IS NULL";
    } elseif ($status === 'Approved') {
        $sql .= " AND o.PO_DateApproved IS NOT NULL AND (SELECT COUNT(*) FROM grv WHERE Order_No = o.Reference) = 0";
    } elseif ($status === 'Partial') {
        $sql .= " AND (SELECT COUNT(*) FROM grv WHERE Order_No = o.Reference) > 0 AND (SELECT SUM(Quantity_Received) FROM grv WHERE Order_No = o.Reference) < o.Quantity";
    } elseif ($status === 'Received') {
        $sql .= " AND (SELECT SUM(Quantity_Received) FROM grv WHERE Order_No = o.Reference) >= o.Quantity";
    }
}

$sql .= " ORDER BY o.PO_Date DESC, o.OrderID DESC LIMIT 500";

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

<div class="card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Orders</h5>
        <div class="btn-group">
            <button class="btn btn-sm btn-outline-success" onclick="exportOrders()">
                <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="supplier" class="form-control" placeholder="Supplier" value="<?php echo sanitize($filters['supplier'] ?? ''); ?>">
            </div>
            <div class="col-md-2">
                <select name="status" class="form-select">
                    <option value="">All Status</option>
                    <option value="Pending" <?php echo $filters['status'] === 'Pending' ? 'selected' : ''; ?>>Pending</option>
                    <option value="Approved" <?php echo $filters['status'] === 'Approved' ? 'selected' : ''; ?>>Approved</option>
                    <option value="Partial" <?php echo $filters['status'] === 'Partial' ? 'selected' : ''; ?>>Partial</option>
                    <option value="Received" <?php echo $filters['status'] === 'Received' ? 'selected' : ''; ?>>Received</option>
                </select>
            </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="orders.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>Order ID</th>
                        <th>Item</th>
                        <th>Description</th>
                        <th>Ordered Qty</th>
                        <th>Received Qty</th>
                        <th>Unit Price</th>
                        <th>Supplier</th>
                        <th>PO Date</th>
                        <th>Approved Date</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($orders)): ?>
                    <tr><td colspan="10" class="text-center text-muted">No orders found</td></tr>
                    <?php else: ?>
                        <?php foreach ($orders as $o): ?>
                        <tr>
                            <td><?php echo $o['OrderID']; ?></td>
                            <td><?php echo sanitize($o['ItemCode']); ?></td>
                            <td><?php echo sanitize($o['ItemDescription'] ?? '-'); ?></td>
                            <td class="text-end"><?php echo number_format($o['Quantity'], 2); ?></td>
                            <td class="text-end"><?php echo number_format($o['Quantity_Received'] ?? 0, 2); ?></td>
                            <td class="text-end"><?php echo number_format($o['UnitPrice'], 2); ?></td>
                            <td><?php echo sanitize($o['Supplier']); ?></td>
                            <td><?php echo $o['PO_Date']; ?></td>
                            <td><?php echo $o['PO_DateApproved'] ?? '-'; ?></td>
                            <td>
                                <?php 
                                $statusClass = [
                                    'Pending' => 'badge-warning',
                                    'Approved' => 'badge-info',
                                    'Partial' => 'badge-primary',
                                    'Received' => 'badge-success'
                                ][$o['Status']] ?? 'badge-secondary';
                                ?>
                                <span class="badge <?php echo $statusClass; ?>"><?php echo $o['Status']; ?></span>
                            </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 Orders</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 orders 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="importOrders()">Import</button>
        </div>
    </div>
</div>

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

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

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

async function importOrders() {
    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/orders-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'; ?>