<?php
require_once __DIR__ . '/../includes/init.php';
require_role(['admin', 'handlowiec', 'supplier']);

$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']) && get_user_role() !== 'supplier') {
    $new_status = $_POST['status'];

    $stmt = $pdo->prepare("SELECT status FROM orders WHERE id = ?");
    $stmt->execute([$order_id]);
    $old_status = $stmt->fetchColumn();

    $update_stmt = $pdo->prepare("UPDATE orders SET status = ? WHERE id = ?");
    $update_stmt->execute([$new_status, $order_id]);

    // If status changed to 'paid', send notifications
    if ($new_status === 'paid' && $old_status !== 'paid') {
        require_once __DIR__ . '/../mail/MailService.php';

        // Fetch order and client details for email
        $stmt = $pdo->prepare("
            SELECT o.*, c.name as client_company_name, u.email as client_email
            FROM orders o
            JOIN clients c ON o.client_id = c.id
            JOIN users u ON c.id = u.client_id
            WHERE o.id = ? AND u.id = (SELECT MIN(id) FROM users WHERE client_id = o.client_id)
        ");
        $stmt->execute([$order_id]);
        $order_details_for_email = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($order_details_for_email && !empty($order_details_for_email['client_email'])) {
            $client_email = $order_details_for_email['client_email'];
            $client_language = 'pl'; // Hardcoded fallback

            // 4. Client - Payment Confirmation
            MailService::sendTemplatedMail(
                $client_email,
                $client_language,
                'payment_confirmation',
                [
                    'order_id' => $order_id,
                    'order_details_for_email' => $order_details_for_email
                ]
            );


        }
    }

    if ($new_status === 'shipped' && $old_status !== 'shipped') {
        require_once __DIR__ . '/../mail/MailService.php';

        // Fetch order and client details for email
        $stmt = $pdo->prepare("
            SELECT o.*, c.name as client_company_name, c.language as client_language, u.email as client_email
            FROM orders o
            JOIN clients c ON o.client_id = c.id
            JOIN users u ON c.id = u.client_id
            WHERE o.id = ? AND u.id = (SELECT MIN(id) FROM users WHERE client_id = o.client_id)
        ");
        $stmt->execute([$order_id]);
        $order_details_for_email = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($order_details_for_email && !empty($order_details_for_email['client_email'])) {
            $client_email = $order_details_for_email['client_email'];
            $client_language = $order_details_for_email['client_language'] ?? 'en';

            MailService::sendTemplatedMail(
                $client_email,
                $client_language,
                'order_shipped',
                [
                    'order_id' => $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'];
$page_title = 'Szczegóły zamówienia #' . htmlspecialchars($order['id']);

?>
<?php require_once __DIR__ . '/../includes/html_head.php'; ?>
<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>Szczegóły zamówienia #<?php echo htmlspecialchars($order['id']); ?></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>Numer zamówienia:</strong> <?php echo htmlspecialchars($order['id']); ?></p>
                    <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>
                    <?php if (!empty($order['notes'])): ?>
                        <hr>
                        <p><strong>Uwagi do zamówienia:</strong></p>
                        <p><?php echo nl2br(htmlspecialchars($order['notes'])); ?></p>
                    <?php endif; ?>
                </div>
            </div>
<?php if (get_user_role() !== 'supplier') : ?>
            <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>
        <?php else: ?>
            <div class="card">
                <div class="card-header">Status zamówienia</div>
                <div class="card-body">
                    <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>
        <?php endif; ?>
        </div>
    </div>
</main>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
</body>
</html>
