<?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';

function sparrow_order_view_lines(string $value, array $fallback): array
{
    $values = array_values(array_filter(array_map(
        'trim',
        preg_split('/\r\n|\r|\n/', $value) ?: []
    )));

    return $values ?: $fallback;
}

function sparrow_order_view_dropdown_options(
    PDO $pdo,
    string $category,
    array $fallback,
    array $current_values = []
): array {
    $values = [];

    foreach (sparrow_get_setting_rows($pdo, $category) as $row) {
        $value = trim((string) ($row['value'] ?? ''));

        if ($value !== '' && !in_array($value, $values, true)) {
            $values[] = $value;
        }
    }

    if (!$values) {
        $values = $fallback;
    }

    foreach ($current_values as $current_value) {
        $current_value = trim((string) $current_value);

        if ($current_value !== '' && !in_array($current_value, $values, true)) {
            $values[] = $current_value;
        }
    }

    return $values;
}

function sparrow_order_price_normalize(string $value): string
{
    $value = strtolower(trim($value));
    $value = preg_replace('/[^a-z0-9]+/', ' ', $value);
    return trim(preg_replace('/\s+/', ' ', $value));
}

function sparrow_order_price_normalize_size(string $size): string
{
    $size = strtoupper(trim($size));
    $size = str_replace(['(', ')'], '', $size);
    $size = preg_replace('/\s+/', ' ', $size);

    $map = [
        'X-SMALL' => 'XS',
        'EXTRA SMALL' => 'XS',
        'EXTRA-SMALL' => 'XS',
        'XS' => 'XS',

        'SMALL' => 'S',
        'S' => 'S',

        'MEDIUM' => 'M',
        'M' => 'M',

        'LARGE' => 'L',
        'L' => 'L',

        'X-LARGE' => 'XL',
        'XLARGE' => 'XL',
        'EXTRA LARGE' => 'XL',
        'EXTRA-LARGE' => 'XL',
        'XL' => 'XL',

        '2X' => '2XL',
        '2XL' => '2XL',
        'XXL' => '2XL',
        '2X LARGE' => '2XL',
        '2X-LARGE' => '2XL',
        'XX-LARGE' => '2XL',

        '3X' => '3XL',
        '3XL' => '3XL',
        '3X LARGE' => '3XL',
        '3X-LARGE' => '3XL',

        '4X' => '4XL',
        '4XL' => '4XL',
        '4X LARGE' => '4XL',
        '4X-LARGE' => '4XL',

        '5X' => '5XL',
        '5XL' => '5XL',
        '5X LARGE' => '5XL',
        '5X-LARGE' => '5XL',
    ];

    return $map[$size] ?? $size;
}

function sparrow_order_size_order_value(string $size): int
{
    $size = sparrow_order_price_normalize_size($size);

    $order = [
        'XS' => 1,
        'S' => 2,
        'M' => 3,
        'L' => 4,
        'XL' => 5,
        '2XL' => 6,
        '3XL' => 7,
        '4XL' => 8,
        '5XL' => 9,
    ];

    return $order[$size] ?? 999;
}

function sparrow_order_size_matches_range(string $order_size, string $pricing_range): bool
{
    $order_size = sparrow_order_price_normalize_size($order_size);
    $pricing_range = strtoupper(trim($pricing_range));

    if ($order_size === '' || $pricing_range === '') {
        return true;
    }

    $pricing_range = str_replace(' ', '', $pricing_range);

    if (strpos($pricing_range, '-') !== false) {
        [$start, $end] = explode('-', $pricing_range, 2);

        $order_value = sparrow_order_size_order_value($order_size);
        $start_value = sparrow_order_size_order_value($start);
        $end_value = sparrow_order_size_order_value($end);

        return $order_value >= $start_value && $order_value <= $end_value;
    }

    return sparrow_order_price_normalize_size($pricing_range) === $order_size;
}

