<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/backup.php';

if (empty($_SESSION['admin_logged_in'])) {
    header('Location: login.php');
    exit;
}

$pageTitle = 'Admin Dashboard';
$backupAutoMessage = '';
$backupAutoMessageType = '';

try {
    $backup = backupCreateAutomaticIfDue();
    if ($backup !== null) {
        $backupAutoMessage =
            'Automatisches Backup wurde erstellt: ' .
            $backup['filename'] .
            '.';
        $backupAutoMessageType = 'success';
    }
} catch (Throwable $exception) {
    $backupAutoMessage =
        'Automatisches Backup konnte nicht erstellt werden: ' .
        $exception->getMessage();
    $backupAutoMessageType = 'warning';
}
$orders = getOrders();

$backorderGroups = getBackorderGroups();
$backorderCount = 0;
foreach ($backorderGroups as $group) {
    $backorderCount += (int) $group['to_be_backordered'] + (int) $group['ordered'];
}

$stats = [
    'open' => 0,
    'partial' => 0,
    'processed' => 0,
    'cancelled' => 0,
    'backorder' => $backorderCount,
];

foreach ($orders as $order) {
    if ($order['status'] === 'cancelled') {
        $stats['cancelled']++;
    } elseif ($order['status'] === 'processed') {
        $stats['processed']++;
    } elseif ($order['status'] === 'partial') {
        $stats['partial']++;
    } else {
        $stats['open']++;
    }
}

$recentOrders = array_values(array_filter($orders, function ($order) {
    $label = getOrderStatusLabel($order);
    if ($label !== 'Offen' && $label !== 'Teilweise bearbeitet') {
        return false;
    }
    foreach ($order['items'] as $item) {
        if (!empty($item['is_processed'])) {
            continue;
        }
        if (trim((string) ($item['backorder_status'] ?? '')) === '') {
            return true;
        }
    }
    return false;
}));
usort($recentOrders, function ($left, $right) {
    return strcmp($right['created_at'], $left['created_at']);
});
$recentOrders = array_slice($recentOrders, 0, 5);

$outstandingItems = [];
foreach ($orders as $order) {
    $label = getOrderStatusLabel($order);
    if ($label !== 'Offen' && $label !== 'Teilweise bearbeitet') {
        continue;
    }
    foreach ($order['items'] as $item) {
        if (!empty($item['is_processed'])) {
            continue;
        }
        if (trim((string) ($item['backorder_status'] ?? '')) !== '') {
            continue;
        }
        $outstandingItems[] = [
            'order_id' => $order['id'],
            'customer_name' => $order['customer_name'],
            'organization_label' => $order['organization_label'],
            'created_at' => $order['created_at'],
            'product_name' => $item['product_name'],
            'size' => $item['size'],
            'availability_label' => $item['availability_label'],
        ];
    }
}
usort($outstandingItems, function ($left, $right) {
    $cmp = strcmp($left['created_at'], $right['created_at']);
    if ($cmp !== 0) {
        return $cmp;
    }
    $cmp = strcmp($left['order_id'], $right['order_id']);
    if ($cmp !== 0) {
        return $cmp;
    }
    return strcmp($left['product_name'], $right['product_name']);
});

$bodyClass = 'admin-page';
include __DIR__ . '/../includes/header.php';
?>

<div class="admin-header">
    <h2>Admin Dashboard</h2>
    <div class="admin-dashboard-actions">
        <a href="orders.php" class="btn">Bestellungen</a>
        <details class="admin-actions-dropdown">
            <summary class="btn btn-secondary">Verwaltung</summary>
            <div class="admin-actions-menu">
                <a href="products.php">Produkte verwalten</a>
                <a href="categories.php">Kategorien verwalten</a>
                <a href="organizations.php">Organisationen verwalten</a>
                <a href="settings.php">Einstellungen</a>
                <a href="faq.php">FAQ bearbeiten</a>
                <a href="backorders.php">Nachbestellungen verwalten</a>
                <a href="admins.php">Admins verwalten</a>
                <form method="POST" action="login.php" class="inline-form">
                    <?php echo csrfField(); ?>
                    <button type="submit" name="logout" class="btn btn-secondary btn-small">Abmelden</button>
                </form>
            </div>
        </details>
    </div>
</div>

