<?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',
    'website_url',
    'contact_email',
    'contact_phone',
    'facebook',
    'instagram',
    'logo_url',
    'invoice_header_url',
    'signature_url',
    'invoice_thank_you',
    'invoice_print_mode',
    'invoice_header_layout',
    'invoice_show_header_image',
    'invoice_show_logo',
    'invoice_show_footer',
    'invoice_show_thank_you',
    'invoice_show_page_number',
    'invoice_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('Invoice Not Found'); ?>
    <section class="card">
        <h1>Invoice Not Found</h1>
        <p class="muted">That order could not be found.</p>
        <a class="button" href="<?= sparrow_escape(sparrow_url('/backyard/dashboard.php')) ?>">Back to Dashboard</a>
    </section>
<?php
    sparrow_backyard_footer();
    exit;
}

function sparrow_invoice_money($amount): string
{
    return '$' . number_format((float) $amount, 2);
}

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

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

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

function sparrow_invoice_asset_url(string $value, string $fallback): string
{
    $value = trim($value);

    if ($value === '') {
        $value = $fallback;
    }

    if (preg_match('#^https?://#i', $value)) {
        return $value;
    }

    return sparrow_url('/' . ltrim($value, '/'));
}

function sparrow_invoice_item_description(array $item): string
{
    $parts = [];

    $type = trim((string) ($item['item_type'] ?? ''));
    $color = trim((string) ($item['shirt_color'] ?? ''));
    $size = trim((string) ($item['shirt_size'] ?? ''));
    $placement = trim((string) ($item['print_location'] ?? ''));
    $specialty = trim((string) ($item['specialty'] ?? ''));
    $notes = trim((string) ($item['item_notes'] ?? ''));

    if ($color !== '' || $type !== '') {
        $parts[] = trim($color . ' ' . $type);
    }

    if ($size !== '') {
        $parts[] = 'Size ' . $size;
    }

    if ($placement !== '') {
        $parts[] = $placement;
    }

    if ($specialty !== '') {
        $parts[] = $specialty;
    }

    if ($notes !== '') {
        $parts[] = $notes;
    }

    return implode(' - ', array_filter($parts));
}

$show_logo = ($settings['invoice_show_logo'] ?? 'yes') === 'yes';
$show_header_image = ($settings['invoice_show_header_image'] ?? 'yes') === 'yes';
$show_footer = ($settings['invoice_show_footer'] ?? 'yes') === 'yes';
$show_thank_you = ($settings['invoice_show_thank_you'] ?? 'yes') === 'yes';
$show_page_number = ($settings['invoice_show_page_number'] ?? 'yes') === 'yes';

$invoice_print_mode = ($settings['invoice_print_mode'] ?? 'pretty') === 'bw'
    ? 'bw'
    : 'pretty';
$invoice_header_layout = ($settings['invoice_header_layout'] ?? 'stacked') === 'side_by_side'
    ? 'side_by_side'
    : 'stacked';

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

$logo_url = sparrow_invoice_asset_url(
    (string) ($settings['logo_url'] ?? ''),
    '/backyard/images/sparrow-logo.png'
);
$invoice_header_url = sparrow_invoice_asset_url(
    (string) ($settings['invoice_header_url'] ?? ''),
    '/backyard/images/Invoice.png'
);
$signature_url = sparrow_invoice_asset_url(
    (string) ($settings['signature_url'] ?? ''),
    '/backyard/images/sparrow-signature-header.png'
);

$footer_social = [];
$footer_contact = [];

if (trim((string) ($settings['facebook'] ?? '')) !== '') {
    $footer_social[] = 'Facebook: ' . trim((string) $settings['facebook']);
}

if (trim((string) ($settings['instagram'] ?? '')) !== '') {
    $footer_social[] = 'Instagram: ' . trim((string) $settings['instagram']);
}

foreach (['website_url', 'contact_phone', 'contact_email'] as $contact_key) {
    $contact_value = trim((string) ($settings[$contact_key] ?? ''));
    if ($contact_value !== '') {
        $footer_contact[] = $contact_value;
    }
}

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

sparrow_backyard_header($page_title);
?>

<style>
:root {
    --invoice-light: #f4e7ec;
    --invoice-soft: #e8cfd8;
    --invoice-line: #d9a8b8;
    --invoice-accent: #c9879d;
    --invoice-dark: #9b5c75;
    --invoice-ink: #241a22;
}

