<?php
session_start();

require_once __DIR__ . '/../includes/auth.php';
require_role('admin');
require_once __DIR__ . '/../includes/helpers.php';

$pdotry = null;
$error = null;
$orders = [];
$stats = [
    'new_today' => 0,
    'new_week' => 0,
    'awaiting_payment' => 0,
    'in_progress' => 0,
];

try {
    $pdo = db();

    // Fetch all orders with customer information
    $stmt = $pdo->query("
        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
        ORDER BY o.created_at DESC
    ");
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

    $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();

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

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

?>
<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $pageTitle ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../assets/css/custom.css">
</head>
<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">
            <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>
        </div>
        <div class="col-md-3">
            <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>
        </div>
        <div class="col-md-3">
            <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>
        </div>
        <div class="col-md-3">
            <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>
        </div>
    </div>


    <div class="card">
        <div class="card-header">
            Wszystkie zamówienia
        </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"><?= htmlspecialchars($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>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>