<?php
// packing-slip.php
require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/orders.php';
require_once __DIR__ . '/../app/settings.php';

$user = sparrow_require_backyard_login();
$pdo = sparrow_db();

$settings = sparrow_get_settings($pdo, [
    'business_name',
    'packing_footer',
    'packing_slip_print_mode',
    'packing_slip_layout',
    'packing_show_delivery',
    'packing_show_customer_contact',
    'packing_slip_title_text',
    'packing_show_business_name',
    'packing_show_delivery_notes',
    'packing_show_admin_notes',
    'packing_show_footer_message',
    'packing_slip_date_mode',
]);

$selected_ids = [];

if (!empty($_GET['ids'])) {
    $selected_ids = array_filter(array_map('intval', explode(',', (string) $_GET['ids'])));
} else {
    $single_id = (int) ($_GET['id'] ?? 0);

    if ($single_id > 0) {
        $selected_ids[] = $single_id;
    }
}

$selected_ids = array_values(array_unique($selected_ids));

if (!$selected_ids) {
    sparrow_redirect('/backyard/dashboard.php');
}

$orders_for_print = [];

foreach ($selected_ids as $selected_id) {
    $selected_order = sparrow_get_order((int) $selected_id);

    if ($selected_order) {
        $orders_for_print[] = [
            'order' => $selected_order,
            'items' => sparrow_get_order_items((int) $selected_id),
        ];
    }
}

if (!$orders_for_print) {
    sparrow_backyard_header('Packing Slip Not Found'); ?>
    <section class="card">
        <h1>Packing Slip Not Found</h1>
        <p class="muted">That order could not be found.</p>
        <a class="button" href="<?= sparrow_url('/backyard/dashboard.php') ?>">Back to Dashboard</a>
    </section>
<?php
    sparrow_backyard_footer();
    exit;
}

function sparrow_packing_slip_date($date): string
{
    if (empty($date)) {
        return date('n/j/Y');
    }

    $timestamp = strtotime((string) $date);
    return $timestamp ? date('n/j/Y', $timestamp) : (string) $date;
}

$packing_slip_title = trim((string) ($settings['packing_slip_title_text'] ?? 'Packing Slip'));
if ($packing_slip_title === '') {
    $packing_slip_title = 'Packing Slip';
}

$business_name = trim((string) ($settings['business_name'] ?? ''));
if ($business_name === '') {
    $business_name = 'Sparrow & Seed Creations';
}

$packing_print_mode = in_array(
    ($settings['packing_slip_print_mode'] ?? 'pretty'),
    ['pretty', 'bw', 'compact_bw'],
    true
) ? $settings['packing_slip_print_mode'] : 'pretty';

$packing_layout = ($settings['packing_slip_layout'] ?? 'full_page') === 'compact'
    ? 'compact'
    : 'full_page';

$show_delivery = ($settings['packing_show_delivery'] ?? 'yes') === 'yes';
$show_customer_contact = ($settings['packing_show_customer_contact'] ?? 'yes') === 'yes';
$show_business_name = ($settings['packing_show_business_name'] ?? 'yes') === 'yes';
$show_delivery_notes = ($settings['packing_show_delivery_notes'] ?? 'yes') === 'yes';
$show_admin_notes = ($settings['packing_show_admin_notes'] ?? 'yes') === 'yes';
$show_footer_message = ($settings['packing_show_footer_message'] ?? 'yes') === 'yes';
$packing_footer = trim((string) ($settings['packing_footer'] ?? ''));

$is_bulk = count($orders_for_print) > 1;
$page_title = $is_bulk
    ? 'Bulk ' . $packing_slip_title . 's'
    : $packing_slip_title . ' - ' . ($orders_for_print[0]['order']['order_number'] ?? '');

sparrow_backyard_header($page_title);
?>

<style>
/* Hide navigation & buttons on print */
@media print {
    @page {
        margin: 0.35in;
    }

    html,
    body {
        margin: 0 !important;
        padding: 0 !important;
        background: #ffffff !important;
        height: auto !important;
        min-height: 0 !important;
    }

    .sidebar,
    .topbar,
    .packing-actions,
    .button,
    .button-secondary {
        display: none !important;
    }

    .backyard-shell,
    .main-shell,
    .page {
        display: block !important;
        margin: 0 !important;
        padding: 0 !important;
        width: 100% !important;
        max-width: none !important;
        min-height: 0 !important;
        height: auto !important;
    }

    .card {
        border: 0 !important;
        box-shadow: none !important;
        border-radius: 0 !important;
        padding: 0 !important;
        margin: 0 !important;
        min-height: 0 !important;
    }

    table {
        page-break-inside: auto;
    }

    tr {
        page-break-inside: avoid;
        page-break-after: auto;
    }

    thead {
        display: table-header-group;
    }

    h1,
    h2,
    h3,
    p {
        margin-top: 0;
    }

/* Make tables scale to page width */
    table {
        width: 100% !important;
        max-width: 100% !important;
        overflow: visible !important;
        table-layout: fixed;
    }

    th, td {
        word-wrap: break-word;
        overflow-wrap: break-word;
    }

    .card, .table-wrap {
        width: 100% !important;
        max-width: 100% !important;
        padding: 0 !important;
        margin: 0 !important;
        box-shadow: none !important;
    }

    body, html {
        width: 100% !important;
    }
}

