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

$order_id = $_SESSION['latest_order_id'] ?? 0;

if ($order_id === 0) {
    header('Location: orders.php');
    exit;
}

$db = db();
$stmt = $db->prepare("SELECT * FROM orders WHERE id = ? AND client_id = ?");
$stmt->execute([$order_id, $_SESSION['client_id']]);
$order = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$order) {
    header('Location: orders.php');
    exit;
}

// Fetch order items
$stmt = $db->prepare("
    SELECT oi.*, p.name as product_name
    FROM order_items oi
    JOIN products p ON oi.product_id = p.id
    WHERE oi.order_id = ?
");
$stmt->execute([$order_id]);
$order_items = $stmt->fetchAll(PDO::FETCH_ASSOC);

$page_title = t('order_confirmation');

require_once __DIR__ . '/includes/html_head.php';
require_once __DIR__ . '/includes/header.php';
?>
<div class="container mt-5">
    <div class="card">
        <div class="card-header bg-success text-white">
            <h4 class="mb-0"><?= t('thank_you_for_your_order') ?></h4>
        </div>
        <div class="card-body">
            <p><?= t('your_order_number') ?> <strong>#<?php echo $order['id']; ?></strong> <?= t('has_been_placed_successfully') ?></p>
            <hr>

            <h5 class="mt-4"><?= t('order_summary') ?></h5>
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th><?= t('product') ?></th>
                        <th><?= t('quantity') ?></th>
                        <th><?= t('price') ?></th>
                        <th><?= t('total') ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($order_items as $item) : ?>
                        <tr>
                            <td><?php echo htmlspecialchars($item['product_name']); ?></td>
                            <td><?php echo $item['quantity']; ?></td>
                            <td><?php echo format_money($item['unit_price'], get_lang(), $db); ?></td>
                            <td><?php echo format_money($item['line_total'], get_lang(), $db); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <th colspan="3" class="text-right"><?= t('grand_total') ?></th>
                        <th><?php echo format_money($order['total_amount'], get_lang(), $db); ?></th>
                    </tr>
                </tfoot>
            </table>

            <p class="mb-0 mt-4"><?= t('order_details_will_be_sent') ?> <a href="orders.php"><?= t('orders') ?></a>.</p>
        </div>
        <div class="card-footer">
            <a href="index.php" class="btn btn-primary"><?= t('continue_shopping') ?></a>
        </div>
    </div>
</div>
<?php 
// Unset the session variable so it's not shown again on refresh
unset($_SESSION['latest_order_id']);
require_once __DIR__ . '/includes/footer.php'; 
?>
