<?php

declare(strict_types=1);

require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/orders.php';
require_once __DIR__ . '/../app/supplier-splitter.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/settings.php';

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

$supplier_settings = sparrow_get_settings($pdo, [
    'supplier_names',
    'supplier_default_travel_cost',
    'supplier_gang_sheet_width',
    'supplier_gang_sheet_height',
    'supplier_gang_sheet_mode',
]);

$supplier_names = array_values(array_unique(array_filter(array_map(
    'trim',
    preg_split('/\r\n|\r|\n/', $supplier_settings['supplier_names'] ?? '') ?: []
))));

if (!$supplier_names) {
    $supplier_names = ['Jiffy', 'ShirtSpace', 'Texas Vinyl Supply', 'Amazon', 'Other'];
}

$supplier_default_travel_cost = is_numeric(
    $supplier_settings['supplier_default_travel_cost'] ?? null
)
    ? number_format((float) $supplier_settings['supplier_default_travel_cost'], 2, '.', '')
    : '0.00';

$supplier_gang_sheet_width = is_numeric(
    $supplier_settings['supplier_gang_sheet_width'] ?? null
)
    ? max(0.01, (float) $supplier_settings['supplier_gang_sheet_width'])
    : 22.00;

$supplier_gang_sheet_height = is_numeric(
    $supplier_settings['supplier_gang_sheet_height'] ?? null
)
    ? max(0.01, (float) $supplier_settings['supplier_gang_sheet_height'])
    : 24.00;

$supplier_gang_sheet_mode = in_array(
    $supplier_settings['supplier_gang_sheet_mode'] ?? '',
    ['used', 'full'],
    true
)
    ? (string) $supplier_settings['supplier_gang_sheet_mode']
    : 'used';

$notice = '';
$error = '';

$edit_receipt_id = isset($_GET['edit_id']) ? (int) $_GET['edit_id'] : 0;
$edit_receipt = null;
$edit_items = [];

function supplier_page_e($value): string
{
    return htmlspecialchars((string) ($value ?? ''), ENT_QUOTES, 'UTF-8');
}

function supplier_page_money($value): string
{
    return '$' . number_format((float) ($value ?? 0), 2);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
	
	if ($action === 'apply_ready_supplier_receipts') {
    try {
        $confirmation = trim(
            (string) ($_POST['apply_confirmation'] ?? '')
        );

        if ($confirmation !== 'APPLY') {
            throw new RuntimeException(
                'Type APPLY in the confirmation box before applying costs.'
            );
        }

        $apply_result = sparrow_supplier_apply_ready_receipts();

        $query = http_build_query([
            'applied' => 1,
            'applied_rows' => $apply_result['applied_count'] ?? 0,
            'applied_orders' => $apply_result['order_count'] ?? 0,
            'applied_total' => $apply_result['applied_total'] ?? 0,
        ]);

        header(
            'Location: supplier-splitter.php?' . $query
        );
        exit;
    } catch (Throwable $e) {
        $error = 'Supplier costs could not be applied: '
            . $e->getMessage();
    }
}

    if ($action === 'update_supplier_status') {
        try {
            $receipt_id = (int) ($_POST['receipt_id'] ?? 0);
            $status = (string) ($_POST['status'] ?? 'draft');

            if ($receipt_id <= 0) {
                throw new RuntimeException('Missing supplier receipt draft ID.');
            }

            sparrow_supplier_update_status($receipt_id, $status);

            header('Location: supplier-splitter.php?status_updated=1&id=' . $receipt_id);
            exit;
        } catch (Throwable $e) {
            $error = 'Supplier draft status could not be updated: ' . $e->getMessage();
        }
    }
	
	    if ($action === 'delete_supplier_receipt') {
        try {
            $receipt_id = (int) ($_POST['receipt_id'] ?? 0);

            if ($receipt_id <= 0) {
                throw new RuntimeException('Missing supplier receipt draft ID.');
            }

            sparrow_supplier_delete_receipt($receipt_id);

            header('Location: supplier-splitter.php?deleted=1');
            exit;
        } catch (Throwable $e) {
            $error = 'Supplier draft could not be deleted: ' . $e->getMessage();
        }
    }

    if ($action === 'save_supplier_receipt') {
        try {
            $items = [];

            $item_types = $_POST['item_type'] ?? [];
            $goes_with_order_numbers = $_POST['goes_with_order_number'] ?? [];
            $descriptions = $_POST['description'] ?? [];
            $quantities = $_POST['quantity'] ?? [];
            $unit_costs = $_POST['unit_cost'] ?? [];
            $item_costs = $_POST['item_cost'] ?? [];
            $accuracies = $_POST['accuracy'] ?? [];
            $possible_order_uses = $_POST['possible_order_use'] ?? [];
            $item_notes = $_POST['item_notes'] ?? [];

            $row_count = max(
                count($item_types),
                count($descriptions),
                count($quantities),
                count($unit_costs),
                count($item_costs),
                1
            );

            for ($i = 0; $i < $row_count; $i++) {
                $items[] = [
                    'item_type' => $item_types[$i] ?? 'Sparrow Order',
                    'goes_with_order_number' => $goes_with_order_numbers[$i] ?? '',
                    'description' => $descriptions[$i] ?? '',
                    'quantity' => $quantities[$i] ?? 1,
                    'unit_cost' => $unit_costs[$i] ?? 0,
                    'item_cost' => $item_costs[$i] ?? 0,
                    'accuracy' => $accuracies[$i] ?? 'Exact',
                    'possible_order_use' => $possible_order_uses[$i] ?? 0,
                    'notes' => $item_notes[$i] ?? '',
                ];
            }

            $receipt_id = sparrow_supplier_create_receipt($_POST, $items);

            header('Location: supplier-splitter.php?saved=1&id=' . $receipt_id);
            exit;
        } catch (Throwable $e) {
            $error = 'Supplier draft could not be saved: ' . $e->getMessage();
        }
    }
	
	    if ($action === 'update_supplier_receipt') {
        try {
            $receipt_id = (int) ($_POST['receipt_id'] ?? 0);

            if ($receipt_id <= 0) {
                throw new RuntimeException('Missing supplier receipt draft ID.');
            }

            $items = [];

            $item_types = $_POST['item_type'] ?? [];
            $goes_with_order_numbers = $_POST['goes_with_order_number'] ?? [];
            $descriptions = $_POST['description'] ?? [];
            $quantities = $_POST['quantity'] ?? [];
            $unit_costs = $_POST['unit_cost'] ?? [];
            $item_costs = $_POST['item_cost'] ?? [];
            $accuracies = $_POST['accuracy'] ?? [];
            $possible_order_uses = $_POST['possible_order_use'] ?? [];
            $item_notes = $_POST['item_notes'] ?? [];

            $row_count = max(
                count($item_types),
                count($descriptions),
                count($quantities),
                count($unit_costs),
                count($item_costs),
                1
            );

            for ($i = 0; $i < $row_count; $i++) {
                $items[] = [
                    'item_type' => $item_types[$i] ?? 'Sparrow Order',
                    'goes_with_order_number' => $goes_with_order_numbers[$i] ?? '',
                    'description' => $descriptions[$i] ?? '',
                    'quantity' => $quantities[$i] ?? 1,
                    'unit_cost' => $unit_costs[$i] ?? 0,
                    'item_cost' => $item_costs[$i] ?? 0,
                    'accuracy' => $accuracies[$i] ?? 'Exact',
                    'possible_order_use' => $possible_order_uses[$i] ?? 0,
                    'notes' => $item_notes[$i] ?? '',
                ];
            }

            sparrow_supplier_update_receipt($receipt_id, $_POST, $items);

            header('Location: supplier-splitter.php?updated=1&id=' . $receipt_id);
            exit;
        } catch (Throwable $e) {
            $error = 'Supplier draft could not be updated: ' . $e->getMessage();
        }
    }
}

