<?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, [
    'worklog_print_mode',
    'worklog_orientation',
    'worklog_show_pulled',
    'worklog_show_qc',
    'worklog_show_pressed',
    'worklog_show_pictured',
    'worklog_show_packed',
    'worklog_title_text',
    'worklog_show_phone',
    'worklog_show_total_shirts',
    'worklog_show_notes_column',
]);

$worklog_title = trim((string) ($settings['worklog_title_text'] ?? 'Work Log'));
if ($worklog_title === '') {
    $worklog_title = 'Work Log';
}

$worklog_orientation = ($settings['worklog_orientation'] ?? 'landscape') === 'portrait'
    ? 'portrait'
    : 'landscape';

$worklog_print_mode = ($settings['worklog_print_mode'] ?? 'pretty') === 'bw'
    ? 'bw'
    : 'pretty';

$worklog_options = [
    'title' => $worklog_title,
    'show_phone' => ($settings['worklog_show_phone'] ?? 'yes') === 'yes',
    'show_total_shirts' => ($settings['worklog_show_total_shirts'] ?? 'yes') === 'yes',
    'show_notes_column' => ($settings['worklog_show_notes_column'] ?? 'yes') === 'yes',
    'show_pulled' => ($settings['worklog_show_pulled'] ?? 'yes') === 'yes',
    'show_qc' => ($settings['worklog_show_qc'] ?? 'yes') === 'yes',
    'show_pressed' => ($settings['worklog_show_pressed'] ?? 'yes') === 'yes',
    'show_pictured' => ($settings['worklog_show_pictured'] ?? 'yes') === 'yes',
    'show_packed' => ($settings['worklog_show_packed'] ?? 'yes') === 'yes',
];

function sparrow_worklog_format_date($date): string
{
    if (!$date) {
        return '';
    }

    $timestamp = strtotime((string) $date);

    if (!$timestamp) {
        return (string) $date;
    }

    return date('n/j/Y', $timestamp);
}