.invoice-actions {
    display: flex;
    gap: 10px;
    margin-bottom: 14px;
}

.invoice-card {
    background: #ffffff;
    overflow-x: auto;
}

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

.invoice-sheet {
    width: 8.5in;
    min-height: 11in;
    margin: 0 auto;
    padding: 0.42in 0.55in 0.35in;
    background: #ffffff;
    color: var(--invoice-ink);
    font-size: 12px;
    position: relative;
    box-sizing: border-box;
    font-family: Arial, Helvetica, sans-serif;

    display: flex;
    flex-direction: column;
}

.invoice-sheet--bw {
    --invoice-light: #f1f1f1;
    --invoice-soft: #dddddd;
    --invoice-line: #aaaaaa;
    --invoice-accent: #555555;
    --invoice-dark: #111111;
    --invoice-ink: #000000;
}

.invoice-header {
    display: grid;
    grid-template-columns: 2.15in 1fr;
    column-gap: 0.25in;
    align-items: start;
}

.invoice-logo {
    width: 1.55in;
    height: auto;
    display: block;
}

.invoice-title-area {
    text-align: right;
    padding-top: 0.03in;
}

.invoice-header--no-logo {
    grid-template-columns: 1fr;
}

.invoice-header--side-by-side {
    grid-template-columns: 1.45in 1fr;
    column-gap: 0.18in;
    align-items: center;
}

.invoice-header--side-by-side .invoice-title-area {
    display: grid;
    grid-template-columns: 2.05in 1fr;
    column-gap: 0.16in;
    align-items: center;
    padding-top: 0;
}

.invoice-header--side-by-side .invoice-title-image {
    width: 2.05in;
}

.invoice-header--side-by-side .invoice-info-table {
    width: 100%;
    margin: 0;
}

.invoice-header--side-by-side.invoice-header--no-title-image .invoice-title-area {
    grid-template-columns: 1fr;
}

.invoice-header--side-by-side.invoice-header--no-logo {
    grid-template-columns: 1fr;
}

.invoice-title-image {
    width: 3.25in;
    max-width: 100%;
    height: auto;
    display: inline-block;
}

.invoice-info-table {
    width: 4.7in;
    margin: 0.08in 0 0 auto;
    border-collapse: collapse;
    table-layout: fixed;
    text-align: center;
}

.invoice-info-table th {
    background: var(--invoice-light);
    color: var(--invoice-dark);
    border: 1px solid #ddc8d0;
    padding: 7px 8px;
    font-size: 10px;
    letter-spacing: 0.14em;
    text-transform: uppercase;
    font-weight: 700;
}

.invoice-info-table td {
    border: 1px solid #ddc8d0;
    padding: 10px 8px;
    font-size: 12px;
    font-weight: 700;
}

.invoice-items {
    width: 100%;
    margin-top: 0.42in;
    border-collapse: collapse;
    table-layout: fixed;
}

.invoice-items th {
    color: var(--invoice-dark);
    border-bottom: 2px solid var(--invoice-accent);
    padding: 8px 7px;
    font-size: 10px;
    letter-spacing: 0.16em;
    text-transform: uppercase;
    text-align: center;
}

.invoice-items th:first-child {
    text-align: left;
}

.invoice-items td {
    height: 0.31in;
    padding: 7px;
    border-bottom: 1px solid #e6d9de;
    border-right: 1px solid #e6d9de;
    vertical-align: top;
}

.invoice-items tbody tr:last-child td {
    border-bottom: 2px solid var(--invoice-accent);
}

.invoice-items td:last-child {
    border-right: none;
}

.invoice-items .description-col {
    width: 55%;
}

.invoice-items .qty-col {
    width: 16%;
    text-align: center;
}

.invoice-items .unit-col,
.invoice-items .total-col {
    width: 14.5%;
    text-align: right;
}

.invoice-lower {
    display: grid;
    grid-template-columns: 1fr 3.45in;
    column-gap: 0.35in;
    margin-top: 0.16in;
    align-items: start;
}

.invoice-lower--totals-only {
    grid-template-columns: 3.45in;
    justify-content: end;
}

