<?php
require_once __DIR__ . '/../includes/init.php';
require_role(['admin', 'handlowiec', 'supplier']);

function t_filter_status($status) {
    if ($status === 'new_today') return 'Nowe (dziś)';
    if ($status === 'new_week') return 'Nowe (tydzień)';
    return t_status($status);
}

$pdo = db();
$role = get_user_role();
$error = null;
$orders = [];
$stats = [
    'new_today' => 0,
    'new_week' => 0,
    'awaiting_payment' => 0,
    'in_progress' => 0,
];

$filter_status = $_GET['status'] ?? null;

try {
    $params = [];
    $where_clauses = [];

    $today_start = date('Y-m-d 00:00:00');
    $week_start = date('Y-m-d 00:00:00', strtotime('-7 days'));

    if ($role === 'supplier') {
        $supplier_id = $_SESSION['user_id'];
        $sql = "
            SELECT DISTINCT
                o.id,
                c.name as client_company_name,
                o.created_at,
                o.status,
                o.total_amount,
                o.delivery_source
            FROM orders o
            LEFT JOIN clients c ON o.client_id = c.id
            JOIN order_items oi ON o.id = oi.order_id
            JOIN products p ON oi.product_id = p.id
        ";
        $where_clauses[] = "p.supplier_id = :supplier_id";
        $params[':supplier_id'] = $supplier_id;

        // Stats for supplier
        $stats_base_sql = "SELECT COUNT(DISTINCT o.id) FROM orders o JOIN order_items oi ON o.id = oi.order_id JOIN products p ON oi.product_id = p.id WHERE p.supplier_id = ?";
        
        $new_today_stmt = $pdo->prepare($stats_base_sql . " AND o.created_at >= ?");
        $new_today_stmt->execute([$supplier_id, $today_start]);
        $stats['new_today'] = $new_today_stmt->fetchColumn();

        $new_week_stmt = $pdo->prepare($stats_base_sql . " AND o.created_at >= ?");
        $new_week_stmt->execute([$supplier_id, $week_start]);
        $stats['new_week'] = $new_week_stmt->fetchColumn();

        $awaiting_payment_stmt = $pdo->prepare($stats_base_sql . " AND o.status = 'pending_payment'");
        $awaiting_payment_stmt->execute([$supplier_id]);
        $stats['awaiting_payment'] = $awaiting_payment_stmt->fetchColumn();

        $in_progress_stmt = $pdo->prepare($stats_base_sql . " AND o.status = 'in_progress'");
        $in_progress_stmt->execute([$supplier_id]);
        $stats['in_progress'] = $in_progress_stmt->fetchColumn();

    } else { // admin or handlowiec
        $sql = "
            SELECT
                o.id,
                c.name as client_company_name,
                o.created_at,
                o.status,
                o.total_amount,
                o.delivery_source
            FROM orders o
            LEFT JOIN clients c ON o.client_id = c.id
        ";
        
        // Stats for admin/handlowiec
        $new_today_stmt = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE created_at >= ?");
        $new_today_stmt->execute([$today_start]);
        $stats['new_today'] = $new_today_stmt->fetchColumn();

        $new_week_stmt = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE created_at >= ?");
        $new_week_stmt->execute([$week_start]);
        $stats['new_week'] = $new_week_stmt->fetchColumn();

        $awaiting_payment_stmt = $pdo->query("SELECT COUNT(*) FROM orders WHERE status = 'pending_payment'");
        $stats['awaiting_payment'] = $awaiting_payment_stmt->fetchColumn();

        $in_progress_stmt = $pdo->query("SELECT COUNT(*) FROM orders WHERE status = 'in_progress'");
        $stats['in_progress'] = $in_progress_stmt->fetchColumn();
    }

    if ($filter_status) {
        switch ($filter_status) {
            case 'new_today':
                $where_clauses[] = "o.created_at >= :today_start";
                $params[':today_start'] = $today_start;
                break;
            case 'new_week':
                $where_clauses[] = "o.created_at >= :week_start";
                $params[':week_start'] = $week_start;
                break;
            default:
                $where_clauses[] = "o.status = :status";
                $params[':status'] = $filter_status;
                break;
        }
    }

    if (!empty($where_clauses)) {
        $sql .= " WHERE " . implode(" AND ", $where_clauses);
    }
    
    $sql .= " ORDER BY o.created_at DESC";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    $error = "Błąd bazy danych: " . $e->getMessage();
}

