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

$pageTitle = 'Procurement Dashboard';
require_once __DIR__ . '/../includes/admin-header.php';

require_once __DIR__ . '/../lib/logic.php';

$pdo = getDBConnection();

$statusFilter = $_GET['status'] ?? '';
$supplierFilter = $_GET['supplier'] ?? '';
$startDate = $_GET['start_date'] ?? '';
$endDate = $_GET['end_date'] ?? '';
$searchTerm = $_GET['search'] ?? '';

$sql = "SELECT * FROM orders WHERE 1=1";
$params = [];

if (!empty($statusFilter)) {
    if ($statusFilter === 'pending') {
        $sql .= " AND PO_DateApproved IS NULL";
    } elseif ($statusFilter === 'approved') {
        $sql .= " AND PO_DateApproved IS NOT NULL";
    }
}

if (!empty($supplierFilter)) {
    $sql .= " AND Supplier = ?";
    $params[] = $supplierFilter;
}

if (!empty($startDate)) {
    $sql .= " AND STR_TO_DATE(PO_Date, '%Y/%m/%d') >= ?";
    $params[] = $startDate;
}
if (!empty($endDate)) {
    $sql .= " AND STR_TO_DATE(PO_Date, '%Y/%m/%d') <= ?";
    $params[] = $endDate;
}

if (!empty($searchTerm)) {
    $sql .= " AND (OrderID LIKE ? OR ItemCode LIKE ? OR Supplier LIKE ?)";
    $searchParam = "%$searchTerm%";
    $params[] = $searchParam;
    $params[] = $searchParam;
    $params[] = $searchParam;
}

$sql .= " ORDER BY IF(PO_DateApproved IS NULL, 0, 1) ASC, STR_TO_DATE(PO_Date, '%Y/%m/%d') DESC, OrderID DESC";

if (!empty($params)) {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $orders = $stmt->fetchAll();
} else {
    $orders = $pdo->query($sql)->fetchAll();
}

$statsSql = "SELECT 
    COUNT(*) as total_orders,
    SUM(CASE WHEN PO_DateApproved IS NULL THEN 1 ELSE 0 END) as pending_orders,
    SUM(CASE WHEN PO_DateApproved IS NOT NULL THEN 1 ELSE 0 END) as approved_orders,
    SUM(Quantity * UnitPrice) as total_value
FROM orders";
$stats = $pdo->query($statsSql)->fetch();

$suppliers = $pdo->query("SELECT DISTINCT Supplier FROM orders WHERE Supplier IS NOT NULL AND Supplier != '' ORDER BY Supplier")->fetchAll(PDO::FETCH_COLUMN);

$recentOrders = array_slice($orders, 0, 10);
?>

<style>
    .stat-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 12px;
        padding: 20px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    }
    .stat-card.pending {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }
    .stat-card.approved {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    }
    .stat-card.value {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
    }
    .stat-value {
        font-size: 2rem;
        font-weight: bold;
        margin-top: 5px;
    }
    .stat-label {
        font-size: 0.85rem;
        opacity: 0.9;
    }
</style>

<div class="row g-4 mb-4">
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-label">Total Orders</div>
            <div class="stat-value"><?php echo number_format($stats['total_orders'] ?? 0); ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card pending">
            <div class="stat-label">Pending Approval</div>
            <div class="stat-value"><?php echo number_format($stats['pending_orders'] ?? 0); ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card approved">
            <div class="stat-label">Approved Orders</div>
            <div class="stat-value"><?php echo number_format($stats['approved_orders'] ?? 0); ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card value">
            <div class="stat-label">Total Value</div>
            <div class="stat-value">$<?php echo number_format($stats['total_value'] ?? 0, 2); ?></div>
        </div>
    </div>
</div>

<div class="card mb-4">
    <div class="card-header">
        <h5 class="mb-0"><i class="bi bi-funnel me-2"></i>Filters</h5>
    </div>
    <div class="card-body">
        <form method="GET" class="row g-3">
            <div class="col-md-2">
                <input type="text" name="search" class="form-control" placeholder="Search orders..." value="<?php echo htmlspecialchars($searchTerm); ?>">
            </div>
            <div class="col-md-2">
                <select name="status" class="form-select">
                    <option value="">All Status</option>
                    <option value="pending" <?php echo $statusFilter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                    <option value="approved" <?php echo $statusFilter === 'approved' ? 'selected' : ''; ?>>Approved</option>
                </select>
            </div>
            <div class="col-md-2">
                <select name="supplier" class="form-select">
                    <option value="">All Suppliers</option>
                    <?php foreach ($suppliers as $supplier): ?>
                        <option value="<?php echo htmlspecialchars($supplier); ?>" <?php echo $supplierFilter === $supplier ? 'selected' : ''; ?>><?php echo htmlspecialchars($supplier); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <input type="date" name="start_date" class="form-control" value="<?php echo htmlspecialchars($startDate); ?>" placeholder="Start Date">
            </div>
            <div class="col-md-2">
                <input type="date" name="end_date" class="form-control" value="<?php echo htmlspecialchars($endDate); ?>" placeholder="End Date">
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary me-2"><i class="bi bi-search"></i> Filter</button>
                <a href="dashboard.php" class="btn btn-outline-secondary"><i class="bi bi-x-circle"></i> Clear</a>
            </div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="bi bi-cart me-2"></i>Orders</h5>
        <span class="badge bg-primary"><?php echo count($orders); ?> orders</span>
    </div>
    <div class="card-body">
        <?php if (empty($orders)): ?>
            <p class="text-muted">No orders found</p>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Order ID</th>
                            <th>Item Code</th>
                            <th>Quantity</th>
                            <th>Unit Price</th>
                            <th>Total</th>
                            <th>Supplier</th>
                            <th>PO Date</th>
                            <th>Approved Date</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($orders as $order): ?>
                        <tr>
                            <td><?php echo $order['OrderID']; ?></td>
                            <td><?php echo sanitize($order['ItemCode'] ?? '-'); ?></td>
                            <td><?php echo number_format($order['Quantity'] ?? 0); ?></td>
                            <td>$<?php echo number_format($order['UnitPrice'] ?? 0, 2); ?></td>
                            <td>$<?php echo number_format(($order['Quantity'] ?? 0) * ($order['UnitPrice'] ?? 0), 2); ?></td>
                            <td><?php echo sanitize($order['Supplier'] ?? '-'); ?></td>
                            <td><?php echo $order['PO_Date'] ?? '-'; ?></td>
                            <td><?php echo $order['PO_DateApproved'] ?? '-'; ?></td>
                            <td>
                                <?php if ($order['PO_DateApproved']): ?>
                                    <span class="badge bg-success">Approved</span>
                                <?php else: ?>
                                    <span class="badge bg-warning">Pending</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

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