function sparrow_worklog_render_sheet(array $order, array $items, array $options): void
{
    $total_quantity = 0;

    foreach ($items as $item) {
        $total_quantity += max(1, (int) ($item['quantity'] ?? 1));
    }

    ?>
    <div class="worklog-sheet">
        <h1 class="worklog-title"><?= htmlspecialchars((string) ($options['title'] ?? 'Work Log')) ?></h1>
        <div class="worklog-header-box">
            <div>
                <strong>Order #:</strong> <?= htmlspecialchars($order['order_number'] ?? '') ?><br>
                <strong>Date:</strong> <?= htmlspecialchars(sparrow_worklog_format_date($order['order_date'] ?? '')) ?>
            </div>

            <div>
                <strong>Customer:</strong> <?= htmlspecialchars($order['customer_name'] ?? '') ?>
                <?php if (!empty($options['show_phone'])): ?>
                    <br><strong>Phone:</strong> <?= htmlspecialchars(sparrow_format_phone_number($order['customer_phone'] ?? '')) ?>
                <?php endif; ?>
            </div>

            <?php if (!empty($options['show_total_shirts'])): ?>
            <div>
                <strong>Total Shirts:</strong> <?= (int) $total_quantity ?>
            </div>
            <?php endif; ?>
        </div>

        <table class="worklog-table">
            <thead>
                <tr>
                    <th class="num-col">#</th>
                    <th class="color-col">Color</th>
                    <th class="size-col">Size</th>
                    <th class="placement-col">Placement</th>
                    <th class="specialty-col">Specialty/Add-ons</th>
                    <?php if (!empty($options['show_notes_column'])): ?><th class="notes-col">Notes</th><?php endif; ?>
                    <th class="shirt-col">Shirt #</th>
                    <?php if (!empty($options['show_pulled'])): ?><th class="check-col">Pulled</th><?php endif; ?>
                    <?php if (!empty($options['show_qc'])): ?><th class="check-col">QC</th><?php endif; ?>
                    <?php if (!empty($options['show_pressed'])): ?><th class="check-col">Pressed</th><?php endif; ?>
                    <?php if (!empty($options['show_pictured'])): ?><th class="check-col">Pictured</th><?php endif; ?>
                    <?php if (!empty($options['show_packed'])): ?><th class="check-col">Packed</th><?php endif; ?>
                </tr>
            </thead>

            <tbody>
                <?php
                $row_number = 1;

                foreach ($items as $item):
                    $quantity = max(1, (int) ($item['quantity'] ?? 1));
                    $color = trim((string) ($item['shirt_color'] ?? ''));
                    $size = trim((string) ($item['shirt_size'] ?? ''));
                    $placement = trim((string) ($item['print_location'] ?? ''));
$specialty = trim((string) ($item['specialty'] ?? ''));
$item_notes = trim((string) ($item['item_notes'] ?? ''));

if ($specialty === 'None') {
    $specialty = '';
}

                    for ($shirt_number = 1; $shirt_number <= $quantity; $shirt_number++):
                        ?>
                        <tr>
                            <td class="num-col"><?= (int) $row_number ?></td>
                            <td class="color-col"><?= htmlspecialchars($color) ?></td>
                            <td class="size-col"><?= htmlspecialchars($size) ?></td>
                            <td class="placement-col"><?= htmlspecialchars($placement) ?></td>
                            <td class="specialty-col"><?= htmlspecialchars($specialty) ?></td>
                            <?php if (!empty($options['show_notes_column'])): ?><td class="notes-col"><?= htmlspecialchars($item_notes) ?></td><?php endif; ?>
                            <td class="shirt-col"><?= (int) $shirt_number ?> of <?= (int) $quantity ?></td>
                            <?php if (!empty($options['show_pulled'])): ?><td class="check-col">☐</td><?php endif; ?>
                            <?php if (!empty($options['show_qc'])): ?><td class="check-col">☐</td><?php endif; ?>
                            <?php if (!empty($options['show_pressed'])): ?><td class="check-col">☐</td><?php endif; ?>
                            <?php if (!empty($options['show_pictured'])): ?><td class="check-col">☐</td><?php endif; ?>
                            <?php if (!empty($options['show_packed'])): ?><td class="check-col">☐</td><?php endif; ?>
                        </tr>
                        <?php
                        $row_number++;
                    endfor;
                endforeach;
                ?>
            </tbody>
        </table>
    </div>
    <?php
}

$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');
}

$print_type = strtolower(trim($_GET['type'] ?? 'all'));

$orders_for_print = [];

foreach ($selected_ids as $order_id) {
    $order = sparrow_get_order((int) $order_id);

    if (!$order) {
        continue;
    }

    $items = sparrow_get_order_items((int) $order_id);

    if ($print_type === 'shirts') {
        $items = array_filter($items, function ($item) {
            $item_type = strtolower(trim((string) ($item['item_type'] ?? '')));
            $notes = strtolower(trim((string) ($item['item_notes'] ?? '')));

            return (
                strpos($item_type, 'shirt') !== false ||
                strpos($item_type, 'tee') !== false ||
                strpos($item_type, 't-shirt') !== false ||
                strpos($item_type, 'tshirt') !== false ||
                strpos($notes, 'shirt') !== false
            );
        });
    }

    if ($print_type === 'koozies') {
        $items = array_filter($items, function ($item) {
            $item_type = strtolower(trim((string) ($item['item_type'] ?? '')));
            $notes = strtolower(trim((string) ($item['item_notes'] ?? '')));

            return (
                strpos($item_type, 'koozie') !== false ||
                strpos($item_type, 'coozie') !== false ||
                strpos($item_type, 'can cooler') !== false ||
                strpos($item_type, 'can holder') !== false ||
                strpos($notes, 'koozie') !== false ||
                strpos($notes, 'coozie') !== false ||
                strpos($notes, 'can cooler') !== false ||
                strpos($notes, 'can holder') !== false
            );
        });
    }

    $items = array_values($items);

    $orders_for_print[] = [
        'order' => $order,
        'items' => $items,
    ];
}

