<?php

require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/public-orders.php';

$user = sparrow_require_backyard_login();

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

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

    if ($action === 'update_request') {
        try {
            if ($request_id > 0) {
                sparrow_update_public_order_request_admin(
    $request_id,
    $_POST['status'] ?? 'New',
    $_POST['admin_notes'] ?? '',
    (float) ($_POST['quote_amount'] ?? 0),
    $_POST['quote_notes'] ?? '',
    $_POST['customer_message'] ?? ''
);

                $notice = 'Order request updated.';
            }
        } catch (Throwable $e) {
            $error = 'Order request could not be updated.';
        }
    }

    if ($action === 'delete_request') {
        try {
            if ($request_id > 0) {
                sparrow_delete_public_order_request($request_id);

                $notice = 'Order request deleted.';
            }
        } catch (Throwable $e) {
            $error = 'Order request could not be deleted.';
        }
    }
}

$requests = sparrow_get_public_order_requests();
$statuses = sparrow_public_order_statuses();

$active_requests = [];
$converted_requests = [];

foreach ($requests as $request) {
    $is_converted =
        ($request['status'] ?? '') === 'Converted'
        || !empty($request['converted_order_id']);

    if ($is_converted) {
        $converted_requests[] = $request;
    } else {
        $active_requests[] = $request;
    }
}

sparrow_backyard_header('Order Requests');

?>

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

<?php if (($_GET['error'] ?? '') === 'missing_quote'): ?>
    <div class="notice-error">
        Please enter a quote amount before converting this request to an order.
    </div>
<?php endif; ?>

<section class="card">
    <div class="page-heading-row">
        <div>
            <h1>Public Order Requests</h1>
            <p class="muted">
                Review requests submitted from the public website.
            </p>
        </div>

        <div class="heading-actions">
            <a class="button button-secondary" href="<?php echo sparrow_escape(sparrow_url('/order.php')); ?>" target="_blank">
                View Public Form
            </a>
        </div>
    </div>
</section>

<?php if (!$active_requests && !$converted_requests): ?>
    <section class="card">
        <p class="muted">No public order requests yet.</p>
    </section>
<?php else: ?>
    <?php foreach ($active_requests as $request): ?>
	<?php
$raw_form_data = json_decode(
    (string) ($request['raw_form_data'] ?? ''),
    true
);

if (!is_array($raw_form_data)) {
    $raw_form_data = [];
}

$uploaded_files = json_decode(
    (string) ($request['uploaded_files'] ?? ''),
    true
);

if (!is_array($uploaded_files)) {
    $uploaded_files = [];
}
?>
        <section
    class="card order-request-card"
    id="request-<?php echo (int) $request['id']; ?>"
>
            <div class="page-heading-row">
                <div>
                    <h2>
                        <?php echo sparrow_escape($request['customer_name']); ?>
                    </h2>

                    <p class="muted">
                        Submitted <?php echo sparrow_escape(date('M j, Y g:i A', strtotime($request['created_at']))); ?>
                    </p>
                </div>

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

            <div class="request-summary-panels">
    <div class="request-summary-panel">
        <h3>Contact Information</h3>

        <div class="request-summary-details">
            <div>
                <strong>Email:</strong>
                <?php echo sparrow_escape(
                    $request['customer_email'] ?: 'Not provided'
                ); ?>
            </div>

            <div>
                <strong>Phone:</strong>
                <?php echo sparrow_escape(
                    $request['customer_phone'] ?: 'Not provided'
                ); ?>
            </div>

            <div>
                <strong>Preferred Contact:</strong>
                <?php echo sparrow_escape(
                    $request['preferred_contact'] ?: 'Not provided'
                ); ?>
            </div>
        </div>
    </div>

    <div class="request-summary-panel">
        <h3>Request Summary</h3>

        <div class="request-summary-details">
            <div>
                <strong>Order Type:</strong>
                <?php echo sparrow_escape(
                    $request['order_type'] ?: 'Not provided'
                ); ?>
            </div>

            <div>
                <strong>Quantity:</strong>
                <?php echo sparrow_escape(
                    $request['quantity'] ?: 'Not provided'
                ); ?>
            </div>

            <div>
                <strong>Needed By:</strong>
                <?php echo !empty($request['needed_by'])
                    ? sparrow_escape(
                        date(
                            'M j, Y',
                            strtotime($request['needed_by'])
                        )
                    )
                    : 'Not provided'; ?>
            </div>
        </div>
    </div>
</div>