if (isset($_GET['saved'])) {
    $notice = 'Supplier receipt draft saved. Nothing was applied to order costs.';
}

if (isset($_GET['updated'])) {
    $notice = 'Supplier receipt draft updated. Nothing was applied to order costs.';
}

if (isset($_GET['status_updated'])) {
    $notice = 'Supplier receipt draft status updated. Nothing was applied to order costs.';
}

if (isset($_GET['deleted'])) {
    $notice = 'Supplier receipt draft deleted. Nothing was changed on order costs.';
}

if (isset($_GET['applied'])) {
    $applied_rows = (int) ($_GET['applied_rows'] ?? 0);
    $applied_orders = (int) ($_GET['applied_orders'] ?? 0);
    $applied_total = (float) ($_GET['applied_total'] ?? 0);

    $notice =
        number_format($applied_rows)
        . ' supplier cost row(s) applied to '
        . number_format($applied_orders)
        . ' order(s). Total internal cost applied: $'
        . number_format($applied_total, 2)
        . '.';
}

$receipts = sparrow_supplier_get_receipts();
$ready_preview_rows = sparrow_supplier_get_ready_apply_preview();
$ready_preview_summary = [
    'row_count' => count($ready_preview_rows),
    'matched_count' => 0,
    'missing_count' => 0,
    'already_applied_count' => 0,
    'not_applied_count' => 0,
    'estimated_total' => 0.00,
];

$ready_preview_can_apply_later = false;
$ready_preview_lock_messages = [];

foreach ($ready_preview_rows as $preview_row) {
    if (!empty($preview_row['order_found'])) {
        $ready_preview_summary['matched_count']++;
    } else {
        $ready_preview_summary['missing_count']++;
    }

    if (!empty($preview_row['already_applied'])) {
        $ready_preview_summary['already_applied_count']++;
    } else {
        $ready_preview_summary['not_applied_count']++;
    }

    $ready_preview_summary['estimated_total'] +=
        (float) ($preview_row['total_internal_cost'] ?? 0);
}

if ($ready_preview_summary['row_count'] <= 0) {
    $ready_preview_lock_messages[] =
        'No Ready to Apply preview rows found yet.';
}

if ($ready_preview_summary['missing_count'] > 0) {
    $ready_preview_lock_messages[] =
        'One or more preview rows do not match an order yet.';
}

if ($ready_preview_summary['already_applied_count'] > 0) {
    $ready_preview_lock_messages[] =
        'One or more preview rows have already been applied.';
}

if (
    $ready_preview_summary['row_count'] > 0
    && $ready_preview_summary['missing_count'] === 0
    && $ready_preview_summary['already_applied_count'] === 0
) {
    $ready_preview_can_apply_later = true;
}

$ready_preview_order_totals = [];

foreach ($ready_preview_rows as $preview_row) {
    $order_number = (string) ($preview_row['order_number'] ?? '');

    if ($order_number === '') {
        continue;
    }

    if (!isset($ready_preview_order_totals[$order_number])) {
        $ready_preview_order_totals[$order_number] = [
            'order_number' => $order_number,
            'customer_name' => $preview_row['customer_name'] ?? '',
            'order_found' => !empty($preview_row['order_found']),
            'receipt_count' => 0,
            'item_total' => 0.00,
            'shipping_share' => 0.00,
            'tax_share' => 0.00,
            'travel_share' => 0.00,
            'discount_share' => 0.00,
            'total_internal_cost' => 0.00,
            'suppliers' => [],
        ];
    }

    $ready_preview_order_totals[$order_number]['receipt_count']++;
    $ready_preview_order_totals[$order_number]['item_total'] += (float) ($preview_row['item_total'] ?? 0);
    $ready_preview_order_totals[$order_number]['shipping_share'] += (float) ($preview_row['shipping_share'] ?? 0);
    $ready_preview_order_totals[$order_number]['tax_share'] += (float) ($preview_row['tax_share'] ?? 0);
    $ready_preview_order_totals[$order_number]['travel_share'] += (float) ($preview_row['travel_share'] ?? 0);
    $ready_preview_order_totals[$order_number]['discount_share'] += (float) ($preview_row['discount_share'] ?? 0);
    $ready_preview_order_totals[$order_number]['total_internal_cost'] += (float) ($preview_row['total_internal_cost'] ?? 0);

    $supplier_name = (string) ($preview_row['supplier_name'] ?? '');

    if ($supplier_name !== '' && !in_array($supplier_name, $ready_preview_order_totals[$order_number]['suppliers'], true)) {
        $ready_preview_order_totals[$order_number]['suppliers'][] = $supplier_name;
    }
}

$tracked_non_order_items = sparrow_supplier_get_tracked_non_order_items();

$tracked_non_order_summary = [
    'count' => count($tracked_non_order_items),
    'total' => 0.00,
    'by_type' => [],
];

foreach ($tracked_non_order_items as $tracked_item) {
    $type = (string) ($tracked_item['item_type'] ?? 'Other');
    $amount = (float) ($tracked_item['item_cost'] ?? 0);

    $tracked_non_order_summary['total'] += $amount;

    if (!isset($tracked_non_order_summary['by_type'][$type])) {
        $tracked_non_order_summary['by_type'][$type] = [
            'type' => $type,
            'count' => 0,
            'total' => 0.00,
        ];
    }

    $tracked_non_order_summary['by_type'][$type]['count']++;
    $tracked_non_order_summary['by_type'][$type]['total'] += $amount;
}

if ($edit_receipt_id > 0) {
    $edit_receipt = sparrow_supplier_get_receipt($edit_receipt_id);

    if ($edit_receipt) {
        $edit_items = sparrow_supplier_get_receipt_items($edit_receipt_id);
    } else {
        $error = 'That supplier receipt draft could not be found.';
        $edit_receipt_id = 0;
    }
}

sparrow_backyard_header('Supplier Splitter');
?>

<?php if ($notice): ?>
    <div class="notice-success">
        <?= supplier_page_e($notice) ?>
    </div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="notice-error">
        <?= supplier_page_e($error) ?>
    </div>
<?php endif; ?>