@media print {
    body, table, th, td {
        font-size: 10pt; /* smaller font for A5/letter scaling */
    }
}

@media print {
    .items-edit-table th, .items-edit-table td {
        width: auto !important;
        max-width: 100% !important;
    }
}

/* Default print styles already exist for Letter/A4 */

/* Smaller sizes */
@media print and (max-width: 420px) { /* roughly A5 width */
    body, table, th, td, p, h2 {
        font-size: 8pt !important; /* shrink font for small paper */
    }

    table, .table-wrap, .card {
        width: 100% !important;
        max-width: 100% !important;
        margin: 0 !important;
        padding: 0 !important;
    }

    th, td {
        word-wrap: break-word;
        overflow-wrap: break-word;
        padding: 2px 4px !important;
    }
}

@media print and (max-width: 350px) { /* roughly A6 width */
    body, table, th, td, p, h2 {
        font-size: 7pt !important; /* even smaller */
    }

    th, td {
        padding: 1px 2px !important;
    }
}

.packing-actions {
    margin-bottom: 12px;
}

.packing-print-area {
    display: grid;
    gap: 18px;
}

.packing-slip-sheet--compact {
    padding: 16px;
}

.packing-slip-sheet--compact .packing-slip-title {
    margin-bottom: 8px;
}

.packing-slip-sheet--compact .packing-slip-meta,
.packing-slip-sheet--compact .packing-slip-notes {
    margin-bottom: 8px;
}

.packing-slip-sheet--compact th,
.packing-slip-sheet--compact td {
    padding: 5px 6px;
}

.packing-slip-business {
    margin: 0 0 4px;
    font-weight: 700;
}

.packing-slip-meta p,
.packing-slip-notes p {
    margin-bottom: 8px;
}

.packing-slip-footer {
    margin: 16px 0 0;
    text-align: center;
}

@media print {
    .packing-print-area {
        display: block !important;
    }

    .packing-print-area .packing-slip-sheet {
        page-break-after: always;
        break-after: page;
    }

    .packing-print-area .packing-slip-sheet:last-child {
        page-break-after: auto;
        break-after: auto;
    }

    .packing-slip-sheet--bw,
    .packing-slip-sheet--compact_bw {
        color: #000000 !important;
        filter: grayscale(1);
    }

    .packing-slip-sheet--compact,
    .packing-slip-sheet--compact_bw {
        font-size: 8pt !important;
    }

    .packing-slip-sheet--compact .packing-slip-table th,
    .packing-slip-sheet--compact .packing-slip-table td,
    .packing-slip-sheet--compact_bw .packing-slip-table th,
    .packing-slip-sheet--compact_bw .packing-slip-table td {
        padding: 2px 4px !important;
        line-height: 1.05 !important;
    }

    .packing-slip-table {
        table-layout: fixed !important;
        width: 100% !important;
        font-size: 8pt !important;
    }

    .packing-slip-table th,
    .packing-slip-table td {
        padding: 4px 5px !important;
        line-height: 1.15 !important;
        overflow-wrap: break-word !important;
        word-break: normal !important;
    }

    .packing-slip-table th {
        font-size: 7.5pt !important;
        letter-spacing: 0.02em !important;
    }

    .packing-slip-table .col-qty {
        width: 9%;
    }

    .packing-slip-table .col-type {
        width: 14%;
    }

    .packing-slip-table .col-size {
        width: 13%;
    }

    .packing-slip-table .col-color {
        width: 14%;
    }

    .packing-slip-table .col-specialty {
        width: 13%;
    }

    .packing-slip-table .col-print {
        width: 16%;
    }

    .packing-slip-table .col-notes {
        width: 21%;
    }

    .packing-slip-title {
        font-size: 15pt !important;
        margin-bottom: 14px !important;
    }

    .packing-slip-meta {
        font-size: 8.5pt !important;
        line-height: 1.25 !important;
        margin-bottom: 12px !important;
    }
}
</style>