function sparrow_order_get_pricing_lookup_rows(): array
{
    try {
        $pdo = sparrow_db();

        $stmt = $pdo->query("
            SELECT id, item_type, size_range, color_style, retail_price
            FROM pricing_items
            WHERE retail_price IS NOT NULL
              AND retail_price != ''
            ORDER BY item_type ASC, color_style ASC, size_range ASC
        ");

        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    } catch (Throwable $e) {
        return [];
    }
}

function sparrow_order_find_retail_price_for_item(array $item, array $pricing_rows): ?float
{
    $item_type = sparrow_order_price_normalize((string) ($item['item_type'] ?? ''));
    $size = (string) ($item['shirt_size'] ?? '');
    $color = sparrow_order_price_normalize((string) ($item['shirt_color'] ?? ''));

    if ($item_type === '') {
        return null;
    }

    $best_match = null;
    $best_score = -1;

    foreach ($pricing_rows as $row) {
        $pricing_type = sparrow_order_price_normalize((string) ($row['item_type'] ?? ''));
        $pricing_color = sparrow_order_price_normalize((string) ($row['color_style'] ?? ''));
        $pricing_size = (string) ($row['size_range'] ?? '');

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

        $type_matches =
            $pricing_type === $item_type ||
            str_contains($pricing_type, $item_type) ||
            str_contains($item_type, $pricing_type);

        if (!$type_matches) {
            continue;
        }

        if (!sparrow_order_size_matches_range($size, $pricing_size)) {
            continue;
        }

        $score = 10;

        if ($pricing_type === $item_type) {
            $score += 20;
        }

        if ($color !== '' && $pricing_color !== '') {
            if ($color === $pricing_color) {
                $score += 20;
            } else {
                continue;
            }
        }

        if ($size !== '' && $pricing_size !== '') {
            $score += 5;
        }

        if ($score > $best_score) {
            $best_match = $row;
            $best_score = $score;
        }
    }

    if (!$best_match || $best_match['retail_price'] === null || $best_match['retail_price'] === '') {
        return null;
    }

    return (float) $best_match['retail_price'];
}

function sparrow_order_calculate_customer_total_from_items(array $items, array $settings = []): array
{
    $pricing_rows = sparrow_order_get_pricing_lookup_rows();

    $total = 0.0;
    $matched = 0;
    $unmatched = [];

    foreach ($items as $index => $item) {
    /*
     * Gift items stay on the order and keep their
     * internal costs, but the customer is not charged.
     */
    if (!empty($item['is_gift'])) {
        continue;
    }

    $quantity = max(1, (int) ($item['quantity'] ?? 1));
    $price = sparrow_order_find_retail_price_for_item(
        $item,
        $pricing_rows
    );

        if ($price === null) {
            $unmatched[] = $index + 1;
            continue;
        }

        $print_location = sparrow_order_price_normalize((string) ($item['print_location'] ?? ''));
        $specialty = sparrow_order_price_normalize((string) ($item['specialty'] ?? ''));

        if (in_array($print_location, ['front back', 'front and back'], true)) {
            $price += (float) ($settings['front_back_upcharge'] ?? 0);
        } elseif (in_array($print_location, ['chest back', 'chest and back', 'left chest back', 'left chest and back', 'front chest'], true)) {
            $price += (float) ($settings['chest_back_upcharge'] ?? 0);
        } elseif (str_contains($print_location, 'sleeve')) {
            $price += (float) ($settings['sleeve_upcharge'] ?? 0);
        }

        if ($specialty !== '' && $specialty !== 'none') {
            $price += (float) ($settings['specialty_upcharge'] ?? 0);
        }

        $matched++;
        $total += $quantity * $price;
    }

    return [
        'total' => $total,
        'matched' => $matched,
        'unmatched' => $unmatched,
    ];
}

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

$order_view_settings = sparrow_get_settings($pdo, [
    'status_list',
    'default_order_status',
    'front_back_upcharge',
    'chest_back_upcharge',
    'sleeve_upcharge',
    'specialty_upcharge',
]);

$status_options = sparrow_order_view_lines(
    (string) ($order_view_settings['status_list'] ?? ''),
    [
        'Order Received',
        'Order Approved',
        'Products Ordered',
        'Pressing',
        'Packaging',
        'Ready for Pickup',
        'Delivered',
    ]
);

$default_order_status = trim((string) ($order_view_settings['default_order_status'] ?? ''));

if ($default_order_status === '') {
    $default_order_status = $status_options[0];
}

$order_id = (int) ($_GET['id'] ?? 0);

if ($order_id <= 0) {
    sparrow_redirect('/backyard/orders.php');
}

$order = sparrow_get_order($order_id);

if (!$order) {
    sparrow_backyard_header('Order Not Found');
    ?>

    <section class="card">
        <h1>Order Not Found</h1>

        <p class="muted">
            That order could not be found.
        </p>

        <a class="button" href="<?php echo sparrow_escape(sparrow_url('/backyard/dashboard.php')); ?>">
            Back to Dashboard
        </a>
    </section>

    <?php
    sparrow_backyard_footer();
    exit;
}

$reference_images =
    sparrow_get_order_reference_images($order_id);

$approval_image_positions =
    sparrow_get_approval_image_positions();

$approval_images =
    sparrow_get_order_approval_images($order_id);

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
	
	if ($action === 'save_item_approval_image') {
    $order_item_id = (int) (
        $_POST['order_item_id'] ?? 0
    );

    $image_position = trim(
        (string) ($_POST['image_position'] ?? '')
    );

    $new_file_path = '';

    try {
        /*
         * Confirm that the submitted item belongs
         * to the order currently being viewed.
         */
        $item_check_stmt = $pdo->prepare("
            SELECT id
            FROM order_items
            WHERE id = :item_id
              AND order_id = :order_id
            LIMIT 1
        ");

        $item_check_stmt->execute([
            ':item_id' => $order_item_id,
            ':order_id' => $order_id,
        ]);

        if (!$item_check_stmt->fetchColumn()) {
            throw new RuntimeException(
                'The selected order item could not be verified.'
            );
        }

        if (
            !isset(
                $approval_image_positions[
                    $image_position
                ]
            )
        ) {
            throw new RuntimeException(
                'Please choose a valid image position.'
            );
        }

        $file = $_FILES['approval_image'] ?? null;

        if (
            !$file ||
            ($file['error'] ?? UPLOAD_ERR_NO_FILE)
                !== UPLOAD_ERR_OK
        ) {
            throw new RuntimeException(
                'Please choose the approval image again.'
            );
        }

        $image_info = @getimagesize(
            (string) $file['tmp_name']
        );

        $allowed_mime_types = [
            'image/jpeg' => 'jpg',
            'image/png' => 'png',
            'image/gif' => 'gif',
            'image/webp' => 'webp',
        ];

        $mime_type = (string) (
            $image_info['mime'] ?? ''
        );

        if (!isset($allowed_mime_types[$mime_type])) {
            throw new RuntimeException(
                'The file must be a JPG, PNG, GIF, or WEBP image.'
            );
        }

        $extension = $allowed_mime_types[$mime_type];

        $upload_dir =
            __DIR__ . '/../storage/approvals/';

        if (
            !is_dir($upload_dir) &&
            !mkdir($upload_dir, 0755, true)
        ) {
            throw new RuntimeException(
                'The approval upload folder could not be created.'
            );
        }

        $existing_images =
            sparrow_get_order_item_approval_images(
                $order_item_id
            );

        $old_image_path = (string) (
            $existing_images[$image_position]['image_path']
            ?? ''
        );

        $new_name =
            'approval-item-'
            . $order_item_id
            . '-'
            . $image_position
            . '-'
            . time()
            . '-'
            . bin2hex(random_bytes(4))
            . '.'
            . $extension;

        $destination = $upload_dir . $new_name;

        if (
            !move_uploaded_file(
                (string) $file['tmp_name'],
                $destination
            )
        ) {
            throw new RuntimeException(
                'The approval image could not be saved.'
            );
        }

        $new_file_path =
            '/storage/approvals/' . $new_name;

        sparrow_save_order_item_approval_image(
            $order_item_id,
            $image_position,
            $new_file_path
        );

        /*
         * Remove the older file after its database
         * record has been replaced successfully.
         */
        if ($old_image_path !== '') {
            $old_url_path = parse_url(
                $old_image_path,
                PHP_URL_PATH
            );

            $old_filename = basename(
                (string) $old_url_path
            );

            $old_file =
                $upload_dir . $old_filename;

            if (
                $old_filename !== '' &&
                is_file($old_file)
            ) {
                unlink($old_file);
            }
        }

        $notice =
            $approval_image_positions[$image_position]
            . ' approval image saved.';
    } catch (Throwable $e) {
        /*
         * If the database save failed, remove the
         * newly uploaded file.
         */
        if ($new_file_path !== '') {
            $new_filename = basename(
                (string) parse_url(
                    $new_file_path,
                    PHP_URL_PATH
                )
            );

            $new_file =
                __DIR__
                . '/../storage/approvals/'
                . $new_filename;

            if (
                $new_filename !== '' &&
                is_file($new_file)
            ) {
                unlink($new_file);
            }
        }

        $error =
            'Approval image could not be saved: '
            . $e->getMessage();
    }
}

if ($action === 'delete_item_approval_image') {
    $order_item_id = (int) (
        $_POST['order_item_id'] ?? 0
    );

    $image_position = trim(
        (string) ($_POST['image_position'] ?? '')
    );

    try {
        /*
         * Confirm that this item belongs to
         * the order currently being viewed.
         */
        $item_check_stmt = $pdo->prepare("
            SELECT id
            FROM order_items
            WHERE id = :item_id
              AND order_id = :order_id
            LIMIT 1
        ");

        $item_check_stmt->execute([
            ':item_id' => $order_item_id,
            ':order_id' => $order_id,
        ]);

        if (!$item_check_stmt->fetchColumn()) {
            throw new RuntimeException(
                'The selected order item could not be verified.'
            );
        }

        if (
            !isset(
                $approval_image_positions[
                    $image_position
                ]
            )
        ) {
            throw new RuntimeException(
                'The image position could not be verified.'
            );
        }

        $deleted_image_path =
            sparrow_delete_order_item_approval_image(
                $order_item_id,
                $image_position
            );

        /*
         * Remove the saved file after its
         * database record is deleted.
         */
        if ($deleted_image_path) {
            $deleted_filename = basename(
                (string) parse_url(
                    $deleted_image_path,
                    PHP_URL_PATH
                )
            );

            $deleted_file =
                __DIR__
                . '/../storage/approvals/'
                . $deleted_filename;

            if (
                $deleted_filename !== '' &&
                is_file($deleted_file)
            ) {
                unlink($deleted_file);
            }
        }

        $notice =
            $approval_image_positions[$image_position]
            . ' approval image removed.';
    } catch (Throwable $e) {
        $error =
            'Approval image could not be removed: '
            . $e->getMessage();
    }
}

if ($action === 'save_item_approval_notes') {
    $order_item_id = (int) (
        $_POST['order_item_id'] ?? 0
    );

    $approval_notes = trim(
        (string) ($_POST['approval_notes'] ?? '')
    );

    try {
        /*
         * Confirm that the item belongs to
         * the order currently being viewed.
         */
        $item_check_stmt = $pdo->prepare("
            SELECT id
            FROM order_items
            WHERE id = :item_id
              AND order_id = :order_id
            LIMIT 1
        ");

        $item_check_stmt->execute([
            ':item_id' => $order_item_id,
            ':order_id' => $order_id,
        ]);

        if (!$item_check_stmt->fetchColumn()) {
            throw new RuntimeException(
                'The selected order item could not be verified.'
            );
        }

        $notes_stmt = $pdo->prepare("
            UPDATE order_items
            SET approval_notes = :approval_notes
            WHERE id = :item_id
              AND order_id = :order_id
            LIMIT 1
        ");

        $notes_stmt->execute([
            ':approval_notes' =>
                $approval_notes !== ''
                    ? $approval_notes
                    : null,
            ':item_id' => $order_item_id,
            ':order_id' => $order_id,
        ]);

        $notice = 'Approval notes saved.';
    } catch (Throwable $e) {
        $error =
            'Approval notes could not be saved: '
            . $e->getMessage();
    }
}

    if ($action === 'save_payment') {
        $total_amount = (float) ($_POST['total_amount'] ?? 0);
        $paid_amount = (float) ($_POST['paid_amount'] ?? 0);
        $blessing_amount = (float) ($_POST['blessing_amount'] ?? 0);
		$payment_method = trim((string) ($_POST['payment_method'] ?? ''));
		$order_discount_amount = (float) ($_POST['order_discount_amount'] ?? 0);
		
		
        try {
            sparrow_update_order_payment($order_id, [
    'total_amount' => $total_amount,
    'paid_amount' => $paid_amount,
    'payment_method' => $payment_method,
    'blessing_amount' => $blessing_amount,
    'order_discount_amount' => $order_discount_amount,
	'order_shipping_amount' => (float) ($order['order_shipping_amount'] ?? 0),
	
]);

            $notice = 'Payment info saved.';

            $order = sparrow_get_order($order_id);
        } catch (Throwable $e) {
            $error = 'Payment info could not be saved: ' . $e->getMessage();
        }
    }
	
	if ($action === 'save_gift') {
    $is_gift = !empty($_POST['is_gift']);

    try {
        sparrow_update_order_gift($order_id, $is_gift);

        $notice = $is_gift
            ? 'Order marked as a gift.'
            : 'Gift status removed.';

        $order = sparrow_get_order($order_id);
    } catch (Throwable $e) {
        $error = 'Gift status could not be saved: ' . $e->getMessage();
    }
}

if ($action === 'save_items') {
    $itemsData = [];

    foreach (($_POST['item_type'] ?? []) as $i => $type) {
        $itemsData[] = [
    'id' => (int) ($_POST['item_id'][$i] ?? 0),
    'item_type' => trim((string) $type),
    'quantity' => max(1, (int) ($_POST['quantity'][$i] ?? 1)),
    'shirt_size' => trim((string) ($_POST['shirt_size'][$i] ?? '')),
    'shirt_color' => trim((string) ($_POST['shirt_color'][$i] ?? '')),

    'customer_supplied' => !empty(
        $_POST['customer_supplied'][$i]
    ) ? 1 : 0,
	'is_gift' => !empty(
		$_POST['item_gift'][$i]
	) ? 1 : 0,
    'specialty' => trim((string) ($_POST['specialty'][$i] ?? '')),
    'print_location' => trim((string) ($_POST['print_location'][$i] ?? '')),
    'item_notes' => trim((string) ($_POST['item_notes'][$i] ?? '')),
];
    }

    try {
        sparrow_update_order($order_id, [
            'items' => $itemsData,
            'customer_name' => $order['customer_name'],
            'customer_email' => $order['customer_email'],
            'customer_phone' => $order['customer_phone'],
            'status' => $order['status'],
            'notes' => $order['notes'],
        ]);
		
		$has_customer_supplied = false;
$billable_item_count = 0;

foreach ($itemsData as $itemData) {
    /*
     * Gift items are not part of the customer charge.
     */
    if (!empty($itemData['is_gift'])) {
        continue;
    }

    $billable_item_count++;

    if (!empty($itemData['customer_supplied'])) {
        $has_customer_supplied = true;
    }
}

        $pricing_total = sparrow_order_calculate_customer_total_from_items(
            $itemsData,
            $order_view_settings
        );

        if (
    !$has_customer_supplied &&
    !empty($itemsData) &&
    empty($pricing_total['unmatched']) &&
    $pricing_total['matched'] === $billable_item_count
) {
            sparrow_update_order_payment($order_id, [
                'total_amount' => $pricing_total['total'],
                'paid_amount' => (float) ($order['paid_amount'] ?? 0),
                'payment_method' => $order['payment_method'] ?? '',
                'blessing_amount' => (float) ($order['blessing_amount'] ?? 0),
                'order_discount_amount' => (float) ($order['order_discount_amount'] ?? 0),
				'order_shipping_amount' => (float) ($order['order_shipping_amount'] ?? 0),
				
            ]);

            $notice = 'Items saved. Payment total updated to $' . number_format($pricing_total['total'], 2) . '.';
        } elseif ($has_customer_supplied) {
    $notice =
        'Items saved. Payment total was left unchanged because '
        . 'this order contains a customer-supplied garment.';
} else {
    $notice =
        'Items saved, but payment total was not updated because '
        . 'one or more item rows did not match the pricing table. '
        . 'Check item type, size, and color.';
}

        $order = sparrow_get_order($order_id);
        $items = sparrow_get_order_items($order_id);
    } catch (Throwable $e) {
        $error = "Could not save items: " . $e->getMessage();
    }
}
	
	if ($action === 'save_order_number') {
    try {
		

$date_check = DateTime::createFromFormat(
    'Y-m-d',
    $order_date
);

if (
    !$date_check ||
    $date_check->format('Y-m-d') !== $order_date
) {
    throw new RuntimeException(
        'Please enter a valid order date.'
    );
}

$order_date_stmt = $pdo->prepare("
    UPDATE orders
    SET order_date = :order_date
    WHERE id = :order_id
    LIMIT 1
");

$order_date_stmt->execute([
    ':order_date' => $order_date,
    ':order_id' => $order_id,
]);

        sparrow_update_order_number($order_id, $_POST['order_number'] ?? '');

        header('Location: ' . sparrow_url('/backyard/order-view.php?id=' . (int) $order_id . '&notice=order_number_saved'));
        exit;
    } catch (Throwable $e) {
        $notice = '';
        $error = $e->getMessage();
    }
}
	
	if ($action === 'save_customer') {
    $customer_name = trim($_POST['customer_name'] ?? '');
    $customer_email = trim($_POST['customer_email'] ?? '');
    $customer_phone = trim($_POST['customer_phone'] ?? '');
    $status = trim($_POST['status'] ?? $default_order_status);
    $notes = trim($_POST['notes'] ?? '');
	
	$order_date = trim(
    (string) ($_POST['order_date'] ?? '')
);

if ($order_date === '') {
    $order_date = trim(
        (string) ($order['order_date'] ?? '')
    );
}

    if ($customer_name === '') {
        $error = 'Customer name is required.';
    } else {
        try {
            sparrow_update_order_number($order_id, $_POST['order_number'] ?? '');

sparrow_update_order_customer($order_id, [
    'customer_name' => $customer_name,
    'customer_email' => $customer_email,
    'customer_phone' => $customer_phone,
	'order_date' => $order_date,
    'status' => $status,
    'notes' => $notes,
]);

$notice =
    'Customer, status, order number, and order date saved.';

$order = sparrow_get_order($order_id);
        } catch (Throwable $e) {
            $error = 'Customer info could not be saved: ' . $e->getMessage();
        }
    }
	}

if ($action === 'save_delivery') {
    $delivery_method = trim($_POST['delivery_method'] ?? 'Pickup');

    $order_shipping_amount = strcasecmp($delivery_method, 'Shipping') === 0
        ? max(0, (float) ($_POST['order_shipping_amount'] ?? 0))
        : 0.00;

    $delivery_notes = trim($_POST['delivery_notes'] ?? '');

    try {
        sparrow_update_order_delivery($order_id, [
            'delivery_method' => $delivery_method,
			'order_shipping_amount' => $order_shipping_amount,
            'delivery_notes' => $delivery_notes,
        ]);

        $notice = 'Delivery info saved.';

        $order = sparrow_get_order($order_id);
    } catch (Throwable $e) {
        $error = 'Delivery info could not be saved: ' . $e->getMessage();
    }
}

if ($action === 'save_internal_costs') {
    $shipping_cost = (float) ($_POST['shipping_cost'] ?? 0);
    $discount_cost = (float) ($_POST['discount_cost'] ?? 0);
    $tax_cost = (float) ($_POST['tax_cost'] ?? 0);
    $other_cost = (float) ($_POST['other_cost'] ?? 0);
    $internal_cost_notes = trim($_POST['internal_cost_notes'] ?? '');

    try {
        sparrow_update_order_internal_costs($order_id, [
            'shipping_cost' => $shipping_cost,
            'discount_cost' => $discount_cost,
            'tax_cost' => $tax_cost,
            'other_cost' => $other_cost,
            'internal_cost_notes' => $internal_cost_notes,
        ]);

        $notice = 'Internal costs saved.';

        $order = sparrow_get_order($order_id);
    } catch (Throwable $e) {
        $error = 'Internal costs could not be saved.';
    }
}

if ($action === 'save_admin_notes') {
    $admin_notes = trim($_POST['admin_notes'] ?? '');

    try {
        sparrow_update_order_admin_notes($order_id, $admin_notes);

        $notice = 'Admin notes saved.';

        $order = sparrow_get_order($order_id);
    } catch (Throwable $e) {
        $error = 'Admin notes could not be saved.';
    }
}

if ($action === 'save_order_notes') {
    $notes = trim((string) ($_POST['order_notes'] ?? ''));

    try {
        $pdo = sparrow_db();

        $stmt = $pdo->prepare("
            UPDATE orders
            SET notes = :notes
            WHERE id = :id
            LIMIT 1
        ");

        $stmt->execute([
            ':notes' => $notes !== '' ? $notes : null,
            ':id' => $order_id,
        ]);

        $notice = 'Order notes saved.';
        $order = sparrow_get_order($order_id);
    } catch (Throwable $e) {
        $error = 'Order notes could not be saved: ' . $e->getMessage();
    }
}

if ($action === 'save_approval') {
    $approval_notes = trim($_POST['approval_notes'] ?? '');

    /*
     * order-view.php lives in:
     * /backyard/order-view.php
     *
     * This points to:
     * /storage/approvals/
     */
    $upload_dir = __DIR__ . '/../storage/approvals/';

    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }

    $image_path = $order['approval_image'] ?? null;
	
	$new_approval_images_saved = 0;

foreach (
    $approval_image_positions as $image_position => $position_label
) {
    $input_name = 'approval_image_' . $image_position;

    if (empty($_FILES[$input_name]['name'])) {
        continue;
    }

    $file = $_FILES[$input_name];

    if (
        ($file['error'] ?? UPLOAD_ERR_NO_FILE)
        !== UPLOAD_ERR_OK
    ) {
        $error = $position_label
            . ' image upload failed. Please choose it again.';
        break;
    }

    $ext = strtolower(
        pathinfo($file['name'], PATHINFO_EXTENSION)
    );

    $allowed_exts = [
        'jpg',
        'jpeg',
        'png',
        'gif',
        'webp',
    ];

    if (!in_array($ext, $allowed_exts, true)) {
        $error = $position_label
            . ' must be a JPG, PNG, GIF, or WEBP image.';
        break;
    }

    $new_name =
        'approval-order-'
        . $order_id
        . '-'
        . $image_position
        . '-'
        . time()
        . '.'
        . $ext;

    $destination = $upload_dir . $new_name;

    if (
        !move_uploaded_file(
            $file['tmp_name'],
            $destination
        )
    ) {
        $error = $position_label
            . ' image could not be saved.';
        break;
    }

    $new_image_path =
        '/storage/approvals/' . $new_name;

    try {
        sparrow_save_order_approval_image(
            $order_id,
            $image_position,
            $new_image_path
        );

        $new_approval_images_saved++;
    } catch (Throwable $e) {
        if (is_file($destination)) {
            unlink($destination);
        }

        $error = 'Could not save the '
            . $position_label
            . ' image: '
            . $e->getMessage();

        break;
    }
}

    if (!empty($_FILES['approval_image']['name'])) {
        $file = $_FILES['approval_image'];

        if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
            $error = 'Upload failed. Please choose the image again.';
        } else {
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $allowed_exts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

            if (!in_array($ext, $allowed_exts, true)) {
                $error = 'Invalid file type. Please upload JPG, PNG, GIF, or WEBP.';
            } else {
                $new_name = 'approval-order-' . $order_id . '-' . time() . '.' . $ext;
                $destination = $upload_dir . $new_name;

                if (move_uploaded_file($file['tmp_name'], $destination)) {
                    /*
                     * This should become something like:
                     * /storage/approvals/approval-order-1-1234567890.jpg
                     */
                    $image_path = '/storage/approvals/' . $new_name;
                } else {
                    $error = 'Upload failed. The image could not be saved.';
                }
            }
        }
    }

    if ($error === '') {
        try {
            sparrow_update_order_approval(
                $order_id,
                $image_path,
                'waiting',
                $approval_notes
            );

            $notice = $new_approval_images_saved > 0
    ? 'Approval images saved.'
    : 'Approval saved.';

$order = sparrow_get_order($order_id);

$approval_images =
    sparrow_get_order_approval_images($order_id);
        } catch (Throwable $e) {
            $error = 'Could not save approval: ' . $e->getMessage();
        }
    }
}

if ($action === 'delete_approval_image') {
    try {
        $current_image = $order['approval_image'] ?? '';

        if ($current_image !== '') {
            $filename = basename(parse_url($current_image, PHP_URL_PATH));

            $upload_dir = __DIR__ . '/../storage/approvals/';
            $file_path = $upload_dir . $filename;

            if ($filename !== '' && is_file($file_path)) {
                unlink($file_path);
            }
        }

        sparrow_update_order_approval(
            $order_id,
            null,
            'waiting',
            $order['approval_notes'] ?? ''
        );

        $notice = 'Approval image deleted.';
        $order = sparrow_get_order($order_id);
    } catch (Throwable $e) {
        $error = 'Approval image could not be deleted: ' . $e->getMessage();
    }
}

if ($action === 'set_approval_status') {
    $new_status = trim($_POST['approval_status'] ?? 'waiting');
    $allowed = ['waiting','approved','changes_requested'];

    if (!in_array($new_status, $allowed, true)) {
        $error = 'Invalid approval status.';
    } else {
        try {
            sparrow_update_order_approval(
                $order_id,
                $order['approval_image'] ?? null,
                $new_status,
                $order['approval_notes'] ?? ''
            );

            $notice = 'Approval status updated.';
            $order = sparrow_get_order($order_id);
        } catch (Throwable $e) {
            $error = 'Could not update approval status: ' . $e->getMessage();
        }
    }
}
}

$items = sparrow_get_order_items($order_id);

if (!in_array((string) ($order['status'] ?? ''), $status_options, true)) {
    $status_options[] = (string) $order['status'];
}

$item_type_options = sparrow_order_view_dropdown_options(
    $pdo,
    'item_type',
    ['Shirt', 'V-Neck Shirt', 'Koozie', 'Bookmark', 'Hat', 'Other'],
    array_column($items, 'item_type')
);

$specialty_options = sparrow_order_view_dropdown_options(
    $pdo,
    'specialty',
    ['None', 'Glitter', 'Glow', 'Gold Foil', 'Iridescent', 'Thermochromic', 'Pearl'],
    array_column($items, 'specialty')
);

$print_location_options = sparrow_order_view_dropdown_options(
    $pdo,
    'print_location',
    ['Full Front', 'Left Chest', 'Full Back', 'Front & Back', 'Chest & Back', 'Sleeve', 'Other'],
    array_column($items, 'print_location')
);

$delivery_method_options = sparrow_order_view_dropdown_options(
    $pdo,
    'delivery_method',
    ['Pickup', 'Shipping', 'Local Delivery', 'Church Delivery'],
    [(string) ($order['delivery_method'] ?? '')]
);

sparrow_backyard_header($order['order_number']);

?>

<style>
.customer-approval-response {
    margin: 14px 0 18px;
    padding: 14px 16px;
    border: 1px solid #e8c3d3;
    border-left: 5px solid #b85d87;
    border-radius: 14px;
    background: #fff7fb;
}

.customer-approval-response h3 {
    margin: 0 0 8px;
    color: #854766;
}

.customer-approval-response p {
    margin: 6px 0 0;
}

.customer-approval-response-date {
    color: #765f6c;
    font-size: 13px;
}

.customer-supplied-edit {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    margin: 0;
    white-space: nowrap;
}

.customer-supplied-edit input[type="checkbox"] {
    margin: 0;
}
</style>

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

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

<div class="order-work-layout">
    <div class="order-work-main">
	
<section class="card">
    <div class="page-heading-row">

        <div class="heading-actions">			
<a class="button button-secondary" href="<?= sparrow_escape(sparrow_url('/backyard/invoice.php?id=' . $order_id)) ?>">
    Print Invoice
</a>

<a class="button button-secondary" href="<?= sparrow_url('/backyard/packing-slip.php?id=' . $order_id) ?>">
    Print Packing Slip
</a>

<a class="button button-secondary" href="<?= sparrow_url('/backyard/work-log.php?id=' . $order_id) ?>">
    Print Work Log
</a>

            <a class="button button-secondary" href="<?php echo sparrow_escape(sparrow_url('/backyard/dashboard.php')); ?>">
                Back to Dashboard
            </a>
        </div>
    </div>
</section>

<section class="card">
    <div class="page-heading-row">
        <div>
            <h2>Customer & Order Info</h2>
        </div>

        <div class="heading-actions">
            <button type="button" class="button button-secondary" id="toggle-customer-edit">
                Edit Customer / Status
            </button>
        </div>
    </div>

    <div class="detail-grid">
        <div>
            <div class="detail-label">Customer</div>
            <div class="detail-value"><?php echo sparrow_escape($order['customer_name']); ?></div>
        </div>

        <div>
            <div class="detail-label">Status</div>
            <div class="detail-value">
    <span class="status-pill">
        <?php echo sparrow_escape($order['status']); ?>
    </span>

    <?php if (!empty($order['is_gift'])): ?>
        <span class="status-pill gift-order-pill">
            Gift
        </span>
    <?php endif; ?>
</div>
        </div>

        <div>
            <div class="detail-label">Phone</div>
            <div class="detail-value"><?php echo sparrow_escape(sparrow_format_phone_number($order['customer_phone'] ?? '')); ?></div>
        </div>

        <div>
            <div class="detail-label">Email</div>
            <div class="detail-value"><?php echo sparrow_escape($order['customer_email']); ?></div>
        </div>

        <div>
            <div class="detail-label">Order Date</div>
            <div class="detail-value"><?php echo sparrow_escape($order['order_date']); ?></div>
        </div>

        <div>
            <div class="detail-label">Total Quantity</div>
            <div class="detail-value"><?php echo (int) $order['quantity']; ?></div>
        </div>

        <?php if (!empty($order['original_forminator_entry_id'])): ?>
            <div>
                <div class="detail-label">Original Forminator Entry</div>
                <div class="detail-value">
                    <?php echo (int) $order['original_forminator_entry_id']; ?>
                </div>
            </div>
        <?php endif; ?>
    </div>

<div class="inline-edit-box" id="customer-edit-box" style="display: none;">
    <h3>Edit Customer Info</h3>

    <form method="post">
        <input type="hidden" name="action" value="save_customer">

        <div class="form-grid">
		<div>
                <label for="order_number">Order Number</label>
                <input
                    type="text"
                    id="order_number"
                    name="order_number"
                    value="<?php echo sparrow_escape($order['order_number']); ?>"
                    required
                >
            </div>
			
			<div>
    <label for="order_date">Order Date</label>
    <input
        type="date"
        id="order_date"
        name="order_date"
        value="<?php echo sparrow_escape(
            $order['order_date'] ?? ''
        ); ?>"
    >
</div>
			
            <div>
                <label for="customer_name">Customer Name</label>
                <input
                    type="text"
                    id="customer_name"
                    name="customer_name"
                    value="<?php echo sparrow_escape($order['customer_name']); ?>"
                    required
                >
            </div>

            <div>
                <label for="status">Status</label>
                <select id="status" name="status">
                    <?php foreach ($status_options as $status_option): ?>
                        <option
                            value="<?php echo sparrow_escape($status_option); ?>"
                            <?php echo ($order['status'] === $status_option) ? 'selected' : ''; ?>
                        >
                            <?php echo sparrow_escape($status_option); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div>
                <label for="customer_phone">Phone</label>
                <input
                    type="text"
                    id="customer_phone"
                    name="customer_phone"
                    value="<?php echo sparrow_escape($order['customer_phone']); ?>"
                >
            </div>

            <div>
                <label for="customer_email">Email</label>
                <input
                    type="email"
                    id="customer_email"
                    name="customer_email"
                    value="<?php echo sparrow_escape($order['customer_email']); ?>"
                >
            </div>
        </div>

        <div class="form-section">
            <label for="notes">Order Notes</label>
            <textarea
    id="notes"
    name="notes"
    rows="4"
><?php echo sparrow_escape($order['notes'] ?? ''); ?></textarea>
        </div>

        <div class="form-actions">
            <button type="submit" class="button">
                Save Customer Info
            </button>

            <button type="button" class="button button-secondary" id="cancel-customer-edit">
                Cancel
            </button>
        </div>
    </form>
</div>
</section>

<?php
$total_amount = (float) ($order['total_amount'] ?? 0);
$paid_amount = (float) ($order['paid_amount'] ?? 0);
$blessing_amount = (float) ($order['blessing_amount'] ?? 0);
$order_discount_amount = (float) ($order['order_discount_amount'] ?? 0);

$is_gift = !empty($order['is_gift']);

$customer_total_after_discount = max(0, $total_amount - $order_discount_amount);

$balance_amount = $is_gift
    ? 0.00
    : max(0, $customer_total_after_discount - $paid_amount);
	
	$profit_revenue = $is_gift
    ? 0.00
    : $customer_total_after_discount;

$supplier_item_cost = (float) ($order['supplier_item_cost'] ?? 0);
$shipping_cost = (float) ($order['shipping_cost'] ?? 0);
$discount_cost = (float) ($order['discount_cost'] ?? 0);
$tax_cost = (float) ($order['tax_cost'] ?? 0);
$other_cost = (float) ($order['other_cost'] ?? 0);

$pricing_lookup = sparrow_calculate_order_pricing_from_lookup($order_id);
$blank_cost_total = (float) ($pricing_lookup['blank_cost_total'] ?? 0);

/*
 * Blank Products is an estimate from the pricing table.
 * Once Supplier Splitter has real supplier item costs,
 * do not count the blank estimate again.
 */
$counted_blank_cost_total = $supplier_item_cost > 0
    ? 0.00
    : $blank_cost_total;

$total_internal_costs =
    $counted_blank_cost_total
    + $supplier_item_cost
    + $shipping_cost
    + $tax_cost
    + $other_cost
    - $discount_cost;
?>

<div class="payment-delivery-row">
<section class="card">
    <h2>Delivery Method</h2>

    <form method="post">
        <input type="hidden" name="action" value="save_delivery">

        <div class="form-grid">
            <div>
                <label for="delivery_method">Method</label>
                <select id="delivery_method" name="delivery_method">
                    <?php foreach ($delivery_method_options as $method_option): ?>
                        <option
                            value="<?php echo sparrow_escape($method_option); ?>"
                            <?php echo (($order['delivery_method'] ?? '') === $method_option) ? 'selected' : ''; ?>
                        >
                            <?php echo sparrow_escape($method_option); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
		
<div
    id="customer-shipping-field"
    <?php if (strcasecmp((string) ($order['delivery_method'] ?? ''), 'Shipping') !== 0): ?>
        style="display: none;"
    <?php endif; ?>
>
    <label for="order_shipping_amount">Customer Shipping</label>

    <input
        type="number"
        step="0.01"
        min="0"
        id="order_shipping_amount"
        name="order_shipping_amount"
        value="<?php echo sparrow_escape(number_format((float) ($order['order_shipping_amount'] ?? 0), 2, '.', '')); ?>"
    >
</div>

<div class="form-section">
    <label for="delivery_notes">Delivery Notes</label>
    <textarea
        id="delivery_notes"
        name="delivery_notes"
        rows="3"
        placeholder="Pickup details, shipping address, local delivery notes..."
    ><?php echo sparrow_escape($order['delivery_notes'] ?? ''); ?></textarea>
</div>
        <button type="submit" class="button">Save Delivery Method</button>
    </form>
	
</section>

<section class="card">
    <h2>Payment Info</h2>

    <form method="post">
        <input type="hidden" name="action" value="save_payment">

        <div class="form-grid">
            <div>
                <label for="total_amount">Total Amount</label>
                <input
                    type="number"
                    step="0.01"
                    min="0"
                    id="total_amount"
                    name="total_amount"
                    value="<?php echo sparrow_escape(number_format($total_amount, 2, '.', '')); ?>"
                >
            </div>

            <div>
                <label for="paid_amount">Paid Amount</label>
                <input
                    type="number"
                    step="0.01"
                    min="0"
                    id="paid_amount"
                    name="paid_amount"
                    value="<?php echo sparrow_escape(number_format($paid_amount, 2, '.', '')); ?>"
                >
            </div>
			
			<div>
    <label for="order_discount_amount">Order Discount</label>
    <input
        type="number"
        step="0.01"
        id="order_discount_amount"
        name="order_discount_amount"
        value="<?php echo sparrow_escape($order['order_discount_amount'] ?? '0.00'); ?>"
    >
</div>

            <div>
                <label for="blessing_amount">Blessing / Tip</label>
                <input
                    type="number"
                    step="0.01"
                    min="0"
                    id="blessing_amount"
                    name="blessing_amount"
                    value="<?php echo sparrow_escape(number_format($blessing_amount, 2, '.', '')); ?>"
                >
            </div>

            <div>
                <label>Balance</label>
                <div class="fake-input">
                    $<?php echo number_format($balance_amount, 2); ?>
                </div>
            </div>
			
			<div>
    <label for="payment_method">Payment Method</label>
    <select id="payment_method" name="payment_method">
        <?php
        $payment_methods = [
            '',
            'Cash',
            'Cash App',
            'PayPal',
            'Venmo',
            'Card',
            'Check',
            'Other',
        ];

        $current_payment_method = $order['payment_method'] ?? '';
        ?>

        <?php foreach ($payment_methods as $method): ?>
            <option
                value="<?php echo sparrow_escape($method); ?>"
                <?php echo ($current_payment_method === $method) ? 'selected' : ''; ?>
            >
                <?php echo $method === '' ? 'Not Set' : sparrow_escape($method); ?>
            </option>
        <?php endforeach; ?>
    </select>
</div>
        </div>

        <button type="submit" class="button">
            Save Payment
        </button>
    </form>
	
	<form method="post" class="gift-order-form">
    <input type="hidden" name="action" value="save_gift">

    <label class="gift-order-toggle">
        <input
            type="checkbox"
            name="is_gift"
            value="1"
            <?php echo !empty($order['is_gift']) ? 'checked' : ''; ?>
        >

        <span>
            Gift Order
            <small>No customer payment required</small>
        </span>
    </label>

    <button type="submit" class="button">
        Save Gift Setting
    </button>
</form>
</section>
</div>

<section class="card">
    <h2>Items</h2>

    <form method="post">
        <input type="hidden" name="action" value="save_items">

        <table class="items-edit-table">
            <thead>
                <tr>
                    <th>Qty</th>
                    <th>Type</th>
                    <th>Size / Style</th>
                    <th>Color</th>
					<th>Customer Supplied</th>
					<th>Gift</th>
                    <th>Specialty</th>
                    <th>Print Location</th>
                    <th>Notes</th>
                    <th>Remove</th>
                </tr>
            </thead>
            <tbody id="items-table-body">
                <?php foreach ($items as $index => $item): ?>
<tr>
    <td>
        <input
            type="hidden"
            name="item_id[]"
            value="<?php echo (int) ($item['id'] ?? 0); ?>"
        >

        <input
            type="number"
            name="quantity[]"
            value="<?php echo (int) $item['quantity']; ?>"
            min="1"
        >
    </td>
                    <td>
                        <select name="item_type[]">
                            <?php foreach ($item_type_options as $type_option): ?>
                                <option
                                    value="<?php echo sparrow_escape($type_option); ?>"
                                    <?php echo (($item['item_type'] ?? '') === $type_option) ? 'selected' : ''; ?>
                                >
                                    <?php echo sparrow_escape($type_option); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td><input type="text" name="shirt_size[]" value="<?php echo htmlspecialchars($item['shirt_size'] ?? ''); ?>" placeholder="Large, Regular, Skinny"></td>
                    <td><input type="text" name="shirt_color[]" value="<?php echo htmlspecialchars((string) ($item['shirt_color'] ?? '')); ?>"></td>
					<td>
    <input
        type="hidden"
        name="customer_supplied[]"
        class="customer-supplied-value"
        value="<?php echo !empty($item['customer_supplied']) ? '1' : '0'; ?>"
    >

    <label class="customer-supplied-edit">
        <input
            type="checkbox"
            class="customer-supplied-checkbox"
            <?php echo !empty($item['customer_supplied']) ? 'checked' : ''; ?>
        >
        <span>Yes</span>
    </label>
</td>

<td>
    <input
        type="hidden"
        name="item_gift[]"
        class="item-gift-value"
        value="<?php echo !empty($item['is_gift']) ? '1' : '0'; ?>"
    >

    <label class="customer-supplied-edit">
        <input
            type="checkbox"
            class="item-gift-checkbox"
            <?php echo !empty($item['is_gift']) ? 'checked' : ''; ?>
        >
        <span>Yes</span>
    </label>
</td>
                    <td>
                        <select name="specialty[]">
                            <?php foreach ($specialty_options as $specialty_option): ?>
                                <option
                                    value="<?php echo sparrow_escape($specialty_option); ?>"
                                    <?php echo (($item['specialty'] ?? '') === $specialty_option) ? 'selected' : ''; ?>
                                >
                                    <?php echo sparrow_escape($specialty_option); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td>
                        <select name="print_location[]">
                            <?php foreach ($print_location_options as $location_option): ?>
                                <option
                                    value="<?php echo sparrow_escape($location_option); ?>"
                                    <?php echo (($item['print_location'] ?? '') === $location_option) ? 'selected' : ''; ?>
                                >
                                    <?php echo sparrow_escape($location_option); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td><input type="text" name="item_notes[]" value="<?php echo htmlspecialchars((string) ($item['item_notes'] ?? '')); ?>"></td>
                    <td><button type="button" class="remove-item-button">Remove</button></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
<br>
        <button type="button" id="add-item-row">Add Item</button>
        <button type="submit" class="button">Save Items</button>
    </form>
</section>

<section class="card">
    <h2>Line Item Approvals</h2>

    <?php foreach ($items as $index => $item): ?>
        <?php
        $order_item_id = (int) ($item['id'] ?? 0);

        $item_approval_images =
            sparrow_get_order_item_approval_images(
                $order_item_id
            );

        $item_approval_status =
            $item['approval_status'] ?? 'waiting';

        $item_approval_status_labels = [
            'waiting' => 'Waiting',
            'approved' => 'Approved',
            'changes_requested' => 'Changes Requested',
        ];

        $item_approval_status_label =
            $item_approval_status_labels[
                $item_approval_status
            ] ?? 'Waiting';
        ?>

        <div class="item-card">
            <h3>
                Item <?= $index + 1 ?>:
                <?= htmlspecialchars(
                    (string) ($item['item_type'] ?? 'Item')
                ) ?>
            </h3>

            <p>
                <strong>Quantity:</strong>
                <?= (int) ($item['quantity'] ?? 1) ?>

                <?php if (!empty($item['shirt_size'])): ?>
                    |
                    <strong>Size:</strong>
                    <?= htmlspecialchars(
                        (string) $item['shirt_size']
                    ) ?>
                <?php endif; ?>

                <?php if (!empty($item['shirt_color'])): ?>
                    |
                    <strong>Color:</strong>
                    <?= htmlspecialchars(
                        (string) $item['shirt_color']
                    ) ?>
                <?php endif; ?>
            </p>

            <p>
                <strong>Approval Status:</strong>
                <?= htmlspecialchars(
                    $item_approval_status_label
                ) ?>
            </p>
			
			<?php if (
    $item_approval_status === 'changes_requested'
): ?>
    <p>
        <strong>Customer’s Requested Changes:</strong><br>

        <?= nl2br(
            sparrow_escape(
                (string) (
                    $item['customer_approval_notes']
                    ?? ''
                )
            )
        ) ?>
    </p>
<?php elseif (
    $item_approval_status === 'approved'
): ?>
    <p>
        <strong>Customer Response:</strong>
        This item was approved.
    </p>
<?php else: ?>
    <p>
        <strong>Customer Response:</strong>
        No response yet.
    </p>
<?php endif; ?>

<?php if (!empty($item['approval_responded_at'])): ?>
    <p>
        <strong>Responded:</strong>

        <?= sparrow_escape(
            date(
                'F j, Y \a\t g:i A',
                strtotime(
                    (string) $item[
                        'approval_responded_at'
                    ]
                )
            )
        ) ?>
    </p>
<?php endif; ?>

            <p>
    <strong>Approval Images:</strong>
    <?= count($item_approval_images) ?>
</p>

<?php if ($item_approval_images): ?>
    <div
    class="item-approval-images"
    style="
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        align-items: flex-start;
    "
>
        <?php foreach (
            $item_approval_images
            as $saved_position => $approval_image
        ): ?>
            <?php
            $saved_image_path = (string) (
                $approval_image['image_path'] ?? ''
            );

            $saved_image_url =
                '../'
                . ltrim($saved_image_path, '/');

            $saved_position_label =
                $approval_image_positions[
                    $saved_position
                ] ?? ucfirst($saved_position);
            ?>

            <div
    class="item-approval-image"
    style="
        flex: 0 1 300px;
        max-width: 300px;
    "
>
                <p>
                    <strong>
                        <?= sparrow_escape(
                            $saved_position_label
                        ) ?>
                    </strong>
                </p>

                <img
                    src="<?= sparrow_escape(
                        $saved_image_url
                    ) ?>"
                    alt="<?= sparrow_escape(
                        $saved_position_label
                        . ' approval image'
                    ) ?>"
                    style="
                        display: block;
                        max-width: 300px;
                        width: 100%;
                        height: auto;
                        border-radius: 10px;
                    "
                >
				<form
    method="post"
    style="margin: 10px 0 24px;"
>
    <input
        type="hidden"
        name="action"
        value="delete_item_approval_image"
    >

    <input
        type="hidden"
        name="order_item_id"
        value="<?= $order_item_id ?>"
    >

    <input
        type="hidden"
        name="image_position"
        value="<?= sparrow_escape(
            $saved_position
        ) ?>"
    >

    <button type="submit" class="button">
        Remove <?= sparrow_escape(
            $saved_position_label
        ) ?> Image
    </button>