$page_title = "Zarządzanie zamówieniami";

?>
<?php require_once __DIR__ . '/../includes/html_head.php'; ?>
<body>
<?php include 'menu.php'; ?>
<div class="container">
    <h1 class="mb-4"><?= $pageTitle ?></h1>

    <?php if ($error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div class="row mb-4">
        <div class="col-md-3">
            <a href="?status=new_today" class="text-decoration-none">
                <div class="card text-center">
                    <div class="card-body">
                        <h5 class="card-title">Nowe (dziś)</h5>
                        <p class="card-text fs-4"><?= $stats['new_today'] ?></p>
                    </div>
                </div>
            </a>
        </div>
        <div class="col-md-3">
            <a href="?status=new_week" class="text-decoration-none">
                <div class="card text-center">
                    <div class="card-body">
                        <h5 class="card-title">Nowe (tydzień)</h5>
                        <p class="card-text fs-4"><?= $stats['new_week'] ?></p>
                    </div>
                </div>
            </a>
        </div>
        <div class="col-md-3">
            <a href="?status=pending_payment" class="text-decoration-none">
                <div class="card text-center text-bg-warning">
                    <div class="card-body">
                        <h5 class="card-title">Do zapłaty</h5>
                        <p class="card-text fs-4"><?= $stats['awaiting_payment'] ?></p>
                    </div>
                </div>
            </a>
        </div>
        <div class="col-md-3">
            <a href="?status=in_progress" class="text-decoration-none">
                <div class="card text-center text-bg-info">
                    <div class="card-body">
                        <h5 class="card-title">W realizacji</h5>
                        <p class="card-text fs-4"><?= $stats['in_progress'] ?></p>
                    </div>
                </div>
            </a>
        </div>
    </div>


    <div class="card">
        <div class="card-header">
            <?php 
            $list_title = 'Wszystkie zamówienia';
            if ($filter_status) {
                $list_title = 'Filtrowane: ' . t_filter_status($filter_status);
            }
            echo htmlspecialchars($list_title);
            if ($filter_status) {
                echo '<a href="orders.php" class="btn btn-sm btn-secondary float-end">Wyczyść filtr</a>';
            }
            ?>
        </div>
        <div class="card-body">
            <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Klient</th>
                        <th>Data</th>
                        <th>Status</th>
                        <th>Źródło</th>
                        <th>Suma (brutto)</th>
                        <th>Akcje</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($orders)): ?>
                        <tr>
                            <td colspan="7" class="text-center">Brak zamówień do wyświetlenia.</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($orders as $order): ?>
                        <tr>
                            <td>#<?= htmlspecialchars($order['id']) ?></td>
                            <td><?= htmlspecialchars($order['client_company_name'] ?? 'Klient indywidualny') ?></td>
                            <td><?= date('d.m.Y H:i', strtotime($order['created_at'])) ?></td>
                            <td><span class="badge bg-info"><?= t_status($order['status']) ?></span></td>
                            <td><?= htmlspecialchars($order['delivery_source'] ?? 'N/A') ?></td>
                            <td><?= htmlspecialchars(number_format($order['total_amount'], 2, ',', ' ')) ?> zł</td>
                            <td>
                                <a href="order_details.php?id=<?= $order['id'] ?>" class="btn btn-sm btn-primary">Szczegóły</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
</body>
</html>