<section class="card">
    <h1>Supplier Splitter</h1>
	
		<nav class="supplier-section-tabs">
    <a class="button button-secondary" href="#supplier-entry">
        New Receipt
    </a>

    <a class="button button-secondary" href="#supplier-drafts">
        Receipt Drafts
    </a>

    <a class="button button-secondary" href="#ready-to-apply">
        Ready to Apply
    </a>

    <a
    class="button button-secondary"
    href="<?= supplier_page_e(
        sparrow_url('/backyard/supplier-history.php')
    ) ?>"
>
    Applied History
</a>

    <a class="button button-secondary" href="#tracked-non-order">
        Non-Order Items
    </a>
</nav>

    <p class="muted">
        Save supplier receipt drafts first. Preview and apply will be added later.
        This first version only saves the receipt and item rows.
    </p>
	</section>

<form method="post">
    <?php if ($edit_receipt): ?>
    <input type="hidden" name="action" value="update_supplier_receipt">
    <input type="hidden" name="receipt_id" value="<?= (int) $edit_receipt['id'] ?>">
<?php else: ?>
    <input type="hidden" name="action" value="save_supplier_receipt">
<?php endif; ?>

    <section
    class="card supplier-splitter-card"
    id="supplier-entry"
>
        <h2>Supplier Totals</h2>

        <p class="muted">
            Enter one supplier receipt or order at a time. If one Sparrow order uses supplies from multiple suppliers,
            make one split for each supplier purchase.
        </p>

        <div class="supplier-totals-grid">
            <div>
                <label for="supplier_name">Supplier</label>
                <select id="supplier_name" name="supplier_name" required>
    <?php $selected_supplier = $edit_receipt['supplier_name'] ?? ''; ?>
    <?php if ($selected_supplier !== '' && !in_array($selected_supplier, $supplier_names, true)): ?>
        <?php array_unshift($supplier_names, $selected_supplier); ?>
    <?php endif; ?>
    <option value="">Choose supplier...</option>
    <?php foreach ($supplier_names as $supplier_name): ?>
        <option
            value="<?= supplier_page_e($supplier_name) ?>"
            <?= $selected_supplier === $supplier_name ? 'selected' : '' ?>
        ><?= supplier_page_e($supplier_name) ?></option>
    <?php endforeach; ?>
</select>
            </div>

            <div>
                <label for="receipt_number">Supplier Receipt / Order #</label>
                <input
    type="text"
    id="receipt_number"
    name="receipt_number"
    value="<?= supplier_page_e($edit_receipt['receipt_number'] ?? '') ?>"
    placeholder="Example: Jiffy #12345"
>
            </div>

            <div>
                <label for="order_date">Supplier Order Date</label>
                <input
    type="date"
    id="order_date"
    name="order_date"
    value="<?= supplier_page_e($edit_receipt['order_date'] ?? '') ?>"
>
            </div>

            <div>
                <label for="subtotal">Subtotal Before Discount</label>
                <input
    type="number"
    step="0.01"
    id="subtotal"
    name="subtotal"
    value="<?= supplier_page_e($edit_receipt['subtotal'] ?? '0.00') ?>"
>
            </div>

            <div>
                <label for="shipping_amount">Shipping Paid</label>
                <input
    type="number"
    step="0.01"
    id="shipping_amount"
    name="shipping_amount"
    value="<?= supplier_page_e($edit_receipt['shipping_amount'] ?? '0.00') ?>"
>
            </div>

            <div>
                <label for="discount_amount">Discount / Credit Used</label>
                <input
    type="number"
    step="0.01"
    id="discount_amount"
    name="discount_amount"
    value="<?= supplier_page_e($edit_receipt['discount_amount'] ?? '0.00') ?>"
>
            </div>

            <div>
                <label for="tax_amount">Tax Paid</label>
                <input
    type="number"
    step="0.01"
    id="tax_amount"
    name="tax_amount"
    value="<?= supplier_page_e($edit_receipt['tax_amount'] ?? '0.00') ?>"
>
            </div>

            <div>
                <label for="travel_amount">Travel / Pickup Cost</label>
                <input
    type="number"
    step="0.01"
    id="travel_amount"
    name="travel_amount"
    value="<?= supplier_page_e($edit_receipt['travel_amount'] ?? $supplier_default_travel_cost) ?>"
    placeholder="5.00"
>
            </div>
        </div>

        <div class="supplier-notes-field">
            <label for="notes">Supplier Notes</label>
            <textarea
    id="notes"
    name="notes"
    rows="4"
    placeholder="Example: Jiffy order split between SSC-024, SSC-025, a gift, and one personal test print."
><?= supplier_page_e($edit_receipt['notes'] ?? '') ?></textarea>
        </div>

        <p class="supplier-save-note">
            Supplier totals will save with the item rows when you click Save Supplier Split Draft below.
        </p>
		</section>
		
<section class="card supplier-splitter-card">
    <details class="supplier-collapsible">
        <summary>
            <span>Gang Sheet Split Calculator</span>
            <small>Open when splitting a gang sheet by design size</small>
        </summary>

        <p class="muted">
            Use this to split one gang sheet across multiple orders by design size. This calculator does not save anything by itself.
            Click Send Calculator Rows to Supplier Items, then save the supplier draft below.
        </p>

    <div class="gang-sheet-grid">
        <div>
            <label for="gang_sheet_width">Sheet Width</label>
            <input type="number" step="0.01" id="gang_sheet_width" value="<?= supplier_page_e(number_format($supplier_gang_sheet_width, 2, '.', '')) ?>">
        </div>

        <div>
            <label for="gang_sheet_height">Sheet Height</label>
            <input type="number" step="0.01" id="gang_sheet_height" value="<?= supplier_page_e(number_format($supplier_gang_sheet_height, 2, '.', '')) ?>">
        </div>

        <div>
            <label for="gang_sheet_cost">Cost to Split</label>
            <input type="number" step="0.01" id="gang_sheet_cost" value="0.00">
        </div>

        <div>
            <label for="gang_sheet_mode">Split Mode</label>
            <select id="gang_sheet_mode">
                <option value="used" <?= $supplier_gang_sheet_mode === 'used' ? 'selected' : '' ?>>Split by used design area</option>
                <option value="full" <?= $supplier_gang_sheet_mode === 'full' ? 'selected' : '' ?>>Split by full sheet area</option>
            </select>
        </div>
    </div>

    <div class="gang-sheet-summary">
        <div>
            <span>Full Sheet Area</span>
            <strong id="gang_full_area"><?= supplier_page_e(number_format($supplier_gang_sheet_width * $supplier_gang_sheet_height, 2, '.', '')) ?> sq in</strong>
        </div>

        <div>
            <span>Total Used Area</span>
            <strong id="gang_used_area">0 sq in</strong>
        </div>

        <div>
            <span>Rate</span>
            <strong id="gang_rate">$0.00 / sq in</strong>
        </div>

        <div>
            <span>Calculated Total</span>
            <strong id="gang_calculated_total">$0.00</strong>
        </div>
    </div>

    <div class="table-wrap">
        <table class="gang-sheet-table" id="gang-sheet-table">
            <thead>
                <tr>
                    <th>Type</th>
                    <th>Order / Use</th>
                    <th>Description</th>
                    <th>Width</th>
                    <th>Height</th>
                    <th>Qty</th>
                    <th>Sq In</th>
                    <th>Cost</th>
                    <th></th>
                </tr>
            </thead>

            <tbody>
                <?php for ($g = 0; $g < 5; $g++): ?>
                    <tr>
                        <td>
                            <select class="gang-type">
                                <option value="Sparrow Order">Sparrow Order</option>
                                <option value="Gift">Gift</option>
                                <option value="Free Add-On">Free Add-On</option>
                                <option value="Personal">Personal</option>
                                <option value="Freebie">Freebie</option>
                                <option value="Practice/Test">Practice/Test</option>
								<option value="Possible Order Use">Possible Order Use</option>
                                <option value="Waste">Waste</option>
                                <option value="Other">Other</option>
                            </select>
                        </td>

                        <td>
                            <input type="text" class="gang-order" placeholder="021, SSC-021, Personal, Waste">
                        </td>

                        <td>
                            <input type="text" class="gang-description" placeholder="Design name or shirt">
                        </td>

                        <td>
                            <input type="number" step="0.01" class="gang-width" value="">
                        </td>

                        <td>
                            <input type="number" step="0.01" class="gang-height" value="">
                        </td>

                        <td>
                            <input type="number" step="1" class="gang-qty" value="1">
                        </td>

                        <td>
                            <strong class="gang-row-area">0</strong>
                        </td>

                        <td>
                            <strong class="gang-row-cost">$0.00</strong>
                        </td>

                        <td>
                            <button type="button" class="button button-secondary gang-remove-row">
                                Remove
                            </button>
                        </td>
                    </tr>
                <?php endfor; ?>
            </tbody>
        </table>
    </div>

    <div class="form-actions">
    <button type="button" class="button button-secondary" id="gang-add-row">
        Add Calculator Row
    </button>

    <button type="button" class="button" id="gang-send-to-items">
        Send Calculator Rows to Supplier Items
    </button>