</form>
            </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

<form
    method="post"
    enctype="multipart/form-data"
    class="item-approval-upload-form"
>
    <input
        type="hidden"
        name="action"
        value="save_item_approval_image"
    >

    <input
        type="hidden"
        name="order_item_id"
        value="<?= $order_item_id ?>"
    >

    <div class="sparrow-form-field">
        <label for="item_approval_position_<?= $order_item_id ?>">
            Image Position
        </label>

        <select
            id="item_approval_position_<?= $order_item_id ?>"
            name="image_position"
            required
        >
            <option value="">Choose a position...</option>

            <?php foreach (
                $approval_image_positions
                as $image_position => $position_label
            ): ?>
                <option
                    value="<?= sparrow_escape(
                        $image_position
                    ) ?>"
                >
                    <?= sparrow_escape($position_label) ?>

                    <?php if (
                        isset(
                            $item_approval_images[
                                $image_position
                            ]
                        )
                    ): ?>
                        (replace existing)
                    <?php endif; ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>

    <div class="sparrow-form-field">
        <label for="item_approval_file_<?= $order_item_id ?>">
            Approval Image
        </label>

        <input
            type="file"
            id="item_approval_file_<?= $order_item_id ?>"
            name="approval_image"
            accept=".jpg,.jpeg,.png,.gif,.webp"
            required
        >
    </div>

    <button type="submit" class="button" style="margin: 10px 0 24px;">
        Upload Approval Image
    </button>
