<?php
// print_order.php
session_start();
require_once 'config/database.php';

// Проверка прав администратора
if (!isset($_SESSION['isAdmin']) || $_SESSION['isAdmin'] !== true) {
    die('Доступ запрещен');
}

$orderId = $_GET['id'] ?? 0;

$db = Database::getInstance()->getConnection();

try {
    $orderStmt = $db->prepare("
        SELECT o.*, u.email, u.full_name
        FROM orders o
        LEFT JOIN users u ON o.user_id = u.user_id
        WHERE o.order_id = ?
    ");
    $orderStmt->execute([$orderId]);
    $order = $orderStmt->fetch();

    if (!$order) {
        die('Заказ не найден');
    }

    $itemsStmt = $db->prepare("
        SELECT * FROM order_items
        WHERE order_id = ?
    ");
    $itemsStmt->execute([$orderId]);
    $order_items = $itemsStmt->fetchAll();

} catch (PDOException $e) {
    die('Ошибка базы данных: ' . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Печать заказа #<?= $order['order_number'] ?></title>
    <style>
        @media print {
            .no-print { display: none !important; }
        }
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            color: #000;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        .company-name {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        .order-info {
            margin-bottom: 30px;
        }
        .order-details {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 30px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        th, td {
            border: 1px solid #000;
            padding: 8px;
            text-align: left;
        }
        th {
            background: #f0f0f0;
        }
        .total-row {
            font-weight: bold;
        }
        .footer {
            margin-top: 50px;
            text-align: center;
            font-size: 12px;
            color: #666;
        }
        .print-button {
            margin: 20px;
            padding: 10px 20px;
            background: #453227;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <button onclick="window.print()" class="print-button no-print">
        <i class="fas fa-print"></i> Печать
    </button>

    <div class="header">
        <div class="company-name">AETERNA</div>
        <div>г. Москва, ул. Примерная, д. 123</div>
        <div>Телефон: +7(912)999-12-23 | Email: aeterna@mail.ru</div>
        <div>ИНН: 1234567890 | ОГРН: 1234567890123</div>
    </div>

    <div class="order-info">
        <h2>Заказ #<?= htmlspecialchars($order['order_number']) ?></h2>
        <p>Дата: <?= date('d.m.Y H:i', strtotime($order['created_at'])) ?></p>
        <p>Статус: <?= $order['status'] ?></p>
    </div>

    <div class="order-details">
        <div>
            <h3>Информация о клиенте</h3>
            <p><strong>ФИО:</strong> <?= htmlspecialchars($order['customer_name']) ?></p>
            <p><strong>Email:</strong> <?= htmlspecialchars($order['customer_email']) ?></p>
            <p><strong>Телефон:</strong> <?= htmlspecialchars($order['customer_phone']) ?></p>
        </div>

        <div>
            <h3>Информация о доставке</h3>
            <p><strong>Адрес:</strong> <?= nl2br(htmlspecialchars($order['delivery_address'])) ?></p>
            <p><strong>Способ доставки:</strong> <?= $order['delivery_method'] == 'courier' ? 'Курьер' : 'Самовывоз' ?></p>
            <p><strong>Способ оплаты:</strong> <?= $order['payment_method'] == 'card' ? 'Карта' : 'Наличные' ?></p>
        </div>
    </div>

    <h3>Состав заказа</h3>
    <table>
        <thead>
            <tr>
                <th>№</th>
                <th>Товар</th>
                <th>Кол-во</th>
                <th>Цена</th>
                <th>Сумма</th>
            </tr>
        </thead>
        <tbody>
            <?php $counter = 1; ?>
            <?php foreach ($order_items as $item): ?>
            <tr>
                <td><?= $counter++ ?></td>
                <td><?= htmlspecialchars($item['product_name']) ?></td>
                <td><?= $item['quantity'] ?></td>
                <td><?= number_format($item['unit_price'], 0, '', ' ') ?> ₽</td>
                <td><?= number_format($item['total_price'], 0, '', ' ') ?> ₽</td>
            </tr>
            <?php endforeach; ?>
        </tbody>
        <tfoot>
            <tr class="total-row">
                <td colspan="4" style="text-align: right;">Сумма товаров:</td>
                <td><?= number_format($order['total_amount'], 0, '', ' ') ?> ₽</td>
            </tr>
            <?php if ($order['discount_amount'] > 0): ?>
            <tr class="total-row">
                <td colspan="4" style="text-align: right;">Скидка:</td>
                <td>-<?= number_format($order['discount_amount'], 0, '', ' ') ?> ₽</td>
            </tr>
            <?php endif; ?>
            <?php if ($order['delivery_cost'] > 0): ?>
            <tr class="total-row">
                <td colspan="4" style="text-align: right;">Доставка:</td>
                <td><?= number_format($order['delivery_cost'], 0, '', ' ') ?> ₽</td>
            </tr>
            <?php endif; ?>
            <tr class="total-row">
                <td colspan="4" style="text-align: right; font-size: 16px;">Итого к оплате:</td>
                <td style="font-size: 16px;"><?= number_format($order['final_amount'], 0, '', ' ') ?> ₽</td>
            </tr>
        </tfoot>
    </table>

    <?php if ($order['notes']): ?>
    <div style="margin-top: 30px;">
        <h3>Примечания</h3>
        <p><?= nl2br(htmlspecialchars($order['notes'])) ?></p>
    </div>
    <?php endif; ?>

    <div class="footer">
        <p>Заказ создан в системе AETERNA</p>
        <p>Дата печати: <?= date('d.m.Y H:i') ?></p>
    </div>

    <script>
    // Автоматическая печать при загрузке
    window.onload = function() {
        setTimeout(function() {
            window.print();
        }, 500);
    };
    </script>
</body>
</html>