</div>
        </details>
</section>

<section class="card supplier-splitter-card">
            <h2>Supplier Items</h2>

            <p class="muted">
                Add each receipt line below. Empty description rows will be skipped.
            </p>

        <div class="table-wrap">
            <table class="supplier-splitter-table" id="supplier-items-table">
                <thead>
                    <tr>
                        <th>Type</th>
                        <th>Goes With / Order #</th>
                        <th>Description</th>
                        <th>Qty</th>
                        <th>Unit Cost</th>
                        <th>Item Cost</th>
                        <th>Accuracy</th>
                        <th>Possible Order Use</th>
                        <th>Notes</th>
                        <th></th>
                    </tr>
                </thead>

                <tbody>
                    <?php
$form_items = $edit_items ?: array_fill(0, 5, []);

foreach ($form_items as $i => $form_item):
    $selected_type = $form_item['item_type'] ?? 'Sparrow Order';
    $selected_accuracy = $form_item['accuracy'] ?? 'Exact';
?>
    <tr>
        <td>
            <select name="item_type[]">
                <?php
                $type_options = [
    'Sparrow Order',
    'Gift',
    'Free Add-On',
    'Personal',
    'Freebie',
    'Practice/Test',
    'Possible Order Use',
    'Waste',
    'Other',
];
                ?>

                <?php foreach ($type_options as $type_option): ?>
                    <option
                        value="<?= supplier_page_e($type_option) ?>"
                        <?= $selected_type === $type_option ? 'selected' : '' ?>
                    >
                        <?= supplier_page_e($type_option) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </td>

        <td>
            <input
                type="text"
                name="goes_with_order_number[]"
                value="<?= supplier_page_e($form_item['goes_with_order_number'] ?? '') ?>"
                placeholder="SSC-###"
            >
        </td>

        <td>
            <input
                type="text"
                name="description[]"
                value="<?= supplier_page_e($form_item['description'] ?? '') ?>"
            >
        </td>

        <td>
            <input
                type="number"
                step="0.01"
                name="quantity[]"
                value="<?= supplier_page_e($form_item['quantity'] ?? '1') ?>"
            >
        </td>

        <td>
            <input
    type="number"
    step="0.0001"
    name="unit_cost[]"
    value="<?= supplier_page_e($form_item['unit_cost'] ?? '0.00') ?>"
>
        </td>

        <td>
            <input
                type="number"
                step="0.01"
                name="item_cost[]"
                value="<?= supplier_page_e($form_item['item_cost'] ?? '0.00') ?>"
            >
        </td>

        <td>
            <select name="accuracy[]">
                <?php foreach (['Exact', 'Estimated', 'Check Label'] as $accuracy_option): ?>
                    <option
                        value="<?= supplier_page_e($accuracy_option) ?>"
                        <?= $selected_accuracy === $accuracy_option ? 'selected' : '' ?>
                    >
                        <?= supplier_page_e($accuracy_option) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </td>

        <td class="supplier-center">
            <input
                type="checkbox"
                name="possible_order_use[<?= (int) $i ?>]"
                value="1"
                <?= !empty($form_item['possible_order_use']) ? 'checked' : '' ?>
            >
        </td>

        <td>
            <input
                type="text"
                name="item_notes[]"
                value="<?= supplier_page_e($form_item['notes'] ?? '') ?>"
            >
        </td>

        <td>
            <button type="button" class="button button-secondary supplier-remove-row">
                Remove
            </button>
        </td>
    </tr>
<?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="form-actions">
            <button type="button" class="button button-secondary" id="supplier-add-row">
                Add Item Row
            </button>

            <button type="submit" class="button">
    <?= $edit_receipt ? 'Update Supplier Split Draft' : 'Save Supplier Split Draft' ?>
</button>
<?php if ($edit_receipt): ?>
    <a class="button button-secondary" href="supplier-splitter.php">
        Cancel Edit
    </a>
<?php endif; ?>
        </div>
		</section>
    </form>


<section class="card" id="supplier-drafts">
    <h2>Supplier Receipt Drafts</h2>

    <?php if (!$receipts): ?>
        <p class="muted">No supplier receipt drafts yet.</p>
    <?php else: ?>
        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
					
                        <th>ID</th>
                        <th>Supplier</th>
                        <th>Receipt #</th>
                        <th>Order Date</th>
                        <th>Status</th>
                        <th>Items</th>
                        <th>Items Total</th>
                        <th>Shipping</th>
                        <th>Tax</th>
                        <th>Travel</th>
                        <th>Discount/Credit</th>
                        <th>Created</th>
						<th>Details</th>
						<th>Actions</th>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach ($receipts as $receipt): ?>
                        <tr>
                            <td><?= (int) $receipt['id'] ?></td>

                            <td>
                                <strong><?= supplier_page_e($receipt['supplier_name']) ?></strong>
                            </td>

                            <td><?= supplier_page_e($receipt['receipt_number']) ?></td>
                            <td><?= supplier_page_e($receipt['order_date']) ?></td>

                            <td>
    <?php
    $receipt_status = (string) ($receipt['status'] ?? 'draft');
    $status_class = 'supplier-status-' . str_replace('_', '-', $receipt_status);
    ?>

    <span class="status-pill supplier-status-pill <?= supplier_page_e($status_class) ?>">
        <?= supplier_page_e(sparrow_supplier_status_label($receipt_status)) ?>
    </span>