</form>

<form
    method="post"
    class="item-approval-notes-form"
    style="margin-top: 24px;"
>
    <input
        type="hidden"
        name="action"
        value="save_item_approval_notes"
    >

    <input
        type="hidden"
        name="order_item_id"
        value="<?= $order_item_id ?>"
    >

    <div class="sparrow-form-field">
        <label for="approval_notes_<?= $order_item_id ?>">
            Approval Notes
        </label>

        <textarea
            id="approval_notes_<?= $order_item_id ?>"
            name="approval_notes"
            rows="3"
            placeholder="Add information for the customer about this item..."
        ><?= sparrow_escape(
            (string) ($item['approval_notes'] ?? '')
        ) ?></textarea>
    </div>

    <button type="submit" class="button">
        Save Approval Notes
    </button>
</form>
        </div>
    <?php endforeach; ?>
</section>

<section class="card">
    <h2>Internal Costs</h2>

    <form method="post">
        <input type="hidden" name="action" value="save_internal_costs">

        <!-- Two-column grid for cost inputs -->
        <div class="internal-cost-grid" style="grid-template-columns: 1fr 1fr; gap: 1rem;">
		<div class="sparrow-form-field">
    <label for="supplier_item_cost_display">
        Supplier Items
    </label>

    <input
        type="number"
        step="0.01"
        id="supplier_item_cost_display"
        value="<?= htmlspecialchars(
            number_format(
                (float) ($order['supplier_item_cost'] ?? 0),
                2,
                '.',
                ''
            )
        ) ?>"
        readonly
    >

    <p class="muted" style="margin: 5px 0 0;">
        Added through Supplier Splitter.
    </p>
