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

$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,
    'approved_start_date' => $_GET['approved_start_date'] ?? null,
    'approved_end_date' => $_GET['approved_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 STR_TO_DATE(o.PO_Date, '%Y/%m/%d') >= ?";
    $params[] = $filters['start_date'];
}
if (!empty($filters['end_date'])) {
    $sql .= " AND STR_TO_DATE(o.PO_Date, '%Y/%m/%d') <= ?";
    $params[] = $filters['end_date'];
}
if (!empty($filters['approved_start_date'])) {
    $sql .= " AND STR_TO_DATE(o.PO_DateApproved, '%Y/%m/%d') >= ?";
    $params[] = $filters['approved_start_date'];
}
if (!empty($filters['approved_end_date'])) {
    $sql .= " AND STR_TO_DATE(o.PO_DateApproved, '%Y/%m/%d') <= ?";
    $params[] = $filters['approved_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 OR o.PO_DateApproved = '')";
    } elseif ($status === 'Approved') {
        $sql .= " AND o.PO_DateApproved IS NOT NULL AND o.PO_DateApproved != '' 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 STR_TO_DATE(o.PO_Date, '%Y/%m/%d') 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="d-flex gap-2">
<div class="export-dropdown-container" style="position: relative;">
                <button class="btn btn-sm btn-outline-success" 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('orders', getFilters())" style="display: block; width: 100%; padding: 8px 12px; text-align: left; border: none; background: none; cursor: pointer;">Excel (.xlsx)</button>
                    <button onclick="exportToCSV('orders', 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="import-dropdown-container" style="position: relative;">
                <button class="btn btn-sm btn-outline-primary" 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;">
                    <label style="display: block; padding: 8px 12px; cursor: pointer;">
                        Excel (.xlsx)
                        <input type="file" accept=".xlsx,.xls" onchange="handleFileImport(event, 'orders')" style="display: none;">
                    </label>
                    <label style="display: block; padding: 8px 12px; cursor: pointer; border-top: 1px solid #eee;">
                        CSV (.csv)
                        <input type="file" accept=".csv" onchange="handleFileImport(event, 'orders')" style="display: none;">
                    </label>
                </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 htmlspecialchars($filters['start_date'] ?? ''); ?>">
            </div>
            <div class="col-md-2">
                <input type="date" name="end_date" class="form-control" placeholder="End Date" value="<?php echo htmlspecialchars($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'] ?? 0, 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'] ?? 0, 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>

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

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