</td>

                            <td><?= (int) $receipt['item_count'] ?></td>
                            <td><?= supplier_page_money($receipt['items_total']) ?></td>
                            <td><?= supplier_page_money($receipt['shipping_amount']) ?></td>
                            <td><?= supplier_page_money($receipt['tax_amount']) ?></td>
                            <td><?= supplier_page_money($receipt['travel_amount']) ?></td>
                            <td><?= supplier_page_money($receipt['discount_amount']) ?></td>
                            <td><?= supplier_page_e($receipt['created_at']) ?></td>

<td>
    <?php if ((int) ($receipt['item_count'] ?? 0) > 0): ?>
        <button
            type="button"
            class="button button-secondary button-small supplier-items-toggle"
            data-receipt-id="<?= (int) $receipt['id'] ?>"
            aria-expanded="false"
        >
            View Items
        </button>
    <?php else: ?>
        <span class="muted">No items</span>
    <?php endif; ?>
</td>

<td class="supplier-actions-cell">
    <div class="supplier-actions-inline">
        <?php if (($receipt['status'] ?? 'draft') === 'applied'): ?>

    <span class="status-pill supplier-applied-pill">
        Locked After Apply
    </span>

<?php else: ?>

    <a
        class="button button-secondary button-small"
        href="supplier-splitter.php?edit_id=<?= (int) $receipt['id'] ?>"
    >
        Edit
    </a>

    <form
        method="post"
        class="supplier-delete-form"
        onsubmit="return confirm(
            'Delete this supplier receipt draft? This will remove its item rows too. Order costs will not be changed.'
        );"
    >
        <input
            type="hidden"
            name="action"
            value="delete_supplier_receipt"
        >

        <input
            type="hidden"
            name="receipt_id"
            value="<?= (int) $receipt['id'] ?>"
        >

        <button
            type="submit"
            class="button button-secondary button-small supplier-delete-button"
        >
            Delete
        </button>
    </form>

    <form method="post" class="supplier-status-form">
        <input
            type="hidden"
            name="action"
            value="update_supplier_status"
        >

        <input
            type="hidden"
            name="receipt_id"
            value="<?= (int) $receipt['id'] ?>"
        >

        <select
            name="status"
            class="supplier-status-select"
        >
            <?php foreach (
                sparrow_supplier_allowed_statuses()
                as $status_value => $status_label
            ): ?>
                <option
                    value="<?= supplier_page_e($status_value) ?>"
                    <?= (
                        ($receipt['status'] ?? 'draft')
                        === $status_value
                    ) ? 'selected' : '' ?>
                >
                    <?= supplier_page_e($status_label) ?>
                </option>
            <?php endforeach; ?>
        </select>

        <button
            type="submit"
            class="button button-secondary button-small"
        >
            Save
        </button>
    </form>

<?php endif; ?>
    </div>
</td>
                        </tr>

                        <?php $receipt_items = sparrow_supplier_get_receipt_items((int) $receipt['id']); ?>

                        <?php if ($receipt_items): ?>
    <tr
        class="supplier-items-detail-row"
        id="supplier-items-<?= (int) $receipt['id'] ?>"
        style="display: none;"
    >
        <td></td>
        <td colspan="13">
                                    <div class="supplier-mini-items">
                                        <strong>Items:</strong>

                                        <ul>
                                            <?php foreach ($receipt_items as $item): ?>
                                                <li>
                                                    <?= supplier_page_e($item['item_type']) ?> —
                                                    <?= supplier_page_e($item['description']) ?>

                                                    <?php if (!empty($item['goes_with_order_number'])): ?>
                                                        for <?= supplier_page_e($item['goes_with_order_number']) ?>
                                                    <?php endif; ?>

                                                    —
                                                    <?= supplier_page_money($item['item_cost']) ?>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    </div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</section>

<section class="card" id="ready-to-apply">
    <h2>Ready to Apply Preview</h2>

    <p class="muted">
        This preview only includes supplier drafts marked Ready to Apply. Nothing here changes order costs yet.
    </p>
	
	<?php if ($ready_preview_rows): ?>
<div class="supplier-preview-summary supplier-preview-summary-six">
    <div>
        <span>Preview Rows</span>
        <strong><?= number_format((int) $ready_preview_summary['row_count']) ?></strong>
    </div>

    <div>
        <span>Matched</span>
        <strong><?= number_format((int) $ready_preview_summary['matched_count']) ?></strong>
    </div>

    <div>
        <span>Not Found</span>
        <strong><?= number_format((int) $ready_preview_summary['missing_count']) ?></strong>
    </div>

    <div>
        <span>Not Applied</span>
        <strong><?= number_format((int) $ready_preview_summary['not_applied_count']) ?></strong>
    </div>

    <div>
        <span>Already Applied</span>
        <strong><?= number_format((int) $ready_preview_summary['already_applied_count']) ?></strong>
    </div>

    <div>
        <span>Estimated Total</span>
        <strong><?= supplier_page_money($ready_preview_summary['estimated_total']) ?></strong>
    </div>
</div>

<?php if ($ready_preview_can_apply_later): ?>
    <div class="supplier-readiness-message supplier-readiness-ready">
        <strong>Ready to apply.</strong>
        All preview rows are matched and have not been applied.
    </div>

    <form
        method="post"
        class="supplier-apply-form"
        onsubmit="return confirm(
            'Apply these supplier costs to the matched orders? This will change order internal costs.'
        );"
    >
        <input
            type="hidden"
            name="action"
            value="apply_ready_supplier_receipts"
        >

        <div style="max-width: 420px; margin-top: 16px;">
            <label for="apply_confirmation">
                Type APPLY to confirm
            </label>

            <input
                type="text"
                id="apply_confirmation"
                name="apply_confirmation"
                autocomplete="off"
                placeholder="APPLY"
                required
            >
        </div>

        <p class="muted">
            This will add the previewed supplier item, shipping,
            tax, travel, and discount shares to the matched orders.
        </p>

        <button
            type="submit"
            class="button"
        >
            Apply Supplier Costs
        </button>
    </form>
	<p>
<?php else: ?>
    <div class="supplier-readiness-message supplier-readiness-locked">
        <strong>Apply would be locked.</strong>

        <?php if ($ready_preview_lock_messages): ?>
            <ul>
                <?php foreach ($ready_preview_lock_messages as $lock_message): ?>
                    <li><?= supplier_page_e($lock_message) ?></li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>

        <p>
            No order costs have been changed.
        </p>
    </div>
<?php endif; ?>

    <?php if ($ready_preview_summary['missing_count'] > 0): ?>
        <div class="notice-error">
            One or more preview rows do not match an order yet. Fix those order numbers before applying costs later.
        </div>
    <?php endif; ?>
