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

$order_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($order_id === 0) {
    header('Location: orders.php');
    exit;
}

$client_id = $_SESSION['client_id'] ?? 0;
$error_message = null;
$order = null;
$order_items = [];
$product_images = [];

if ($client_id === 0) {
    $error_message = t('unauthorized_order_view');
} else {
    try {
        $pdo = db();

        $stmt = $pdo->prepare('SELECT * FROM orders WHERE id = :order_id AND client_id = :client_id');
        $stmt->execute([':order_id' => $order_id, ':client_id' => $client_id]);
        $order = $stmt->fetch();

        if (!$order) {
            $error_message = t('order_not_found_or_unauthorized');
        } else {
            $stmt = $pdo->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();

            if (!empty($order_items)) {
                $product_ids = array_map(fn($item) => $item['product_id'], $order_items);
                $placeholders = implode(',', array_fill(0, count($product_ids), '?'));

                $image_stmt = $pdo->prepare(
                    "SELECT product_id, file_path, is_primary, id FROM product_images WHERE product_id IN ($placeholders) ORDER BY product_id, is_primary DESC, id ASC"
                );
                $image_stmt->execute($product_ids);
                $images_data = $image_stmt->fetchAll();

                $product_images_temp = [];
                foreach ($images_data as $image) {
                    if (!isset($product_images_temp[$image['product_id']])) {
                        $product_images_temp[$image['product_id']] = 'uploads/products/' . $image['product_id'] . '/' . basename($image['file_path']);
                    }
                }
                $product_images = $product_images_temp;
            }
        }

    } catch (PDOException $e) {
        $error_message = t('db_error_generic');
        error_log($e->getMessage());
    }
}

$page_title = $order ? str_replace('{order_id}', $order['id'], t('order_details_title')) : t('order_details_fallback_title');

require_once __DIR__ . '/includes/html_head.php';
require_once __DIR__ . '/includes/header.php';

?>

<main class="container my-5">
    <?php if ($error_message): ?>
        <div class="alert alert-danger">
            <i class="bi bi-exclamation-triangle-fill"></i> <?= htmlspecialchars($error_message) ?>
        </div>
        <a href="orders.php" class="btn btn-secondary"><i class="bi bi-arrow-left"></i> <?= t('back_to_orders') ?></a>
    <?php elseif ($order): ?>
        <h1 class="mb-4"><?= htmlspecialchars($page_title) ?></h1>

        <div class="card mb-4">
            <div class="card-header"><?= t('summary') ?></div>
            <div class="card-body">
                <p><strong><?= t('order_date') ?>:</strong> <?= date('d.m.Y H:i', strtotime($order['created_at'])) ?></p>
                <p><strong><?= t('status') ?>:</strong> <span class="badge bg-info"><?= htmlspecialchars(t_status($order['status'])) ?></span></p>
                <p><strong><?= t('payment_method') ?>:</strong> <?= htmlspecialchars(t_status($order['payment_method'])) ?></p>
                <p><strong><?= t('total_gross') ?>:</strong> <?= format_money($order['total_amount'], $_SESSION['lang'] ?? 'pl', $pdo) ?></p>
                <p><strong><?= t('notes') ?>:</strong> <?= nl2br(htmlspecialchars($order['notes'])) ?></p>
            </div>
        </div>

        <div class="card">
            <div class="card-header"><?= t('order_details') ?></div>
            <div class="card-body">
                <table class="table">
                    <thead>
                        <tr>
                            <th><?= t('image') ?></th>
                            <th><?= t('product') ?></th>
                            <th><?= t('unit_price_net') ?></th>
                            <th><?= t('unit_price_gross') ?></th>
                            <th><?= t('quantity') ?></th>
                            <th><?= t('total_gross') ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $vatRate = 1.23;
                        foreach ($order_items as $item): 
                            $image_url = $product_images[$item['product_id']] ?? 'https://placehold.co/100x100/EEE/31343C?text=' . urlencode(t('no_image_placeholder'));
                            $unit_price_gross = (float)$item['unit_price'];
                            $unit_price_net = $unit_price_gross / $vatRate;
                        ?>
                            <tr>
                                <td><img src="<?= htmlspecialchars($image_url) ?>" alt="<?= htmlspecialchars($item['product_name']) ?>" style="width: 50px; height: 50px; object-fit: cover;"></td>
                                <td><?= htmlspecialchars($item['product_name']) ?></td>
                                <td><?= format_money($unit_price_net, $_SESSION['lang'] ?? 'pl', $pdo) ?></td>
                                <td><?= format_money($unit_price_gross, $_SESSION['lang'] ?? 'pl', $pdo) ?></td>
                                <td><?= $item['quantity'] ?></td>
                                <td><?= format_money($item['line_total'], $_SESSION['lang'] ?? 'pl', $pdo) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="mt-4 d-flex justify-content-between">
            <a href="orders.php" class="btn btn-secondary"><i class="bi bi-arrow-left"></i> <?= t('back_to_orders') ?></a>
            <a href="generate_order_pdf.php?order_id=<?= $order['id'] ?>" class="btn btn-primary" target="_blank"><i class="bi bi-download"></i> <?= t('download_pdf') ?></a>
        </div>
    <?php endif; ?>
</main>

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