</div>
<div class="sparrow-form-field">
    <label for="blank_cost_display">
        Blank Products
    </label>

    <input
        type="number"
        step="0.01"
        id="blank_cost_display"
        value="<?= htmlspecialchars(
            number_format(
                $blank_cost_total,
                2,
                '.',
                ''
            )
        ) ?>"
        readonly
    >

    <p class="muted" style="margin: 5px 0 0;">
        Calculated from order items and pricing.
    </p>
</div>
            <div class="sparrow-form-field">
                <label for="shipping_cost">Shipping Cost</label>
                <input
                    type="number"
                    step="0.01"
                    min="0"
                    id="shipping_cost"
                    name="shipping_cost"
                    value="<?= htmlspecialchars(number_format((float) ($order['shipping_cost'] ?? 0), 2, '.', '')) ?>"
                >
            </div>

            <div class="sparrow-form-field">
                <label for="tax_cost">Tax</label>
                <input
                    type="number"
                    step="0.01"
                    min="0"
                    id="tax_cost"
                    name="tax_cost"
                    value="<?= htmlspecialchars(number_format((float) ($order['tax_cost'] ?? 0), 2, '.', '')) ?>"
                >
            </div>

            <div class="sparrow-form-field">
                <label for="other_cost">Other Cost</label>
                <input
                    type="number"
                    step="0.01"
                    min="0"
                    id="other_cost"
                    name="other_cost"
                    value="<?= htmlspecialchars(number_format((float) ($order['other_cost'] ?? 0), 2, '.', '')) ?>"
                >
            </div>

            <div class="sparrow-form-field">
                <label for="discount_cost">Discount / Credit</label>
                <input
                    type="number"
                    step="0.01"
                    min="0"
                    id="discount_cost"
                    name="discount_cost"
                    value="<?= htmlspecialchars(number_format((float) ($order['discount_cost'] ?? 0), 2, '.', '')) ?>"
                >
            </div>
        </div>

        <!-- Full-width notes -->
        <div class="sparrow-form-field" style="margin-top: 1rem;">
            <label for="internal_cost_notes">Internal Cost Notes</label>
            <textarea
                id="internal_cost_notes"
                name="internal_cost_notes"
                rows="3"
            ><?= htmlspecialchars($order['internal_cost_notes'] ?? '') ?></textarea>
        </div>

        <!-- Summary line -->
        <div class="sparrow-summary-line" style="margin-top: 0.5rem;">
            <strong>Total Internal Extra Costs:</strong>
            $<?= number_format($total_internal_costs, 2) ?>
        </div>

        <!-- Save button -->
        <button type="submit" class="button" style="margin-top: 1rem;">
            Save Internal Costs
        </button>
    </form>