<?php endif; ?>

    <?php if (!$ready_preview_rows): ?>
    <p class="muted">
        No Ready to Apply supplier drafts found yet.
    </p>
<?php else: ?>

    <?php if ($ready_preview_order_totals): ?>
        <h3>Grouped by Order</h3>

        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>Order</th>
                        <th>Customer</th>
                        <th>Receipts</th>
                        <th>Suppliers</th>
                        <th>Items</th>
                        <th>Shipping</th>
                        <th>Tax</th>
                        <th>Travel</th>
                        <th>Discount/Credit</th>
                        <th>Estimated Total</th>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach ($ready_preview_order_totals as $order_total): ?>
                        <tr>
                            <td>
                                <strong><?= supplier_page_e($order_total['order_number']) ?></strong>
                            </td>

                            <td>
                                <?= supplier_page_e($order_total['customer_name']) ?>
                            </td>

                            <td>
                                <?= number_format((int) $order_total['receipt_count']) ?>
                            </td>

                            <td>
                                <?= supplier_page_e(implode(', ', $order_total['suppliers'])) ?>
                            </td>

                            <td>
                                <?= supplier_page_money($order_total['item_total']) ?>
                            </td>

                            <td>
                                <?= supplier_page_money($order_total['shipping_share']) ?>
                            </td>

                            <td>
                                <?= supplier_page_money($order_total['tax_share']) ?>
                            </td>

                            <td>
                                <?= supplier_page_money($order_total['travel_share']) ?>
                            </td>

                            <td>
                                -<?= supplier_page_money($order_total['discount_share']) ?>
                            </td>

                            <td>
                                <strong><?= supplier_page_money($order_total['total_internal_cost']) ?></strong>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
<p>
        <h3>Receipt Details</h3>
    <?php endif; ?>
    <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>Order</th>
						<th>Match</th>
						<th>Applied?</th>
                        <th>Supplier</th>
                        <th>Receipt #</th>
                        <th>Items</th>
                        <th>Item Total</th>
                        <th>Shipping Share</th>
                        <th>Tax Share</th>
                        <th>Travel Share</th>
                        <th>Discount/Credit Share</th>
                        <th>Estimated Internal Cost</th>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach ($ready_preview_rows as $preview): ?>
                        <tr>
                            <td>
    <strong><?= supplier_page_e($preview['order_number']) ?></strong>
</td>

<td>
    <?php if (!empty($preview['order_found'])): ?>
        <span class="status-pill supplier-match-found">
            Matched
        </span>

        <?php if (!empty($preview['customer_name'])): ?>
            <div class="muted supplier-match-detail">
                <?= supplier_page_e($preview['customer_name']) ?>
            </div>
        <?php endif; ?>
    <?php else: ?>
        <span class="status-pill supplier-match-missing">
            Not Found
        </span>
    <?php endif; ?>
</td>

<td>
    <?php if (!empty($preview['already_applied'])): ?>
        <span class="status-pill supplier-applied-pill">
            Applied
        </span>

        <?php if (!empty($preview['applied_at'])): ?>
            <div class="muted supplier-match-detail">
                <?= supplier_page_e($preview['applied_at']) ?>
            </div>
        <?php endif; ?>
    <?php else: ?>
        <span class="status-pill supplier-not-applied-pill">
            Not Applied
        </span>
    <?php endif; ?>
</td>

<td>
    <?= supplier_page_e($preview['supplier_name']) ?>
</td>

                            <td>
                                <?= supplier_page_e($preview['receipt_number']) ?>
                            </td>

                            <td>
                                <?= number_format((int) $preview['item_count']) ?>
                            </td>

                            <td>
                                <?= supplier_page_money($preview['item_total']) ?>
                            </td>

                            <td>
                                <?= supplier_page_money($preview['shipping_share']) ?>
                            </td>

                            <td>
                                <?= supplier_page_money($preview['tax_share']) ?>
                            </td>

                            <td>
                                <?= supplier_page_money($preview['travel_share']) ?>
                            </td>

                            <td>
                                -<?= supplier_page_money($preview['discount_share']) ?>
                            </td>

                            <td>
                                <strong><?= supplier_page_money($preview['total_internal_cost']) ?></strong>
                            </td>
                        </tr>

                        <?php if (!empty($preview['items'])): ?>
                            <tr>
                                <td></td>
                                <td colspan="11">
                                    <div class="supplier-mini-items">
                                        <strong>Preview items for <?= supplier_page_e($preview['order_number']) ?>:</strong>

                                        <ul>
                                            <?php foreach ($preview['items'] as $item): ?>
                                                <li>
                                                    <?= supplier_page_e($item['description']) ?>
                                                    —
                                                    Qty <?= supplier_page_e($item['quantity']) ?>
                                                    —
                                                    <?= supplier_page_money($item['item_cost']) ?>

                                                    <?php if (!empty($item['accuracy'])): ?>
                                                        —
                                                        <?= supplier_page_e($item['accuracy']) ?>
                                                    <?php endif; ?>

                                                    <?php if (!empty($item['notes'])): ?>
                                                        —
                                                        <?= supplier_page_e($item['notes']) ?>
                                                    <?php endif; ?>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    </div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</section>

<section class="card" id="tracked-non-order">
    <h2>Tracked Non-Order Items</h2>

    <p class="muted">
        These are supplier receipt items that are tracked but not tied directly to a Sparrow order yet.
        Nothing here applies to order costs.
    </p>

    <?php if (!$tracked_non_order_items): ?>
        <p class="muted">No tracked non-order supplier items yet.</p>
    <?php else: ?>
        <div class="supplier-preview-summary">
            <div>
                <span>Tracked Rows</span>
                <strong><?= number_format((int) $tracked_non_order_summary['count']) ?></strong>
            </div>

            <div>
                <span>Tracked Total</span>
                <strong><?= supplier_page_money($tracked_non_order_summary['total']) ?></strong>
            </div>

            <div>
                <span>Types</span>
                <strong><?= number_format(count($tracked_non_order_summary['by_type'])) ?></strong>
            </div>

            <div>
                <span>Note</span>
                <strong>Not Applied</strong>
            </div>
        </div>

        <h3>By Type</h3>

        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>Type</th>
                        <th>Rows</th>
                        <th>Total</th>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach ($tracked_non_order_summary['by_type'] as $type_row): ?>
                        <tr>
                            <td>
                                <strong><?= supplier_page_e($type_row['type']) ?></strong>
                            </td>

                            <td>
                                <?= number_format((int) $type_row['count']) ?>
                            </td>

                            <td>
                                <?= supplier_page_money($type_row['total']) ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