if (!$orders_for_print) {
    sparrow_backyard_header('Work Log Not Found');
    ?>
    <section class="card">
        <h1>Work Log Not Found</h1>
        <p class="muted">No matching orders were found.</p>
        <a class="button" href="<?= sparrow_url('/backyard/dashboard.php') ?>">Back to Dashboard</a>
    </section>
    <?php
    sparrow_backyard_footer();
    exit;
}

$page_title = count($orders_for_print) > 1 ? 'Bulk ' . $worklog_title . 's' : $worklog_title;

$is_bulk = count($orders_for_print) > 1;

$back_url = $is_bulk
    ? sparrow_url('/backyard/dashboard.php')
    : sparrow_url(
        '/backyard/order-view.php?id='
        . (int) $orders_for_print[0]['order']['id']
    );

$back_label = $is_bulk
    ? '← Back to Dashboard'
    : '← Back to Order';

$worklog_query_base = [];

if (!empty($_GET['ids'])) {
    $worklog_query_base['ids'] = implode(',', $selected_ids);
} elseif (!empty($selected_ids[0])) {
    $worklog_query_base['id'] = (int) $selected_ids[0];
}

$all_worklog_url = sparrow_url('/backyard/work-log.php?' . http_build_query($worklog_query_base));

$shirt_worklog_query = $worklog_query_base;
$shirt_worklog_query['type'] = 'shirts';
$shirt_worklog_url = sparrow_url('/backyard/work-log.php?' . http_build_query($shirt_worklog_query));

$koozie_worklog_query = $worklog_query_base;
$koozie_worklog_query['type'] = 'koozies';
$koozie_worklog_url = sparrow_url('/backyard/work-log.php?' . http_build_query($koozie_worklog_query));

sparrow_backyard_header($page_title);
?>

<style>
@page {
    size: <?= htmlspecialchars($worklog_orientation) ?>;
    margin: 0.25in;
}

.worklog-actions {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 14px;
}

.selected-orders {
    margin: 6px 0 14px;
    font-size: 12px;
}

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

.worklog-sheet {
    background: #fff;
    color: #000;
    border: 1px solid #000;
    padding: 0.25in;
    font-family: Arial, sans-serif;
    page-break-inside: avoid;
    break-inside: avoid;
}

.worklog-title {
    margin: 0 0 10px;
    text-align: center;
    font-size: 20px;
    line-height: 1.15;
}

.worklog-header-box {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(0, 1fr));
    gap: 8px;
    border: 1px solid #000;
    padding: 8px;
    margin-bottom: 12px;
    font-size: 13px;
}

.worklog-mode-pretty .worklog-title {
    color: #8f3f69;
}

.worklog-mode-pretty .worklog-header-box,
.worklog-mode-pretty .worklog-table th {
    background: #fdf2f8;
}

.worklog-mode-bw .worklog-title,
.worklog-mode-bw .worklog-header-box,
.worklog-mode-bw .worklog-table th {
    color: #000;
    background: #fff;
}

.worklog-table {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
    font-size: 12px;
}

.worklog-table th,
.worklog-table td {
    border: 1px solid #000;
    padding: 5px;
    vertical-align: middle;
}

.worklog-table th {
    text-align: center;
    font-weight: bold;
    background: #fff;
}

.num-col {
    width: 34px;
    text-align: center;
}

.shirt-col {
    width: 68px;
    text-align: center;
}

.check-col {
    width: 58px;
    text-align: center;
    font-size: 12px;
    white-space: nowrap;
}