</section>

<div class="notes-row">
    <section class="card">
        <h2>Order Notes</h2>

        <form method="post">
            <input type="hidden" name="action" value="save_order_notes">

            <textarea
                name="order_notes"
                rows="5"
                placeholder="Customer-visible notes for this order"
            ><?= htmlspecialchars($order['notes'] ?? '') ?></textarea>

            <div class="form-actions">
                <button type="submit" class="button">
                    Save Order Notes
                </button>
            </div>
        </form>
    </section>
	
    <section class="card">
        <h2>Admin Notes</h2>

        <form method="post">
            <input type="hidden" name="action" value="save_admin_notes">

            <textarea
                name="admin_notes"
                rows="5"
                placeholder="Private notes for this Backyard order"
            ><?= htmlspecialchars($order['admin_notes'] ?? '') ?></textarea>

            <div class="form-actions">
                <button type="submit" class="button">
                    Save Admin Notes
                </button>
            </div>
        </form>
    </section>

</div>

<?php if ($reference_images): ?>
    <section class="card">
        <h2>Customer Reference Images</h2>

        <p class="muted">
            Artwork or inspiration supplied with this order.
        </p>

        <div class="reference-image-grid">
            <?php foreach ($reference_images as $reference_image): ?>
                <?php
                $product_type = trim(
                    (string) $reference_image['product_type']
                );

                $item_number = max(
                    1,
                    (int) $reference_image['item_number']
                );

                $image_position = ucfirst(
                    (string) $reference_image['image_position']
                );

                $image_path = (string) $reference_image['image_path'];

                $original_name = trim(
                    (string) (
                        $reference_image['original_name'] ?? ''
                    )
                );

                $extension = strtolower(
                    pathinfo($image_path, PATHINFO_EXTENSION)
                );

                $is_image = in_array(
                    $extension,
                    ['jpg', 'jpeg', 'png', 'gif', 'webp'],
                    true
                );

                $reference_url = sparrow_url($image_path);
                ?>

                <div class="reference-image-card">
                    <h3>
                        <?= sparrow_escape($product_type) ?>
                        Entry #<?= $item_number ?>
                        &mdash;
                        <?= sparrow_escape($image_position) ?>
                    </h3>

                    <?php if ($is_image): ?>
                        <a
                            href="<?= sparrow_escape(
                                $reference_url
                            ) ?>"
                            target="_blank"
                            rel="noopener"
                        >
                            <img
                                src="<?= sparrow_escape(
                                    $reference_url
                                ) ?>"
                                alt="<?= sparrow_escape(
                                    $product_type
                                    . ' Entry #'
                                    . $item_number
                                    . ' '
                                    . $image_position
                                    . ' Reference'
                                ) ?>"
                                class="reference-image-preview"
                            >
                        </a>
                    <?php else: ?>
                        <a
                            class="button button-secondary"
                            href="<?= sparrow_escape(
                                $reference_url
                            ) ?>"
                            target="_blank"
                            rel="noopener"
                        >
                            Open Reference PDF
                        </a>
                    <?php endif; ?>

                    <?php if ($original_name !== ''): ?>
                        <p class="muted reference-file-name">
                            <?= sparrow_escape($original_name) ?>
                        </p>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </section>