<p>
        <h3>Details</h3>

        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>Type</th>
                        <th>Supplier</th>
                        <th>Receipt #</th>
                        <th>Date</th>
                        <th>Description</th>
                        <th>Qty</th>
                        <th>Unit Cost</th>
                        <th>Item Cost</th>
                        <th>Status</th>
                        <th>Notes</th>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach ($tracked_non_order_items as $tracked_item): ?>
                        <tr>
                            <td>
                                <strong><?= supplier_page_e($tracked_item['item_type']) ?></strong>
                            </td>

                            <td>
                                <?= supplier_page_e($tracked_item['supplier_name']) ?>
                            </td>

                            <td>
                                <?= supplier_page_e($tracked_item['receipt_number']) ?>
                            </td>

                            <td>
                                <?= supplier_page_e($tracked_item['order_date']) ?>
                            </td>

                            <td>
                                <?= supplier_page_e($tracked_item['description']) ?>
                            </td>

                            <td>
                                <?= supplier_page_e($tracked_item['quantity']) ?>
                            </td>

                            <td>
                                <?= supplier_page_money($tracked_item['unit_cost']) ?>
                            </td>

                            <td>
                                <?= supplier_page_money($tracked_item['item_cost']) ?>
                            </td>

                            <td>
                                <span class="status-pill">
                                    <?= supplier_page_e(sparrow_supplier_status_label((string) $tracked_item['receipt_status'])) ?>
                                </span>
                            </td>

                            <td>
                                <?= supplier_page_e($tracked_item['notes']) ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</section>