<?php
$product_type = trim(
    (string) (
        $raw_form_data['product_type']
        ?? $request['order_type']
        ?? ''
    )
);

$requested_items = [];

if ($product_type === 'Shirt') {
    $sizes = $raw_form_data['shirt_size'] ?? [];
    $quantities = $raw_form_data['shirt_quantity'] ?? [];
    $specialties = $raw_form_data['shirt_specialty'] ?? [];
    $colors = $raw_form_data['shirt_color'] ?? [];
    $placements = $raw_form_data['shirt_placement'] ?? [];
    $notes = $raw_form_data['shirt_notes'] ?? [];

    $item_count = max(
        count($sizes),
        count($quantities),
        count($colors),
        count($placements),
        count($notes)
    );

    for ($index = 0; $index < $item_count; $index++) {
        $quantity = trim(
            (string) ($quantities[$index] ?? '')
        );

        $note = trim(
            (string) ($notes[$index] ?? '')
        );

        if ($quantity === '' && $note === '') {
            continue;
        }

        $requested_items[] = [
            'product' => 'Shirt',
            'item_number' => $index + 1,
            'size' => trim(
                (string) ($sizes[$index] ?? '')
            ),
            'quantity' => $quantity,
            'specialty' => trim(
                (string) ($specialties[$index] ?? '')
            ),
            'color' => trim(
                (string) ($colors[$index] ?? '')
            ),
            'placement' => trim(
                (string) ($placements[$index] ?? '')
            ),
            'notes' => $note,
        ];
    }
}

if ($product_type === 'Koozie') {
    $quantities = $raw_form_data['koozie_quantity'] ?? [];
    $colors = $raw_form_data['koozie_color'] ?? [];
    $placements = $raw_form_data['koozie_placement'] ?? [];
    $notes = $raw_form_data['koozie_notes'] ?? [];

    $item_count = max(
        count($quantities),
        count($colors),
        count($placements),
        count($notes)
    );

    for ($index = 0; $index < $item_count; $index++) {
        $quantity = trim(
            (string) ($quantities[$index] ?? '')
        );

        $note = trim(
            (string) ($notes[$index] ?? '')
        );

        if ($quantity === '' && $note === '') {
            continue;
        }

        $requested_items[] = [
            'product' => 'Koozie',
            'item_number' => $index + 1,
            'quantity' => $quantity,
            'color' => trim(
                (string) ($colors[$index] ?? '')
            ),
            'placement' => trim(
                (string) ($placements[$index] ?? '')
            ),
            'notes' => $note,
        ];
    }
}
?>

<?php if ($requested_items): ?>
    <div class="form-section">
        <strong>Requested Items:</strong>

        <div class="request-item-grid">
            <?php foreach ($requested_items as $item): ?>
                <div class="request-item-card">
                    <h3>
                        <?= sparrow_escape($item['product']) ?>
                        Entry #<?= (int) $item['item_number'] ?>
                    </h3>

                    <div class="request-item-details">
                        <?php if (!empty($item['size'])): ?>
                            <div>
                                <strong>Size:</strong>
                                <?= sparrow_escape($item['size']) ?>
                            </div>
                        <?php endif; ?>

                        <?php if ($item['quantity'] !== ''): ?>
                            <div>
                                <strong>Quantity:</strong>
                                <?= sparrow_escape($item['quantity']) ?>
                            </div>
                        <?php endif; ?>

                        <?php if (!empty($item['color'])): ?>
                            <div>
                                <strong>Color:</strong>
                                <?= sparrow_escape($item['color']) ?>
                            </div>
                        <?php endif; ?>

                        <?php if (!empty($item['specialty'])): ?>
                            <div>
                                <strong>Specialty:</strong>
                                <?= sparrow_escape($item['specialty']) ?>
                            </div>
                        <?php endif; ?>

                        <?php if (!empty($item['placement'])): ?>
                            <div>
                                <strong>Placement:</strong>
                                <?= sparrow_escape($item['placement']) ?>
                            </div>
                        <?php endif; ?>
                    </div>

                    <?php if (!empty($item['notes'])): ?>
                        <p class="request-item-notes">
                            <strong>Notes:</strong><br>
                            <?= nl2br(
                                sparrow_escape($item['notes'])
                            ) ?>
                        </p>
                    <?php endif; ?>

                    <div class="request-reference-list">
                        <?php foreach ($uploaded_files as $file): ?>
                            <?php
                            $file_product = trim(
                                (string) (
                                    $file['product_type']
                                    ?? $file['product']
                                    ?? ''
                                )
                            );

                            $file_item_number = (int) (
                                $file['item_number']
                                ?? $file['entry_number']
                                ?? 0
                            );

                            if (
                                $file_product !== $item['product']
                                || $file_item_number
                                    !== (int) $item['item_number']
                            ) {
                                continue;
                            }

                            $file_path = trim(
                                (string) ($file['path'] ?? '')
                            );

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

                            $file_position = trim(
                                (string) (
                                    $file['position']
                                    ?? $file['image_position']
                                    ?? 'Reference'
                                )
                            );

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

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

                            $file_url = sparrow_url($file_path);
                            ?>

                            <div class="request-reference">
                                <strong>
                                    <?= sparrow_escape(
                                        ucfirst($file_position)
                                    ) ?>
                                    Reference
                                </strong>

                                <?php if ($is_image): ?>
                                    <a
                                        href="<?= sparrow_escape(
                                            $file_url
                                        ) ?>"
                                        target="_blank"
                                        rel="noopener"
                                    >
                                        <img
                                            class="order-request-image"
                                            src="<?= sparrow_escape(
                                                $file_url
                                            ) ?>"
                                            alt="<?= sparrow_escape(
                                                $item['product']
                                                . ' Entry #'
                                                . $item['item_number']
                                                . ' '
                                                . $file_position
                                                . ' reference'
                                            ) ?>"
                                        >
                                    </a>
                                <?php else: ?>
                                    <a
                                        class="button button-secondary"
                                        href="<?= sparrow_escape(
                                            $file_url
                                        ) ?>"
                                        target="_blank"
                                        rel="noopener"
                                    >
                                        Open Reference File
                                    </a>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