@media print {
    .sidebar,
    .topbar,
    .worklog-actions,
    .button,
    .button-secondary {
        display: none !important;
    }

    body,
    html {
        margin: 0 !important;
        padding: 0 !important;
        background: #fff !important;
    }

    .page,
    .card {
        width: 100% !important;
        max-width: 100% !important;
        margin: 0 !important;
        padding: 0 !important;
        border: 0 !important;
        box-shadow: none !important;
        background: #fff !important;
    }

    .worklog-print-area {
        gap: 0.12in;
    }

    .worklog-sheet {
        padding: 0.15in !important;
        margin: 0 0 0.12in !important;
        border: 1px solid #000 !important;
        box-shadow: none !important;
        page-break-inside: avoid;
        break-inside: avoid;
    }

    .worklog-header-box {
        padding: 4px !important;
        margin-bottom: 4px !important;
        font-size: 11px !important;
    }

    .worklog-title {
        margin-bottom: 4px !important;
        font-size: 16px !important;
    }

    .worklog-table {
        font-size: 10px !important;
    }

    .worklog-table th,
    .worklog-table td {
        padding: 2px !important;
        height: 16px !important;
    }

    .check-col {
    width: 58px !important;
    font-size: 9px !important;
    white-space: nowrap !important;
}

    .shirt-col {
        width: 62px !important;
    }
	
	.worklog-table th.check-col {
    font-size: 8px !important;
    letter-spacing: 0 !important;
    padding-left: 1px !important;
    padding-right: 1px !important;
}

.worklog-table td.check-col {
    font-size: 12px !important;
}

.worklog-table th.color-col,
.worklog-table td.color-col {
    width: 105px !important;
}

.worklog-table th.size-col,
.worklog-table td.size-col {
    width: 85px !important;
}

.worklog-table th.check-col,
.worklog-table td.check-col {
    width: 54px !important;
    min-width: 54px !important;
    max-width: 54px !important;
}

.worklog-table th.check-col {
    font-size: 7.5px !important;
    white-space: nowrap !important;
}
}

/* Work log column sizing */
.worklog-table th,
.worklog-table td {
    font-size: 10px;
}

.worklog-table th.color-col,
.worklog-table td.color-col {
    width: 115px;
}

.worklog-table th.size-col,
.worklog-table td.size-col {
    width: 95px;
}

.worklog-table th.check-col,
.worklog-table td.check-col {
    width: 56px;
    min-width: 56px;
    max-width: 56px;
    text-align: center;
}

.worklog-table th.check-col {
    font-size: 8px;
    line-height: 1;
    padding-left: 1px;
    padding-right: 1px;
    white-space: nowrap;
}

.worklog-table td.check-col {
    font-size: 13px;
}

@media print {
    .content,
    .main-content,
    .backyard-content,
    main {
        margin: 0 !important;
        padding: 0 !important;
        width: 100% !important;
        max-width: 100% !important;
    }

    .worklog-print-area {
        display: block !important;
        gap: 0 !important;
        margin: 0 !important;
        padding: 0 !important;
    }

    .worklog-sheet {
        margin: 0 0 0.08in 0 !important;
        padding: 0.10in !important;
        page-break-inside: avoid !important;
        break-inside: avoid !important;
    }

    .worklog-sheet:last-child {
        margin-bottom: 0 !important;
        page-break-after: auto !important;
        break-after: auto !important;
    }

    .card::after,
    .page::after,
    body::after {
        content: none !important;
        display: none !important;
    }
}