.invoice-thank-you {
    min-height: 1.8in;
    padding-top: 0.4in; /* extra padding to push signature down */
    color: var(--invoice-dark);
    font-style: italic;
    font-size: 12px;
    line-height: 1.45;
}

.invoice-thank-you p {
    margin: 0 0 0.08in;
}

.invoice-signature {
    width: 1.55in;
    max-width: 100%;
    height: auto;
    display: block;
    margin-top: 0.18in;
}

.invoice-totals-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 0.1in; /* small spacing above totals */
}

.invoice-totals-table td {
    padding: 9px 12px;
    border-top: 1px solid #ddc8d0;
    font-size: 14px;
}

.invoice-totals-table td:first-child {
    text-transform: uppercase;
    letter-spacing: 0.02em;
}

.invoice-totals-table td:last-child {
    text-align: right;
    font-weight: 700;
}

.invoice-totals-table .total-row td {
    background: var(--invoice-light);
    color: var(--invoice-dark);
    border-top: none;
    font-size: 16px;
    font-weight: 800;
}

.invoice-footer {
    margin-top: auto;
    padding-top: 0.2in;
    text-align: center;
    font-size: 10px;
    font-weight: 700;
    color: #151515;
    clear: both;
}

.invoice-footer-line {
    display: grid;
    grid-template-columns: 1fr auto 1fr;
    align-items: center;
    gap: 12px;
    margin-bottom: 7px;
}

.invoice-footer-line::before,
.invoice-footer-line::after {
    content: "";
    height: 1px;
    background: var(--invoice-accent);
}

.invoice-footer-heart {
    color: var(--invoice-dark);
    font-size: 13px;
}

.invoice-footer-contact {
    line-height: 1.55;
}