<?php elseif (!empty($request['message'])): ?>
    <div class="form-section">
        <strong>Order Details:</strong>

        <p class="muted">
            <?= nl2br(
                sparrow_escape($request['message'])
            ) ?>
        </p>
    </div>
<?php endif; ?>

<?php
$group_name = trim(
    (string) ($raw_form_data['group_name'] ?? '')
);

$order_notes = trim(
    (string) ($raw_form_data['order_notes'] ?? '')
);
?>

<?php if ($group_name !== '' || $order_notes !== ''): ?>
    <div class="form-section">
        <?php if ($group_name !== ''): ?>
            <p>
                <strong>Group Name:</strong><br>
                <?= sparrow_escape($group_name) ?>
            </p>
        <?php endif; ?>

        <?php if ($order_notes !== ''): ?>
            <p>
                <strong>Full Order Notes:</strong><br>
                <?= nl2br(sparrow_escape($order_notes)) ?>
            </p>
        <?php endif; ?>
    </div>
<?php endif; ?>

            <?php $form_id = 'order_request_form_' . (int) $request['id']; ?>

<form method="post" id="<?php echo $form_id; ?>" class="order-request-admin-form">
                <input type="hidden" name="action" value="update_request">
                <input type="hidden" name="request_id" value="<?php echo (int) $request['id']; ?>">

                <div class="form-grid">
                    <div>
                        <label for="status_<?php echo (int) $request['id']; ?>">Status</label>
                        <select id="status_<?php echo (int) $request['id']; ?>" name="status">
                            <?php foreach ($statuses as $status): ?>
                                <option
                                    value="<?php echo sparrow_escape($status); ?>"
                                    <?php echo ($request['status'] === $status) ? 'selected' : ''; ?>
                                >
                                    <?php echo sparrow_escape($status); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
				
				<div class="form-grid">
    <div>
        <label for="quote_amount_<?php echo (int) $request['id']; ?>">Quote Amount</label>
        <input
            type="number"
            step="0.01"
            min="0"
            id="quote_amount_<?php echo (int) $request['id']; ?>"
            name="quote_amount"
            value="<?php echo sparrow_escape(number_format((float) ($request['quote_amount'] ?? 0), 2, '.', '')); ?>"
        >
    </div>
</div>

<div class="form-section">
    <label for="quote_notes_<?php echo (int) $request['id']; ?>">Quote Notes</label>
    <textarea
        id="quote_notes_<?php echo (int) $request['id']; ?>"
        name="quote_notes"
        rows="3"
        placeholder="Internal quote notes, supplies, pricing details, etc."
    ><?php echo sparrow_escape($request['quote_notes'] ?? ''); ?></textarea>
</div>

<div class="form-section">
    <label for="customer_message_<?php echo (int) $request['id']; ?>">Customer Message</label>
    <textarea
        id="customer_message_<?php echo (int) $request['id']; ?>"
        name="customer_message"
        rows="3"
        placeholder="Message to send later when email is added..."
    ><?php echo sparrow_escape($request['customer_message'] ?? ''); ?></textarea>