<div class="packing-actions">
    <button type="button" class="button" onclick="window.print();">
        Print <?= $is_bulk ? sparrow_escape($packing_slip_title . 's') : sparrow_escape($packing_slip_title) ?>
    </button>
    <?php
    $back_url = $is_bulk
        ? sparrow_url('/backyard/dashboard.php')
        : sparrow_url('/backyard/order-view.php?id=' . (int) $orders_for_print[0]['order']['id']);
    ?>
    <a class="button button-secondary" href="<?= sparrow_escape($back_url) ?>">
        <?= $is_bulk ? 'Back to Dashboard' : 'Back to Order' ?>
    </a>
</div>

<div class="packing-print-area">
<?php foreach ($orders_for_print as $print_order): ?>
    <?php
    $order = $print_order['order'];
    $items = $print_order['items'];
    $order_shipping_amount = max(0, (float) ($order['order_shipping_amount'] ?? 0));
    $packing_slip_date = ($settings['packing_slip_date_mode'] ?? 'order_date') === 'print_date'
        ? date('n/j/Y')
        : sparrow_packing_slip_date($order['order_date'] ?? '');
    ?>
<section class="card packing-slip-sheet packing-slip-sheet--<?= sparrow_escape($packing_layout) ?> packing-slip-sheet--<?= sparrow_escape($packing_print_mode) ?>">
    <?php if ($show_business_name): ?>
        <p class="packing-slip-business"><?= sparrow_escape($business_name) ?></p>
    <?php endif; ?>

    <h2 class="packing-slip-title"><?= sparrow_escape($packing_slip_title) ?></h2>

    <div class="packing-slip-meta">
    <p>
        <strong>Order:</strong> <?= sparrow_escape($order['order_number']) ?><br>
        <strong>Customer:</strong> <?= sparrow_escape($order['customer_name']) ?><br>
        <strong>Date:</strong> <?= sparrow_escape($packing_slip_date) ?>
    </p>

    <?php if ($show_customer_contact): ?>
        <?php $customer_phone = trim((string) ($order['customer_phone'] ?? '')); ?>
        <?php $customer_email = trim((string) ($order['customer_email'] ?? '')); ?>
        <?php if ($customer_phone !== '' || $customer_email !== ''): ?>
            <p>
                <?php if ($customer_phone !== ''): ?>
                    <strong>Phone:</strong> <?= sparrow_escape($customer_phone) ?><br>
                <?php endif; ?>
                <?php if ($customer_email !== ''): ?>
                    <strong>Email:</strong> <?= sparrow_escape($customer_email) ?>
                <?php endif; ?>
            </p>
        <?php endif; ?>
    <?php endif; ?>

    <?php if ($show_delivery && !empty($order['delivery_method'])): ?>
        <p><strong>Delivery Method:</strong> <?= sparrow_escape($order['delivery_method']) ?></p>
    <?php endif; ?>
	
	<?php if ($show_delivery && $order_shipping_amount > 0): ?>
    <p>
        <strong>Shipping Charge:</strong>
        $<?= number_format($order_shipping_amount, 2) ?>
    </p>
<?php endif; ?>

    <?php if ($show_delivery_notes && !empty($order['delivery_notes'])): ?>
        <p><strong>Delivery Notes:</strong> <?= nl2br(sparrow_escape($order['delivery_notes'])) ?></p>
    <?php endif; ?>
</div>

    <?php if ($show_admin_notes && !empty($order['admin_notes'])): ?>
        <div class="packing-slip-notes">
            <p><strong>Admin Notes:</strong><br><?= nl2br(sparrow_escape($order['admin_notes'])) ?></p>
        </div>
    <?php endif; ?>

    <div class="table-wrap">
    <table class="packing-slip-table">
        <thead>
            <tr>
                <th class="col-qty">Qty</th>
<th class="col-type">Type</th>
<th class="col-size">Size</th>
<th class="col-color">Color</th>
<th class="col-specialty">Spec.</th>
<th class="col-print">Print</th>
<th class="col-notes">Notes</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($items as $item): ?>
            <tr>
                <td><?= (int)$item['quantity'] ?></td>
                <td><?= sparrow_escape($item['item_type']) ?></td>
                <td><?= sparrow_escape($item['shirt_size']) ?></td>
                <td><?= sparrow_escape($item['shirt_color']) ?></td>
                <td><?= sparrow_escape($item['specialty']) ?></td>
                <td><?= sparrow_escape($item['print_location']) ?></td>
                <td><?= sparrow_escape($item['item_notes']) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    </div>

    <?php if ($show_footer_message && $packing_footer !== ''): ?>
        <p class="packing-slip-footer"><?= nl2br(sparrow_escape($packing_footer)) ?></p>
    <?php endif; ?>
</section>
<?php endforeach; ?>
</div>

<?php sparrow_backyard_footer(); ?>