.invoice-page-number {
    text-align: right;
    margin-top: 0.06in;
    font-size: 10px;
    color: #111111;
}

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

    body {
        background: #ffffff !important;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }

    .invoice-sheet--bw,
    .invoice-sheet--bw * {
        -webkit-print-color-adjust: economy;
        print-color-adjust: economy;
    }

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

    .card,
    .invoice-card {
        box-shadow: none !important;
        border: 0 !important;
        border-radius: 0 !important;
        margin: 0 !important;
        padding: 0 !important;
        background: #ffffff !important;
    }

    .invoice-sheet {
    width: auto;
    min-height: 10.2in;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

    .invoice-print-area {
        display: block !important;
    }

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

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

    @page {
        size: letter;
        margin: 0.42in 0.55in 0.35in;
    }
}
</style>

<section class="card invoice-card">

    <div class="invoice-actions">
        <button type="button" class="button" onclick="window.print();">
            Print <?= $is_bulk ? 'Invoices' : 'Invoice' ?>
        </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="invoice-print-area">
    <?php foreach ($orders_for_print as $print_order): ?>
        <?php
        $order = $print_order['order'];
        $items = $print_order['items'];

        $subtotal_amount = max(0, (float) ($order['total_amount'] ?? 0));
        $discount_amount = max(0, (float) ($order['order_discount_amount'] ?? 0));

        /* shipping_cost is internal; order_shipping_amount is customer-facing. */
        $shipping_amount = max(0, (float) ($order['order_shipping_amount'] ?? 0));
        $total_amount = max(0, $subtotal_amount - $discount_amount + $shipping_amount);
        $invoice_date = ($settings['invoice_date_mode'] ?? 'order_date') === 'print_date'
            ? date('n/j/Y')
            : sparrow_invoice_date($order['order_date'] ?? '');
        ?>
    <section class="invoice-sheet invoice-sheet--<?= sparrow_escape($invoice_print_mode) ?>">

        <header class="invoice-header invoice-header--<?= sparrow_escape($invoice_header_layout) ?><?= $show_logo ? '' : ' invoice-header--no-logo' ?><?= $show_header_image ? '' : ' invoice-header--no-title-image' ?>">
            <?php if ($show_logo): ?>
            <div class="invoice-logo-area">
                <img
                    src="<?= sparrow_escape($logo_url) ?>"
                    alt="<?= sparrow_escape($business_name) ?>"
                    class="invoice-logo"
                >
            </div>
            <?php endif; ?>

            <div class="invoice-title-area">
                <?php if ($show_header_image): ?>
                <img
                    src="<?= sparrow_escape($invoice_header_url) ?>"
                    alt="Invoice"
                    class="invoice-title-image"
                >
                <?php endif; ?>

                <table class="invoice-info-table">
                    <thead>
                        <tr>
                            <th>Customer</th>
                            <th>Invoice</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><?= sparrow_escape($order['customer_name'] ?? '') ?></td>
                            <td><?= sparrow_escape($order['order_number'] ?? '') ?></td>
                            <td><?= sparrow_escape($invoice_date) ?></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </header>

        <table class="invoice-items">
            <thead>
                <tr>
					<th class="description-col">Item</th>
                    <th class="qty-col">Quantity</th>
                    <th class="unit-col">Unit Price</th>
                    <th class="total-col">Total</th>
                </tr>
            </thead>
            <tbody>
<?php
$row_count = 14; // total number of rows you want
$printed_rows = 0;

foreach ($items as $item):
    $qty = (int) ($item['quantity'] ?? 1);

    $unit_price = $item['unit_price']
        ?? $item['price']
        ?? $item['item_price']
        ?? null;

    $line_total = $item['line_total']
        ?? $item['total']
        ?? null;

    if ($line_total === null && $unit_price !== null) {
        $line_total = (float) $unit_price * $qty;
    }
?>
    <tr>
        <td class="description-col"><?= sparrow_escape(sparrow_invoice_item_description($item)) ?></td>
        <td class="qty-col"><?= $qty ?></td>
        <td class="unit-col"><?= $unit_price === null ? '' : sparrow_invoice_money($unit_price) ?></td>
        <td class="total-col"><?= $line_total === null ? '' : sparrow_invoice_money($line_total) ?></td>
    </tr>
<?php
    $printed_rows++;
endforeach;

// Add blank rows to pad the table
for ($i = $printed_rows; $i < $row_count; $i++):
?>
    <tr>
        <td class="description-col">&nbsp;</td>
        <td class="qty-col">&nbsp;</td>
        <td class="unit-col">&nbsp;</td>
        <td class="total-col">&nbsp;</td>
    </tr>
<?php endfor; ?>
</tbody>
        </table>

        <section class="invoice-lower<?= $show_thank_you ? '' : ' invoice-lower--totals-only' ?>">
    <?php if ($show_thank_you): ?>
    <div class="invoice-thank-you">
        <p><?= nl2br(sparrow_escape($settings['invoice_thank_you'] ?? 'Thank you for supporting Sparrow & Seed Creations!')) ?></p>
        <img src="<?= sparrow_escape($signature_url) ?>" class="invoice-signature" alt="<?= sparrow_escape($business_name) ?>">
    </div>
    <?php endif; ?>

    <div>
        <table class="invoice-totals-table">
            <tbody>
                <tr>
                    <td>Subtotal</td>
                    <td><?= sparrow_invoice_money($subtotal_amount) ?></td>
                </tr>
                <tr>
                    <td>Discount</td>
                    <td><?= sparrow_invoice_money($discount_amount) ?></td>
                </tr>
                <tr>
                    <td>Shipping</td>
                    <td><?= sparrow_invoice_money($shipping_amount) ?></td>
                </tr>
                <tr class="total-row">
                    <td>Total</td>
                    <td><?= sparrow_invoice_money($total_amount) ?></td>
                </tr>
            </tbody>
        </table>
    </div>
</section>

        <?php if ($show_footer): ?>
        <footer class="invoice-footer">
    <div class="invoice-footer-line">
        <span class="invoice-footer-heart">♡</span>
    </div>

    <div class="invoice-footer-contact">
                <?php if ($footer_social): ?>
                    <?= implode(' &nbsp; | &nbsp; ', array_map('sparrow_escape', $footer_social)) ?>
                <?php endif; ?>
                <?php if ($footer_social && $footer_contact): ?><br><?php endif; ?>
                <?php if ($footer_contact): ?>
                    <?= implode(' &nbsp; | &nbsp; ', array_map('sparrow_escape', $footer_contact)) ?>
                <?php endif; ?>
            </div>
        </footer>
        <?php endif; ?>

        <?php if ($show_page_number): ?>
        <div class="invoice-page-number">Page 1 of 1</div>
        <?php endif; ?>

    </section>
    <?php endforeach; ?>
    </div>
</section>

<?php sparrow_backyard_footer(); ?>