</div>

                <div class="form-section">
                    <label for="admin_notes_<?php echo (int) $request['id']; ?>">Admin Notes</label>
                    <textarea
                        id="admin_notes_<?php echo (int) $request['id']; ?>"
                        name="admin_notes"
                        rows="3"
                    ><?php echo sparrow_escape($request['admin_notes'] ?? ''); ?></textarea>
                </div>
            </form>
<div class="form-actions order-request-action-row">
    <button
        type="submit"
        class="button"
        form="<?php echo $form_id; ?>"
    >
        Save Request
    </button>

    <?php if (!empty($request['converted_order_id'])): ?>
        <a
            class="button button-secondary"
            href="<?php echo sparrow_escape(sparrow_url('/backyard/order-view.php?id=' . (int) $request['converted_order_id'])); ?>"
        >
            View Order
        </a>
    <?php else: ?>

        <form
            method="post"
            action="<?php echo sparrow_escape(sparrow_url('/backyard/order-request-convert.php')); ?>"
            class="order-request-inline-form"
            onsubmit="return confirm('Convert this request into a Backyard order?');"
        >
            <input type="hidden" name="request_id" value="<?php echo (int) $request['id']; ?>">

            <button type="submit" class="button button-secondary">
                Convert to Order
            </button>
        </form>
    <?php endif; ?>

    <form
        method="post"
        class="order-request-delete-form"
        onsubmit="return confirm('Delete this order request? This cannot be undone.');"
    >
        <input type="hidden" name="action" value="delete_request">
        <input type="hidden" name="request_id" value="<?php echo (int) $request['id']; ?>">

        <button type="submit" class="button button-danger">
            Delete Request
        </button>
    </form>
</div>
        </section>
    <?php endforeach; ?>
<?php endif; ?>

<?php if (!$active_requests && $converted_requests): ?>
    <section class="card">
        <p class="muted">
            No new or active public order requests right now. Converted requests are tucked away below.
        </p>
    </section>
<?php endif; ?>

<?php if ($converted_requests): ?>
    <section class="card converted-requests-card">
        <details>
            <summary class="converted-requests-summary">
                Converted Requests
                <span><?php echo count($converted_requests); ?></span>
            </summary>

            <div class="converted-requests-list">
                <table class="converted-requests-table">
                    <thead>
                        <tr>
                            <th>Submitted</th>
                            <th>Customer</th>
                            <th>Order Type</th>
                            <th>Quantity</th>
                            <th>Converted</th>
                            <th>Order</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php foreach ($converted_requests as $request): ?>
                            <tr>
                                <td>
                                    <?php echo sparrow_escape(date('M j, Y', strtotime($request['created_at']))); ?>
                                </td>

                                <td>
                                    <strong><?php echo sparrow_escape($request['customer_name']); ?></strong>

                                    <div class="muted converted-small-text">
                                        <?php echo sparrow_escape($request['customer_email'] ?: $request['customer_phone'] ?: ''); ?>
                                    </div>
                                </td>

                                <td>
                                    <?php echo sparrow_escape($request['order_type'] ?: ''); ?>
                                </td>

                                <td>
                                    <?php echo sparrow_escape($request['quantity'] ?: ''); ?>
                                </td>

                                <td>
                                    <?php if (!empty($request['converted_at'])): ?>
                                        <?php echo sparrow_escape(date('M j, Y', strtotime($request['converted_at']))); ?>
                                    <?php else: ?>
                                        Converted
                                    <?php endif; ?>
                                </td>

                                <td>
                                    <div class="converted-actions">
                                        <?php if (!empty($request['converted_order_id'])): ?>
                                            <a
                                                class="button button-secondary"
                                                href="<?php echo sparrow_escape(sparrow_url('/backyard/order-view.php?id=' . (int) $request['converted_order_id'])); ?>"
                                            >
                                                View Order
                                            </a>
                                        <?php endif; ?>

                                        <form
                                            method="post"
                                            class="order-request-delete-form"
                                            onsubmit="return confirm('Delete this converted request? This cannot be undone.');"
                                        >
                                            <input type="hidden" name="action" value="delete_request">
                                            <input type="hidden" name="request_id" value="<?php echo (int) $request['id']; ?>">

                                            <button type="submit" class="button button-danger">
                                                Delete
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </details>
    </section>
<?php endif; ?>

<?php sparrow_backyard_footer(); ?>