<script>
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.supplier-items-toggle').forEach(function (button) {
        button.addEventListener('click', function () {
            const receiptId = button.dataset.receiptId;
            const detailRow = document.getElementById(
                'supplier-items-' + receiptId
            );

            if (!detailRow) {
                return;
            }

            const isOpen = detailRow.style.display !== 'none';

            detailRow.style.display = isOpen ? 'none' : 'table-row';
            button.textContent = isOpen ? 'View Items' : 'Hide Items';
            button.setAttribute(
                'aria-expanded',
                isOpen ? 'false' : 'true'
            );
        });
    });
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const tableBody = document.querySelector('#supplier-items-table tbody');
    const addButton = document.getElementById('supplier-add-row');

    if (!tableBody || !addButton) {
        return;
    }

    function reindexPossibleOrderUseCheckboxes() {
        const checkboxes = tableBody.querySelectorAll('input[type="checkbox"][name^="possible_order_use"]');

        checkboxes.forEach(function (checkbox, index) {
            checkbox.name = 'possible_order_use[' + index + ']';
        });
    }

    function bindRemoveButtons() {
        const removeButtons = tableBody.querySelectorAll('.supplier-remove-row');

        removeButtons.forEach(function (button) {
            button.onclick = function () {
                const rows = tableBody.querySelectorAll('tr');

                if (rows.length <= 1) {
                    const row = button.closest('tr');

                    if (!row) {
                        return;
                    }

                    row.querySelectorAll('input').forEach(function (input) {
                        if (input.type === 'checkbox') {
                            input.checked = false;
                        } else if (input.name === 'quantity[]') {
                            input.value = '1';
                        } else if (input.name === 'unit_cost[]' || input.name === 'item_cost[]') {
                            input.value = '0.00';
                        } else {
                            input.value = '';
                        }
                    });

                    row.querySelectorAll('select').forEach(function (select) {
                        select.selectedIndex = 0;
                    });

                    return;
                }

                button.closest('tr').remove();
                reindexPossibleOrderUseCheckboxes();
            };
        });
    }

    addButton.addEventListener('click', function () {
        const firstRow = tableBody.querySelector('tr');

        if (!firstRow) {
            return;
        }

        const newRow = firstRow.cloneNode(true);

        newRow.querySelectorAll('input').forEach(function (input) {
            if (input.type === 'checkbox') {
                input.checked = false;
            } else if (input.name === 'quantity[]') {
                input.value = '1';
            } else if (input.name === 'unit_cost[]' || input.name === 'item_cost[]') {
                input.value = '0.00';
            } else {
                input.value = '';
            }
        });

        newRow.querySelectorAll('select').forEach(function (select) {
            select.selectedIndex = 0;
        });

        tableBody.appendChild(newRow);
        reindexPossibleOrderUseCheckboxes();
        bindRemoveButtons();
    });

    bindRemoveButtons();
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const sheetWidthInput = document.getElementById('gang_sheet_width');
    const sheetHeightInput = document.getElementById('gang_sheet_height');
    const sheetCostInput = document.getElementById('gang_sheet_cost');
    const modeInput = document.getElementById('gang_sheet_mode');

    const fullAreaOutput = document.getElementById('gang_full_area');
    const usedAreaOutput = document.getElementById('gang_used_area');
    const rateOutput = document.getElementById('gang_rate');
    const calculatedTotalOutput = document.getElementById('gang_calculated_total');

    const gangTableBody = document.querySelector('#gang-sheet-table tbody');
    const gangAddButton = document.getElementById('gang-add-row');
    const sendToItemsButton = document.getElementById('gang-send-to-items');

    const supplierItemsBody = document.querySelector('#supplier-items-table tbody');

    if (
        !sheetWidthInput ||
        !sheetHeightInput ||
        !sheetCostInput ||
        !modeInput ||
        !gangTableBody ||
        !gangAddButton
    ) {
        return;
    }

    function money(value) {
        return '$' + Number(value || 0).toFixed(2);
    }

    function numberValue(input) {
        return parseFloat(input.value || '0') || 0;
    }

    function cleanMoneyText(value) {
        return String(value || '').replace('$', '').trim();
    }

    function normalizeOrderForDisplay(value) {
        value = String(value || '').trim().toUpperCase();

        if (value === '') {
            return '';
        }

        value = value.replace(/^ORDER\s*#?\s*/i, '');

        const sscMatch = value.match(/^(SSC|SCC)-?(\d+)$/);

        if (sscMatch) {
            return 'SSC-' + sscMatch[2].padStart(3, '0');
        }

        if (/^\d+$/.test(value)) {
            return 'SSC-' + value.padStart(3, '0');
        }

        return value;
    }

    function calculateGangSheet() {
        const sheetWidth = numberValue(sheetWidthInput);
        const sheetHeight = numberValue(sheetHeightInput);
        const sheetCost = numberValue(sheetCostInput);
        const splitMode = modeInput.value;

        const fullArea = sheetWidth * sheetHeight;
        let usedArea = 0;

        const rows = gangTableBody.querySelectorAll('tr');

        rows.forEach(function (row) {
            const widthInput = row.querySelector('.gang-width');
            const heightInput = row.querySelector('.gang-height');
            const qtyInput = row.querySelector('.gang-qty');
            const areaOutput = row.querySelector('.gang-row-area');

            const width = numberValue(widthInput);
            const height = numberValue(heightInput);
            const qty = numberValue(qtyInput) || 1;

            const rowArea = width * height * qty;

            usedArea += rowArea;
            areaOutput.textContent = rowArea.toFixed(2);
        });

        let rateBase = splitMode === 'full' ? fullArea : usedArea;

        if (rateBase <= 0) {
            rateBase = 0;
        }

        const rate = rateBase > 0 ? sheetCost / rateBase : 0;
        let calculatedTotal = 0;

        rows.forEach(function (row) {
            const area = parseFloat(row.querySelector('.gang-row-area').textContent || '0') || 0;
            const costOutput = row.querySelector('.gang-row-cost');
            const rowCost = area * rate;

            calculatedTotal += rowCost;
            costOutput.textContent = money(rowCost);
        });

        fullAreaOutput.textContent = fullArea.toFixed(2) + ' sq in';
        usedAreaOutput.textContent = usedArea.toFixed(2) + ' sq in';
        rateOutput.textContent = money(rate) + ' / sq in';
        calculatedTotalOutput.textContent = money(calculatedTotal);

        return {
            rate: rate,
            fullArea: fullArea,
            usedArea: usedArea,
            calculatedTotal: calculatedTotal
        };
    }

    function bindGangSheetInputs() {
        const inputs = document.querySelectorAll(
            '#gang_sheet_width, #gang_sheet_height, #gang_sheet_cost, #gang_sheet_mode, ' +
            '#gang-sheet-table input, #gang-sheet-table select'
        );

        inputs.forEach(function (input) {
            input.addEventListener('input', calculateGangSheet);
            input.addEventListener('change', calculateGangSheet);
        });
    }

    function bindGangRemoveButtons() {
        const removeButtons = gangTableBody.querySelectorAll('.gang-remove-row');

        removeButtons.forEach(function (button) {
            button.onclick = function () {
                const rows = gangTableBody.querySelectorAll('tr');

                if (rows.length <= 1) {
                    const row = button.closest('tr');

                    row.querySelectorAll('input').forEach(function (input) {
                        if (input.classList.contains('gang-qty')) {
                            input.value = '1';
                        } else {
                            input.value = '';
                        }
                    });

                    row.querySelectorAll('select').forEach(function (select) {
                        select.selectedIndex = 0;
                    });

                    calculateGangSheet();
                    return;
                }

                button.closest('tr').remove();
                calculateGangSheet();
            };
        });
    }

    function resetSupplierItemRow(row) {
        row.querySelectorAll('input').forEach(function (input) {
            if (input.type === 'checkbox') {
                input.checked = false;
            } else if (input.name === 'quantity[]') {
                input.value = '1';
            } else if (input.name === 'unit_cost[]' || input.name === 'item_cost[]') {
                input.value = '0.00';
            } else {
                input.value = '';
            }
        });

        row.querySelectorAll('select').forEach(function (select) {
            select.selectedIndex = 0;
        });
    }

    function makeSureSupplierItemRowExists(index) {
        if (!supplierItemsBody) {
            return null;
        }

        let rows = supplierItemsBody.querySelectorAll('tr');

        while (rows.length <= index) {
            const firstRow = supplierItemsBody.querySelector('tr');

            if (!firstRow) {
                return null;
            }

            const newRow = firstRow.cloneNode(true);
            resetSupplierItemRow(newRow);
            supplierItemsBody.appendChild(newRow);
            rows = supplierItemsBody.querySelectorAll('tr');
        }

        return rows[index];
    }

    function setSelectValue(select, value) {
        if (!select) {
            return;
        }

        const options = Array.from(select.options);
        const match = options.find(function (option) {
            return option.value === value;
        });

        if (match) {
            select.value = value;
        }
    }

    function sendGangRowsToSupplierItems() {
        if (!supplierItemsBody) {
            alert('Supplier Items table was not found.');
            return;
        }

        const calc = calculateGangSheet();
        const gangRows = Array.from(gangTableBody.querySelectorAll('tr'));
        const usableRows = [];

        gangRows.forEach(function (row) {
            const type = row.querySelector('.gang-type') ? row.querySelector('.gang-type').value : 'Sparrow Order';
            const orderUse = row.querySelector('.gang-order') ? row.querySelector('.gang-order').value.trim() : '';
            const description = row.querySelector('.gang-description') ? row.querySelector('.gang-description').value.trim() : '';
            const area = parseFloat(row.querySelector('.gang-row-area') ? row.querySelector('.gang-row-area').textContent : '0') || 0;
            const cost = cleanMoneyText(row.querySelector('.gang-row-cost') ? row.querySelector('.gang-row-cost').textContent : '0');

            if (area <= 0) {
                return;
            }

            usableRows.push({
                type: type,
                orderUse: orderUse,
                description: description,
                area: area,
                rate: calc.rate,
                cost: parseFloat(cost || '0') || 0
            });
        });

        if (!usableRows.length) {
            alert('No calculator rows with square inches were found.');
            return;
        }

        usableRows.forEach(function (gangRow, index) {
            const supplierRow = makeSureSupplierItemRowExists(index);

            if (!supplierRow) {
                return;
            }

            const typeSelect = supplierRow.querySelector('select[name="item_type[]"]');
            const orderInput = supplierRow.querySelector('input[name="goes_with_order_number[]"]');
            const descriptionInput = supplierRow.querySelector('input[name="description[]"]');
            const qtyInput = supplierRow.querySelector('input[name="quantity[]"]');
            const unitCostInput = supplierRow.querySelector('input[name="unit_cost[]"]');
            const itemCostInput = supplierRow.querySelector('input[name="item_cost[]"]');
            const notesInput = supplierRow.querySelector('input[name="item_notes[]"]');

            setSelectValue(typeSelect, gangRow.type);

            if (orderInput) {
                orderInput.value = gangRow.type === 'Sparrow Order'
                    ? normalizeOrderForDisplay(gangRow.orderUse)
                    : gangRow.orderUse;
            }

            if (descriptionInput) {
                descriptionInput.value = 'Gang sheet portion' + (gangRow.description ? ' - ' + gangRow.description : '');
            }

            if (qtyInput) {
                qtyInput.value = gangRow.area.toFixed(2);
            }

            if (unitCostInput) {
                unitCostInput.value = gangRow.rate.toFixed(4);
            }

            if (itemCostInput) {
                itemCostInput.value = gangRow.cost.toFixed(2);
            }

            if (notesInput) {
                notesInput.value = 'Gang sheet calculator';
            }
        });

        alert('Calculator rows were sent to Supplier Items. Click Save/Update Supplier Split Draft to save them.');
    }

    gangAddButton.addEventListener('click', function () {
        const firstRow = gangTableBody.querySelector('tr');

        if (!firstRow) {
            return;
        }

        const newRow = firstRow.cloneNode(true);

        newRow.querySelectorAll('input').forEach(function (input) {
            if (input.classList.contains('gang-qty')) {
                input.value = '1';
            } else {
                input.value = '';
            }
        });

        newRow.querySelectorAll('select').forEach(function (select) {
            select.selectedIndex = 0;
        });

        newRow.querySelector('.gang-row-area').textContent = '0';
        newRow.querySelector('.gang-row-cost').textContent = '$0.00';

        gangTableBody.appendChild(newRow);

        bindGangSheetInputs();
        bindGangRemoveButtons();
        calculateGangSheet();
    });

    if (sendToItemsButton) {
        sendToItemsButton.addEventListener('click', sendGangRowsToSupplierItems);
    }

    bindGangSheetInputs();
    bindGangRemoveButtons();
    calculateGangSheet();
});
</script>

<?php sparrow_backyard_footer(); ?>
