<?php
session_start();
require_once __DIR__ . '/../includes/auth.php';
require_role('admin');
require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/../includes/helpers.php';

$pdo = db();
$order_id = $_GET['id'] ?? null;

// Simple local translations
$i18n = [
    'pending_payment' => 'Oczekuje na płatność',
    'paid' => 'Opłacone',
    'in_progress' => 'W realizacji',
    'shipped' => 'Wysłane',
    'completed' => 'Zakończone',
    'cancelled' => 'Anulowane',
    'transfer' => 'Przelew bankowy',
    'credit' => 'Kredyt kupiecki',
];

function get_status_translation_local($status, $translations) {
    return $translations[$status] ?? ucfirst(str_replace('_', ' ', $status));
}

function get_payment_method_translation_local($method, $translations) {
    return $translations[$method] ?? ucfirst($method);
}

if (!$order_id) {
    die('Nie podano ID zamówienia');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['status'])) {
    $new_status = $_POST['status'];
    $update_stmt = $pdo->prepare("UPDATE orders SET status = ? WHERE id = ?");
    $update_stmt->execute([$new_status, $order_id]);

    header("Location: order_details.php?id=$order_id");
    exit;
}

$stmt = $pdo->prepare("
    SELECT o.*, c.name as client_company_name
    FROM orders o
    LEFT JOIN clients c ON o.client_id = c.id
    WHERE o.id = ?
");
$stmt->execute([$order_id]);
$order = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$order) {
    die('Nie znaleziono zamówienia');
}

$items_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 = ?
");
$items_stmt->execute([$order_id]);
$order_items = $items_stmt->fetchAll(PDO::FETCH_ASSOC);

$statuses = ['pending_payment', 'paid', 'in_progress', 'shipped', 'completed', 'cancelled'];
$pageTitle = 'Szczegóły zamówienia #' . htmlspecialchars($order['id']);

?>
<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - Panel Administracyjny</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

</head>
<body>
<?php require_once __DIR__ . '/menu.php'; ?>
<main class="container mt-4">

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1><?php echo $pageTitle; ?></h1>
        <a href="orders.php" class="btn btn-secondary">
            <i class="bi bi-arrow-left"></i> Powrót do listy
        </a>
    </div>

    <div class="row">
        <div class="col-lg-8">
            <div class="card mb-4">
                <div class="card-header">Pozycje zamówienia</div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Produkt</th>
                                    <th>Ilość</th>
                                    <th>Cena jedn. netto</th>
                                    <th>Cena jedn. brutto</th>
                                    <th>Suma (brutto)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $vatRate = 1.23;
                                foreach ($order_items as $item): 
                                    $unit_price_gross = (float)$item['unit_price'];
                                    $unit_price_net = $unit_price_gross / $vatRate;
                                ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($item['product_name']); ?></td>
                                    <td><?php echo htmlspecialchars($item['quantity']); ?></td>
                                    <td><?php echo number_format($unit_price_net, 2, ',', ' '); ?> zł</td>
                                    <td><?php echo number_format($unit_price_gross, 2, ',', ' '); ?> zł</td>
                                    <td><?php echo number_format($item['line_total'], 2, ',', ' '); ?> zł</td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="card mb-4">
                <div class="card-header">Podsumowanie</div>
                <div class="card-body">
                    <p><strong>Klient:</strong> <?php echo htmlspecialchars($order['client_company_name'] ?? 'Brak'); ?></p>
                    <p><strong>Data:</strong> <?php echo date('d.m.Y H:i', strtotime($order['created_at'])); ?></p>
                    <p><strong>Metoda płatności:</strong> <span class="badge bg-secondary"><?php echo htmlspecialchars(get_payment_method_translation_local($order['payment_method'], $i18n)); ?></span></p>
                    <p><strong>Suma (brutto):</strong> <strong class="fs-5"><?php echo number_format($order['total_amount'], 2, ',', ' '); ?> zł</strong></p>
                </div>
            </div>
            <div class="card">
                <div class="card-header">Status zamówienia</div>
                <div class="card-body">
                    <form action="order_details.php?id=<?php echo $order_id; ?>" method="POST">
                        <div class="input-group">
                            <select name="status" class="form-select">
                                <?php foreach ($statuses as $status): ?>
                                <option value="<?php echo $status; ?>" <?php echo ($order['status'] === $status) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars(get_status_translation_local($status, $i18n)); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                            <button type="submit" class="btn btn-primary">Zapisz</button>
                        </div>
                    </form>
                    <div class="mt-2">
                        <strong>Aktualny status:</strong>
                        <span class="badge bg-info fs-6"><?php echo htmlspecialchars(get_status_translation_local($order['status'], $i18n)); ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