@media print {
    @page {
        size: <?= htmlspecialchars($worklog_orientation) ?>;
        margin: 0.2in;
    }

    html,
    body {
        margin: 0 !important;
        padding: 0 !important;
        width: 100% !important;
        height: auto !important;
        min-height: 0 !important;
        overflow: visible !important;
        background: #fff !important;
    }

    body * {
        visibility: hidden !important;
    }

    .worklog-print-area,
    .worklog-print-area * {
        visibility: visible !important;
    }

    .worklog-print-area {
        position: absolute !important;
        left: 0 !important;
        top: 0 !important;
        width: 100% !important;
        margin: 0 !important;
        padding: 0 !important;
        display: block !important;
    }

    .worklog-sheet {
    width: 100% !important;
    box-sizing: border-box !important;
    margin: 0 0 0.04in 0 !important;
    padding: 0.14in !important;
        border: 1px solid #000 !important;
        box-shadow: none !important;
        page-break-inside: avoid !important;
        break-inside: avoid !important;
    }

    .worklog-sheet:last-child {
        margin-bottom: 0 !important;
        page-break-after: auto !important;
        break-after: auto !important;
    }

    .worklog-header-box {
    padding: 5px !important;
    margin-bottom: 5px !important;
    font-size: 11px !important;
}

    .worklog-table {
    width: 100% !important;
    font-size: 10px !important;
}

.worklog-table th,
.worklog-table td {
    padding: 2px 3px !important;
    height: 17px !important;
    line-height: 1.15 !important;
}

    .worklog-table th.check-col {
        font-size: 7px !important;
    }

    .worklog-table td.check-col {
        font-size: 10px !important;
    }

    .worklog-actions,
    .selected-orders,
    .sidebar,
    .topbar,
    .button,
    .button-secondary,
    footer {
        display: none !important;
    }
	
	.worklog-table th.placement-col,
.worklog-table td.placement-col {
    width: 70px !important;
}

.worklog-table th.specialty-col,
.worklog-table td.specialty-col {
    width: 80px !important;
}

.worklog-table th.notes-col,
.worklog-table td.notes-col {
    width: 140px !important;
    white-space: normal !important;
    overflow-wrap: break-word !important;
}

.worklog-unified-layout .placement-col {
    width: 70px !important;
}

.worklog-unified-layout .specialty-col {
    width: 80px !important;
}

.worklog-unified-layout .notes-col {
    width: 140px !important;
    white-space: normal !important;
    overflow-wrap: break-word !important;
}

.worklog-unified-layout .shirt-col {
    width: 52px !important;
}

.worklog-unified-layout .check-col {
    width: 54px !important;
    min-width: 54px !important;
    max-width: 54px !important;
}
}

.worklog-table th.placement-col,
.worklog-table td.placement-col {
    width: 78px;
}

.worklog-table th.specialty-col,
.worklog-table td.specialty-col {
    width: 90px;
}

.worklog-table th.notes-col,
.worklog-table td.notes-col {
    width: 150px;
    white-space: normal;
    overflow-wrap: break-word;
}

/* Force single and bulk work logs to use the same table layout */
.worklog-unified-layout .worklog-table {
    table-layout: fixed;
    width: 100%;
}

.worklog-unified-layout .placement-col {
    width: 70px !important;
}

.worklog-unified-layout .specialty-col {
    width: 80px !important;
}

.worklog-unified-layout .notes-col {
    width: 140px !important;
    white-space: normal !important;
    overflow-wrap: break-word !important;
}

.worklog-unified-layout .shirt-col {
    width: 52px !important;
}

.worklog-unified-layout .check-col {
    width: 54px !important;
    min-width: 54px !important;
    max-width: 54px !important;
}

@media screen {
    .worklog-print-area {
        max-width: 11in;
        margin: 0 auto;
    }

    .worklog-sheet {
        width: 100%;
        box-sizing: border-box;
    }
}
</style>

<section class="card">
<div class="worklog-actions">
    <a
    class="button button-secondary"
    href="<?= htmlspecialchars($back_url) ?>"
>
    <?= htmlspecialchars($back_label) ?>
</a>

    <a class="button button-secondary" href="<?= htmlspecialchars($all_worklog_url) ?>">
        All Items
    </a>

    <a class="button button-secondary" href="<?= htmlspecialchars($shirt_worklog_url) ?>">
        Shirts Only
    </a>

    <a class="button button-secondary" href="<?= htmlspecialchars($koozie_worklog_url) ?>">
        Koozies Only
    </a>

    <button type="button" class="button" onclick="window.print();">
        Print Work Log
    </button>
</div>

    <?php if (count($selected_ids) > 1): ?>
        <div class="selected-orders">
            Selected orders: <?= htmlspecialchars(implode(', ', $selected_ids)) ?>
        </div>
    <?php endif; ?>

    <div class="worklog-print-area worklog-unified-layout worklog-mode-<?= htmlspecialchars($worklog_print_mode) ?>">
        <?php foreach ($orders_for_print as $print_order): ?>
            <?php sparrow_worklog_render_sheet($print_order['order'], $print_order['items'], $worklog_options); ?>
        <?php endforeach; ?>
    </div>
</section>

<?php sparrow_backyard_footer(); ?>