<?php if ($backupAutoMessage !== ''): ?>
    <div class="alert alert-<?php echo escape($backupAutoMessageType); ?>">
        <?php echo escape($backupAutoMessage); ?>
    </div>
<?php endif; ?>

<div class="admin-stats">
    <div class="stat-card">
        <h3>Offen</h3>
        <div class="stat-value"><?php echo $stats['open']; ?></div>
    </div>
    <div class="stat-card">
        <h3>Teilweise bearbeitet</h3>
        <div class="stat-value"><?php echo $stats['partial']; ?></div>
    </div>
    <div class="stat-card">
        <h3>Bearbeitet</h3>
        <div class="stat-value"><?php echo $stats['processed']; ?></div>
    </div>
    <div class="stat-card">
        <h3>Storniert</h3>
        <div class="stat-value"><?php echo $stats['cancelled']; ?></div>
    </div>
    <div class="stat-card">
        <h3>Nachbestellung</h3>
        <div class="stat-value"><?php echo $stats['backorder']; ?></div>
    </div>
</div>

<h3 class="section-title mt-4">Bestellungen mit Aktion erforderlich</h3>

<?php if (empty($recentOrders)): ?>
    <p>Keine Bestellungen mit erforderlicher Aktion.</p>
<?php else: ?>
    <div class="table-responsive">
        <table class="responsive-table">
            <thead>
                <tr>
                    <th>Bestellnummer</th>
                    <th>Name</th>
                    <th>Organisation</th>
                    <th>Erstellt</th>
                    <th>Status</th>
                    <th>Nachbestellung</th>
                    <th>Aktionen</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($recentOrders as $order):
                    $backorderSummary = getOrderOpenBackorderSummary($order);
                    ?>
                    <tr>
                        <td data-label="Bestellnummer"><strong><?php echo escape($order['id']); ?></strong></td>
                        <td data-label="Name"><?php echo escape($order['customer_name']); ?></td>
                        <td data-label="Organisation"><?php echo escape($order['organization_label']); ?></td>
                        <td data-label="Erstellt"><?php echo escape(formatDate($order['created_at'])); ?></td>
                        <td data-label="Status"><span class="status <?php echo escape(getOrderStatusClass($order)); ?>"><?php echo escape(getOrderStatusLabel($order)); ?></span></td>
                        <td data-label="Nachbestellung">
                            <?php if ($backorderSummary['label'] !== ''): ?>
                                <span class="status <?php echo escape($backorderSummary['class']); ?>"><?php echo escape($backorderSummary['label']); ?></span>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                        <td data-label="Aktionen"><a href="order.php?id=<?php echo urlencode($order['id']); ?>" class="btn btn-small">Details</a></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
<?php endif; ?>

<h3 class="section-title mt-4">Offene Positionen</h3>

<?php if (empty($outstandingItems)): ?>
    <p>Keine offenen Positionen vorhanden.</p>
<?php else: ?>
    <div class="table-responsive">
        <table class="responsive-table">
            <thead>
                <tr>
                    <th>Bestellnummer</th>
                    <th>Name</th>
                    <th>Organisation</th>
                    <th>Artikel</th>
                    <th>Größe</th>
                    <th>Lieferhinweis</th>
                    <th>Erstellt</th>
                    <th>Aktionen</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($outstandingItems as $row): ?>
                    <tr>
                        <td data-label="Bestellnummer"><strong><?php echo escape($row['order_id']); ?></strong></td>
                        <td data-label="Name"><?php echo escape($row['customer_name']); ?></td>
                        <td data-label="Organisation"><?php echo escape($row['organization_label']); ?></td>
                        <td data-label="Artikel"><?php echo escape($row['product_name']); ?></td>
                        <td data-label="Größe"><?php echo $row['size'] !== '' ? escape($row['size']) : '-'; ?></td>
                        <td data-label="Lieferhinweis"><?php echo $row['availability_label'] !== '' ? escape($row['availability_label']) : '-'; ?></td>
                        <td data-label="Erstellt"><?php echo escape(formatDate($row['created_at'])); ?></td>
                        <td data-label="Aktionen"><a href="order.php?id=<?php echo urlencode($row['order_id']); ?>" class="btn btn-small">Details</a></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
<?php endif; ?>

<?php include __DIR__ . '/../includes/footer.php'; ?>
