<?php

require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/orders.php';
require_once __DIR__ . '/../app/settings.php';

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

function sparrow_order_edit_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_edit_dropdown_options(
    PDO $pdo,
    string $category,
    array $fallback,
    array $current_values = []
): array {
    $rows = sparrow_get_setting_rows($pdo, $category);
    $values = [];

    foreach ($rows 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;
}

$order_settings = sparrow_get_settings($pdo, [
    'status_list',
    'default_order_status',
]);

$statuses = sparrow_order_edit_lines(
    $order_settings['status_list'],
    [
        'Order Received',
        'Order Approved',
        'Products Ordered',
        'Pressing',
        'Packaging',
        'Ready for Pickup',
        'Delivered',
    ]
);

$default_order_status = trim($order_settings['default_order_status']);

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

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

if ($order_id <= 0) {
    sparrow_redirect('/backyard/dashboard.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;
}

$items = sparrow_get_order_items($order_id);
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $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'] ?? '');

	$item_ids = $_POST['item_id'] ?? [];
    $item_types = $_POST['item_type'] ?? [];
    $quantities = $_POST['quantity'] ?? [];
    $sizes = $_POST['shirt_size'] ?? [];
    $colors = $_POST['shirt_color'] ?? [];
    $specialties = $_POST['specialty'] ?? [];
    $print_locations = $_POST['print_location'] ?? [];
    $item_notes = $_POST['item_notes'] ?? [];
	$total_amount = (float) ($_POST['total_amount'] ?? 0);
$paid_amount = (float) ($_POST['paid_amount'] ?? 0);
$blessing_amount = (float) ($_POST['blessing_amount'] ?? 0);

$data['total_amount'] = $total_amount;
$data['paid_amount'] = $paid_amount;
$data['blessing_amount'] = $blessing_amount;

    $new_items = [];

    foreach ($item_types as $index => $item_type) {
		$item_id = (int) ($item_ids[$index] ?? 0);
        $quantity = (int) ($quantities[$index] ?? 1);
        $shirt_size = trim($sizes[$index] ?? '');
        $shirt_color = trim($colors[$index] ?? '');
        $specialty = trim($specialties[$index] ?? '');
        $print_location = trim($print_locations[$index] ?? '');
        $notes_for_item = trim($item_notes[$index] ?? '');

        if ($shirt_size === '' && $shirt_color === '' && $print_location === '' && $notes_for_item === '') {
            continue;
        }

        $new_items[] = [
			'id' => $item_id,
            'item_type' => trim($item_type) ?: 'Shirt',
            'quantity' => max(1, $quantity),
            'shirt_size' => $shirt_size,
            'shirt_color' => $shirt_color,
            'specialty' => $specialty,
            'print_location' => $print_location,
            'item_notes' => $notes_for_item,
        ];
    }

    if ($customer_name === '') {
        $error = 'Customer name is required.';
    } elseif (!$new_items) {
        $error = 'Please keep at least one item on this order.';
    } else {
        try {
            sparrow_update_order($order_id, [
                'customer_name' => $customer_name,
                'customer_email' => $customer_email,
                'customer_phone' => $customer_phone,
                'status' => $status,
                'notes' => $notes,
                'items' => $new_items,
            ]);

            sparrow_redirect('/backyard/order-view.php?id=' . $order_id);
        } catch (Throwable $e) {
            $error = 'Order could not be updated: ' . $e->getMessage();
        }
    }
}

if (!$items) {
    $items = [[
        'item_type' => 'Shirt',
        'quantity' => 1,
        'shirt_size' => '',
        'shirt_color' => '',
        'specialty' => 'None',
        'print_location' => 'Full Front',
        'item_notes' => '',
    ]];
}

$item_type_options = sparrow_order_edit_dropdown_options(
    $pdo,
    'item_type',
    ['Shirt', 'Koozie', 'Bookmark', 'Hat', 'Other'],
    array_column($items, 'item_type')
);

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

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

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

function selected_option(?string $current, string $value): string
{
    return $current === $value ? 'selected' : '';
}

sparrow_backyard_header('Edit ' . $order['order_number']);

?>

<section class="card">
    <div class="page-heading-row">
        <div>
            <h1>Edit <?php echo sparrow_escape($order['order_number']); ?></h1>
            <p class="muted">
                Update customer info, status, notes, and item rows.
            </p>
        </div>

        <div class="heading-actions">
            <a class="button button-secondary" href="<?php echo sparrow_escape(sparrow_url('/backyard/order-view.php?id=' . $order_id)); ?>">
                Back to Order
            </a>
        </div>
    </div>
</section>

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

    <form method="post" class="order-form">
        <div class="form-grid">
            <div>
                <label>Order Number</label>
                <input
                    type="text"
                    value="<?php echo sparrow_escape($order['order_number']); ?>"
                    disabled
                >
            </div>

            <div>
                <label for="status">Status</label>
                <select id="status" name="status">
                    <?php foreach ($statuses as $status_option): ?>
                        <option
                            value="<?php echo sparrow_escape($status_option); ?>"
                            <?php echo selected_option($order['status'], $status_option); ?>
                        >
                            <?php echo sparrow_escape($status_option); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </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="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-grid">
    <div>
        <label>Total Amount</label>
        <input type="number" name="total_amount" step="0.01" value="<?php echo sparrow_escape($order['total_amount']); ?>">
    </div>

    <div>
        <label>Paid Amount</label>
        <input type="number" name="paid_amount" step="0.01" value="<?php echo sparrow_escape($order['paid_amount']); ?>">
    </div>

    <div>
        <label>Blessing / Tip</label>
        <input type="number" name="blessing_amount" step="0.01" value="<?php echo sparrow_escape($order['blessing_amount']); ?>">
    </div>
</div>

        <h2>Items</h2>

        <div id="items-list">
            <?php foreach ($items as $item): ?>
    <div class="item-card">
        <input
            type="hidden"
            name="item_id[]"
            value="<?php echo (int) ($item['id'] ?? 0); ?>"
        >
                    <div class="form-grid">
                        <div>
                            <label>Item Type</label>
                            <select name="item_type[]">
                                <?php foreach ($item_type_options as $type_option): ?>
                                    <option
                                        value="<?php echo sparrow_escape($type_option); ?>"
                                        <?php echo selected_option($item['item_type'] ?? '', $type_option); ?>
                                    >
                                        <?php echo sparrow_escape($type_option); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div>
                            <label>Qty</label>
                            <input
                                type="number"
                                name="quantity[]"
                                value="<?php echo (int) ($item['quantity'] ?? 1); ?>"
                                min="1"
                            >
                        </div>

                        <div>
    <label>Size / Style</label>
    <input
        type="text"
        name="shirt_size[]"
        value="<?php echo sparrow_escape($item['shirt_size'] ?? ''); ?>"
        placeholder="Large, Regular, Skinny"
    >
</div>

                        <div>
                            <label>Color</label>
                            <input
                                type="text"
                                name="shirt_color[]"
                                value="<?php echo sparrow_escape($item['shirt_color'] ?? ''); ?>"
                            >
                        </div>

                        <div>
                            <label>Specialty</label>
                            <select name="specialty[]">
                                <?php foreach ($specialty_options as $specialty_option): ?>
                                    <option
                                        value="<?php echo sparrow_escape($specialty_option); ?>"
                                        <?php echo selected_option($item['specialty'] ?? '', $specialty_option); ?>
                                    >
                                        <?php echo sparrow_escape($specialty_option); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div>
                            <label>Print Location</label>
                            <select name="print_location[]">
                                <?php foreach ($print_location_options as $location_option): ?>
                                    <option
                                        value="<?php echo sparrow_escape($location_option); ?>"
                                        <?php echo selected_option($item['print_location'] ?? '', $location_option); ?>
                                    >
                                        <?php echo sparrow_escape($location_option); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <label>Item Notes</label>
                    <textarea name="item_notes[]" rows="2"><?php echo sparrow_escape($item['item_notes'] ?? ''); ?></textarea>

                    <button type="button" class="button button-secondary remove-item-button">
                        Remove Item
                    </button>
                </div>
            <?php endforeach; ?>
        </div>

        <button type="button" class="button button-secondary" id="add-item-button">
            Add Another Item
        </button>

        <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 Changes</button>

            <a class="button button-secondary" href="<?php echo sparrow_escape(sparrow_url('/backyard/order-view.php?id=' . $order_id)); ?>">
                Cancel
            </a>
        </div>
    </form>
</section>

<script>
    const itemsList = document.getElementById('items-list');
    const addItemButton = document.getElementById('add-item-button');

    function refreshRemoveButtons() {
        const itemCards = itemsList.querySelectorAll('.item-card');
        const removeButtons = itemsList.querySelectorAll('.remove-item-button');

        removeButtons.forEach((button) => {
            button.style.display = itemCards.length > 1 ? 'inline-block' : 'none';
        });
    }

    addItemButton.addEventListener('click', () => {
        const firstItem = itemsList.querySelector('.item-card');
        const newItem = firstItem.cloneNode(true);

        newItem.querySelectorAll('input, textarea').forEach((field) => {
            if (field.type === 'number') {
                field.value = '1';
            } else {
                field.value = '';
            }
        });

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

        itemsList.appendChild(newItem);
        refreshRemoveButtons();
    });

    itemsList.addEventListener('click', (event) => {
        if (!event.target.classList.contains('remove-item-button')) {
            return;
        }

        const itemCards = itemsList.querySelectorAll('.item-card');

        if (itemCards.length <= 1) {
            return;
        }

        event.target.closest('.item-card').remove();
        refreshRemoveButtons();
    });

    refreshRemoveButtons();
</script>

<?php

sparrow_backyard_footer();
