<?php
require_once 'includes/init.php';
require_login();

$orders = [];
$error_message = '';

if (!isset($_SESSION['client_id'])) {
    $error_message = t('error_client_id_not_found');
} else {
    $client_id = $_SESSION['client_id'];
    try {
        $pdo = db();
        $stmt = $pdo->prepare('SELECT * FROM orders WHERE client_id = ? ORDER BY created_at DESC');
        $stmt->execute([$client_id]);
        $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        error_log("Database error in orders.php: " . $e->getMessage());
        $error_message = t('error_fetching_orders');
    }
}

$page_title = t('title_orders');

require_once 'includes/html_head.php';
require_once 'includes/header.php';
?>

<main class="container my-5">
    <h1 class="mb-4"><?= t('order_history') ?></h1>

    <?php if (!empty($error_message)): ?>
        <div class="alert alert-danger" role="alert">
            <?= htmlspecialchars($error_message); ?>
        </div>
    <?php elseif (empty($orders)): ?>
        <div class="alert alert-info" role="alert">
            <?= t('no_orders_yet'); ?>
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th><?= t('order_number') ?></th>
                        <th><?= t('order_date') ?></th>
                        <th><?= t('status') ?></th>
                        <th><?= t('total_amount') ?></th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($orders as $order): ?>
                        <tr>
                            <td>#<?= $order['id']; ?></td>
                            <td><?= date('d.m.Y H:i', strtotime($order['created_at'])); ?></td>
                            <td><span class="badge bg-info"><?= htmlspecialchars(t_status($order['status'])); ?></span></td>
                            <td><?= format_money($order['total_amount'], $_SESSION['lang'] ?? 'pl', $pdo) ?></td>
                            <td>
                                <a href="order_details.php?id=<?= $order['id']; ?>" class="btn btn-sm btn-outline-primary">
                                    <i class="bi bi-eye"></i> <?= t('btn_view_details') ?>
                                </a>
                                <a href="generate_order_pdf.php?order_id=<?= $order['id'] ?>" class="btn btn-sm btn-outline-secondary" target="_blank">
                                    <i class="bi bi-download"></i> <?= t('download_pdf') ?>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</main>

<?php require_once 'includes/footer.php'; ?>