<?php endif; ?>

<?php
$approval_status = $order['approval_status'] ?? 'waiting';

$customer_approval_notes = trim(
    (string) ($order['customer_approval_notes'] ?? '')
);

$approval_responded_at = trim(
    (string) ($order['approval_responded_at'] ?? '')
);

$approval_response_date = '';

if ($approval_responded_at !== '') {
    $approval_response_timestamp = strtotime($approval_responded_at);

    if ($approval_response_timestamp !== false) {
        $approval_response_date = date(
            'F j, Y \\a\\t g:i A',
            $approval_response_timestamp
        );
    }
}

$approval_status_labels = [
    'waiting' => 'Waiting',
    'approved' => 'Approved',
    'changes_requested' => 'Changes Requested',
];

$approval_status_label = $approval_status_labels[$approval_status] ?? 'Waiting';
?>
<section class="card">
    <h2>Customer Approval</h2>
<div class="approval-status-buttons" style="margin-top: 12px; display: flex; gap: 10px;">
    <form method="post" style="display:inline;">
        <input type="hidden" name="action" value="set_approval_status">
        <input type="hidden" name="approval_status" value="approved">
        <button type="submit" class="button button-success">
            Approve
        </button>
    </form>

    <form method="post" style="display:inline;">
        <input type="hidden" name="action" value="set_approval_status">
        <input type="hidden" name="approval_status" value="changes_requested">
        <button type="submit" class="button button-secondary">
            Changes Requested
        </button>
    </form>
</div>

<p>
    <strong>Approval Status:</strong>
    <span class="approval-status-pill approval-status-<?= htmlspecialchars($approval_status) ?>">
        <?= htmlspecialchars($approval_status_label) ?>
    </span>
</p>

<?php if ($customer_approval_notes !== ''): ?>
    <div class="customer-approval-response">
        <h3>Customer Requested Changes</h3>

        <p>
            <?= nl2br(htmlspecialchars($customer_approval_notes)) ?>
        </p>

        <?php if ($approval_response_date !== ''): ?>
            <p class="customer-approval-response-date">
                Submitted <?= htmlspecialchars($approval_response_date) ?>
            </p>
        <?php endif; ?>
    </div>
<?php elseif (
    $approval_status === 'approved'
    && $approval_response_date !== ''
): ?>
    <div class="customer-approval-response">
        <h3>Customer Approved Design</h3>

        <p class="customer-approval-response-date">
            Submitted <?= htmlspecialchars($approval_response_date) ?>
        </p>
    </div>
<?php endif; ?>

    <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="action" value="save_approval">

        <div class="approval-image-manager">
<?php
$has_empty_approval_position = count($approval_images)
    < count($approval_image_positions);
?>

<?php if ($has_empty_approval_position): ?>
    <div class="approval-image-add-row">
        <label for="approval_position_picker">
            Add Approval Image
        </label>

        <select id="approval_position_picker">
            <option value="">
                Choose a position...
            </option>

            <?php foreach (
                $approval_image_positions
                as $image_position => $position_label
            ): ?>
                <?php if (
                    empty($approval_images[$image_position])
                ): ?>
                    <option
                        value="<?= sparrow_escape(
                            $image_position
                        ) ?>"
                    >
                        <?= sparrow_escape($position_label) ?>
                    </option>
                <?php endif; ?>
            <?php endforeach; ?>
        </select>

        <button
            type="button"
            class="button button-secondary"
            id="add_approval_position"
        >
            Add Image
        </button>
    </div>
<?php endif; ?>

<div class="approval-upload-grid">
    <?php foreach (
        $approval_image_positions
        as $image_position => $position_label
    ): ?>
        <?php
        $position_image =
            $approval_images[$image_position] ?? null;

        $input_name =
            'approval_image_' . $image_position;
        ?>

        <div
            class="approval-upload-box"
            id="approval_box_<?= sparrow_escape(
                $image_position
            ) ?>"
            <?php if (!$position_image): ?>
                hidden
            <?php endif; ?>
        >
            <h3>
                <?= sparrow_escape($position_label) ?>
            </h3>

            <?php if ($position_image): ?>
                <img
                    src="<?= sparrow_escape(
                        sparrow_url(
                            $position_image['image_path']
                        )
                    ) ?>"
                    alt="<?= sparrow_escape(
                        $position_label
                    ) ?> Approval Image"
                    class="approval-position-preview"
                >

                <p class="muted">
                    Choose another image to replace this one.
                </p>
            <?php else: ?>
                <p class="muted">
                    Choose an image to add this section.
                </p>
            <?php endif; ?>

            <input
                type="file"
                id="<?= sparrow_escape($input_name) ?>"
                name="<?= sparrow_escape($input_name) ?>"
                accept="image/jpeg,image/png,image/gif,image/webp"
            >
        </div>
    <?php endforeach; ?>
</div>
        </div>

        <div class="form-section">
            <label for="approval_notes">Approval Notes</label>
            <textarea
                id="approval_notes"
                name="approval_notes"
                rows="3"
                placeholder="Approval notes"
            ><?= htmlspecialchars($order['approval_notes'] ?? '') ?></textarea>
        </div>

        <div class="form-actions">
            <button type="submit" class="button">
                Upload / Save Approval
            </button>
        </div>
    </form>
</section>
</div>

    <aside class="order-summary-side">
        <section class="card profit-summary-card">
            <h2>Profit Summary</h2>

            <div class="summary-row">
                <span>Total Amount</span>
                <strong>$<?= number_format((float) ($order['total_amount'] ?? 0), 2) ?></strong>
            </div>

            <div class="summary-row">
                <span>Paid Amount</span>
                <strong>$<?= number_format((float) ($order['paid_amount'] ?? 0), 2) ?></strong>
            </div>

            <div class="summary-row">
                <span>Balance</span>
                <strong>$<?= number_format((float) ($balance_amount ?? 0), 2) ?></strong>
            </div>

            <div class="summary-row">
                <span>Blessing / Tip</span>
                <strong>$<?= number_format((float) ($order['blessing_amount'] ?? 0), 2) ?></strong>
            </div>

            <div class="summary-row">
    <span>
        Blank Products
        <?php if ($supplier_item_cost > 0): ?>
            <small class="muted">(estimate only)</small>
        <?php endif; ?>
    </span>
    <strong>
        $<?= number_format($counted_blank_cost_total, 2) ?>
    </strong>
</div>

<?php if ($supplier_item_cost > 0 && $blank_cost_total > 0): ?>
    <div class="summary-row">
        <span>Blank Estimate Not Counted</span>
        <strong>$<?= number_format($blank_cost_total, 2) ?></strong>
    </div>
<?php endif; ?>

<div class="summary-row">
    <span>Supplier Items</span>
    <strong>$<?= number_format($supplier_item_cost, 2) ?></strong>
</div>

<div class="summary-row">
    <span>Shipping</span>
    <strong>$<?= number_format($shipping_cost, 2) ?></strong>
</div>

<div class="summary-row">
    <span>Tax</span>
    <strong>$<?= number_format($tax_cost, 2) ?></strong>
</div>

<div class="summary-row">
    <span>Travel / Other</span>
    <strong>$<?= number_format($other_cost, 2) ?></strong>
</div>

<div class="summary-row">
    <span>Supplier Discount</span>
    <strong>-$<?= number_format($discount_cost, 2) ?></strong>
</div>

<div class="summary-row summary-row-total">
    <span>Total Internal Costs</span>
    <strong>$<?= number_format($total_internal_costs, 2) ?></strong>
</div>

            <hr>

            <div class="summary-row summary-row-total">
                <span>Estimated Profit</span>
                <strong>
                    $<?= number_format($profit_revenue - $total_internal_costs, 2) ?>
                </strong>
            </div>

           <p class="muted summary-note">
    Blank products, supplier items, shipping, tax, travel,
    and supplier discounts are included.
</p>
        </section>
    </aside>
</div>

<script>
    const toggleCustomerEdit = document.getElementById('toggle-customer-edit');
    const cancelCustomerEdit = document.getElementById('cancel-customer-edit');
    const customerEditBox = document.getElementById('customer-edit-box');

    if (toggleCustomerEdit && customerEditBox) {
        toggleCustomerEdit.addEventListener('click', () => {
            customerEditBox.style.display =
                customerEditBox.style.display === 'none' ? 'block' : 'none';
        });
    }

    if (cancelCustomerEdit && customerEditBox) {
        cancelCustomerEdit.addEventListener('click', () => {
            customerEditBox.style.display = 'none';
        });
    }
</script>

<script>
const tbody = document.getElementById('items-table-body');
const addItemButton = document.getElementById('add-item-row');

function updateCustomerSuppliedValue(row) {
    const checkbox = row.querySelector(
        '.customer-supplied-checkbox'
    );

    const hiddenValue = row.querySelector(
        '.customer-supplied-value'
    );

    if (!checkbox || !hiddenValue) {
        return;
    }

    hiddenValue.value = checkbox.checked ? '1' : '0';
}

function updateItemGiftValue(row) {
    const checkbox = row.querySelector(
        '.item-gift-checkbox'
    );

    const hiddenValue = row.querySelector(
        '.item-gift-value'
    );

    if (!checkbox || !hiddenValue) {
        return;
    }

    hiddenValue.value = checkbox.checked ? '1' : '0';
}

addItemButton.addEventListener('click', () => {
    const firstRow = tbody.querySelector('tr');
    const newRow = firstRow.cloneNode(true);

    newRow.querySelectorAll('input').forEach(input => {
        if (
            input.classList.contains(
                'customer-supplied-checkbox'
            )
        ) {
            input.checked = false;
            return;
        }
		
		if (
    input.classList.contains(
        'item-gift-value'
    )
) {
    input.value = '0';
    return;
}

        if (
            input.classList.contains(
                'customer-supplied-value'
            )
        ) {
            input.value = '0';
            return;
        }

        input.value = '';
    });

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

    tbody.appendChild(newRow);
});

tbody.addEventListener('change', (e) => {
    if (
        e.target.classList.contains(
            'customer-supplied-checkbox'
        )
    ) {
        updateCustomerSuppliedValue(
            e.target.closest('tr')
        );
    }
	
if (
    e.target.classList.contains(
        'item-gift-checkbox'
    )
) {
    updateItemGiftValue(
        e.target.closest('tr')
    );
}
});

tbody.addEventListener('click', (e) => {
    if (e.target.classList.contains('remove-item-button')) {
        const rows = tbody.querySelectorAll('tr');

        if (rows.length > 1) {
            e.target.closest('tr').remove();
        }
    }
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const fileInput = document.getElementById('approval_image');
    const fileName = document.querySelector('.file-upload-name');

    if (!fileInput || !fileName) {
        return;
    }

    fileInput.addEventListener('change', function () {
        fileName.textContent = fileInput.files.length
            ? fileInput.files[0].name
            : 'No file chosen';
    });
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const deliveryMethod = document.getElementById('delivery_method');
    const shippingField = document.getElementById('customer-shipping-field');
    const shippingInput = document.getElementById('order_shipping_amount');

    if (!deliveryMethod || !shippingField || !shippingInput) {
        return;
    }

    function updateShippingVisibility(clearWhenHidden) {
        const isShipping =
            deliveryMethod.value.trim().toLowerCase() === 'shipping';

        shippingField.style.display = isShipping ? '' : 'none';

        if (!isShipping && clearWhenHidden) {
            shippingInput.value = '0.00';
        }
    }

    deliveryMethod.addEventListener('change', function () {
        updateShippingVisibility(true);
    });

    updateShippingVisibility(false);
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const picker = document.getElementById(
        'approval_position_picker'
    );

    const addButton = document.getElementById(
        'add_approval_position'
    );

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

    addButton.addEventListener('click', function () {
        const position = picker.value;

        if (!position) {
            return;
        }

        const box = document.getElementById(
            'approval_box_' + position
        );

        if (!box) {
            return;
        }

        box.hidden = false;

        const selectedOption =
            picker.options[picker.selectedIndex];

        selectedOption.disabled = true;
        picker.value = '';

        const fileInput = box.querySelector(
            'input[type="file"]'
        );

        if (fileInput) {
    fileInput.focus();
}
    });
});
</script>

<?php

sparrow_backyard_footer();
