<?php

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

$notice = '';
$error = '';
$values = [];

function sparrow_public_order_store_uploaded_file(string $tmp_name, string $original_name): ?string
{
    if ($tmp_name === '' || $original_name === '') {
        return null;
    }

    if (!is_uploaded_file($tmp_name)) {
        return null;
    }

    $upload_dir = __DIR__ . '/storage/order-requests/';

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

    if (($size = filesize($tmp_name)) === false || $size < 1 || $size > 10 * 1024 * 1024) {
        return null;
    }

    $allowed_mimes = [
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/gif' => 'gif',
        'image/webp' => 'webp',
        'application/pdf' => 'pdf',
    ];
    $detected_mime = (new finfo(FILEINFO_MIME_TYPE))->file($tmp_name);
    $ext = $allowed_mimes[$detected_mime] ?? '';
    if ($ext === '') {
        return null;
    }

    $file_name = 'order-request-' . time() . '-' . bin2hex(random_bytes(4)) . '.' . $ext;
    $destination = $upload_dir . $file_name;

    if (!move_uploaded_file($tmp_name, $destination)) {
        return null;
    }

    return '/storage/order-requests/' . $file_name;
}

function sparrow_public_order_collect_uploads(
    string $field_name,
    string $product_label,
    string $position_label
): array {
    $saved = [];

    if (
        empty($_FILES[$field_name]['name'])
        || !is_array($_FILES[$field_name]['name'])
    ) {
        return $saved;
    }

    foreach (
        $_FILES[$field_name]['name']
        as $index => $original_name
    ) {
        if (empty($original_name)) {
            continue;
        }

        $tmp_name =
            $_FILES[$field_name]['tmp_name'][$index] ?? '';

        $error_code =
            $_FILES[$field_name]['error'][$index]
            ?? UPLOAD_ERR_NO_FILE;

        if ($error_code !== UPLOAD_ERR_OK) {
            continue;
        }

        $path = sparrow_public_order_store_uploaded_file(
            $tmp_name,
            $original_name
        );

        if ($path) {
            $item_number = $index + 1;

            $saved[] = [
                'field' => $field_name,
                'product_type' => $product_label,
                'item_index' => $index,
                'item_number' => $item_number,
                'position' => $position_label,
                'label' => $product_label
                    . ' Entry #'
                    . $item_number
                    . ' — '
                    . $position_label,
                'original_name' => $original_name,
                'path' => $path,
            ];
        }
    }

    return $saved;
}

function sparrow_public_order_array_value(array $array, int $index): string
{
    return trim((string)($array[$index] ?? ''));
}

function sparrow_public_order_build_quantity_summary(array $post): string
{
    $product_type = trim($post['product_type'] ?? '');

    if ($product_type === 'Shirt') {
        $quantities = $post['shirt_quantity'] ?? [];
        $total = 0;

        foreach ($quantities as $qty) {
            $total += (int) $qty;
        }

        return $total > 0 ? $total . ' shirt(s)' : '';
    }

    if ($product_type === 'Koozie') {
        $quantities = $post['koozie_quantity'] ?? [];
        $total = 0;

        foreach ($quantities as $qty) {
            $total += (int) $qty;
        }

        return $total > 0 ? $total . ' koozie(s)' : '';
    }

    return '';
}

function sparrow_public_order_build_message(array $post, array $uploaded_files): string
{
    $lines = [];

$group_name = trim($post['group_name'] ?? '');

if ($group_name !== '') {
    $lines[] = 'Group Name: ' . $group_name;
    $lines[] = '';
}

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

        $lines[] = 'SHIRT DETAILS';

        foreach ($sizes as $index => $size) {
            $qty = sparrow_public_order_array_value($quantities, $index);
            $specialty = sparrow_public_order_array_value($specialties, $index);
            $color = sparrow_public_order_array_value($colors, $index);
            $placement = sparrow_public_order_array_value($placements, $index);
            $note = sparrow_public_order_array_value($notes, $index);

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

            $lines[] = 'Size Entry #' . ($index + 1);
            $lines[] = '- Size: ' . $size;
            $lines[] = '- Quantity: ' . $qty;
            $lines[] = '- Specialty: ' . $specialty;
            $lines[] = '- Color: ' . $color;
            $lines[] = '- Placement: ' . $placement;

            if ($note !== '') {
                $lines[] = '- Notes: ' . $note;
            }

            $lines[] = '';
        }
    }

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

        $lines[] = 'KOOZIE DETAILS';

        foreach ($quantities as $index => $qty) {
            $qty = trim((string) $qty);
            $color = sparrow_public_order_array_value($colors, $index);
            $note = sparrow_public_order_array_value($notes, $index);

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

            $lines[] = 'Koozie Entry #' . ($index + 1);
            $lines[] = '- Quantity: ' . $qty;
            $lines[] = '- Color: ' . $color;

            if ($note !== '') {
                $lines[] = '- Notes: ' . $note;
            }

            $lines[] = '';
        }
    }

    $order_notes = trim($post['order_notes'] ?? '');

    if ($order_notes !== '') {
        $lines[] = 'FULL ORDER NOTES';
        $lines[] = $order_notes;
        $lines[] = '';
    }

    if ($uploaded_files) {
        $lines[] = 'UPLOADED FILES';

        foreach ($uploaded_files as $file) {
            $lines[] =
    '- '
    . ($file['label'] ?? 'Uploaded File')
    . ': '
    . ($file['original_name'] ?? 'Upload')
    . ' — '
    . ($file['path'] ?? '');
        }

        $lines[] = '';
    }

    $lines[] = 'Agreement Checked: ' . (!empty($post['agreement_checked']) ? 'Yes' : 'No');

    return trim(implode("\n", $lines));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $values = $_POST;

    try {
		        $product_type = trim($_POST['product_type'] ?? '');

        if ($product_type === 'Shirt') {
            $has_quantity = false;

            foreach (($_POST['shirt_quantity'] ?? []) as $quantity) {
                if ((int) $quantity > 0) {
                    $has_quantity = true;
                    break;
                }
            }

            if (!$has_quantity) {
                throw new InvalidArgumentException('Please enter at least one shirt quantity.');
            }
        } elseif ($product_type === 'Koozie') {
            $has_quantity = false;

            foreach (($_POST['koozie_quantity'] ?? []) as $quantity) {
                if ((int) $quantity > 0) {
                    $has_quantity = true;
                    break;
                }
            }

            if (!$has_quantity) {
                throw new InvalidArgumentException('Please enter at least one koozie quantity.');
            }
        } else {
            throw new InvalidArgumentException('Please choose a product type.');
        }
		
        $uploaded_files = [];

$upload_fields = [
    [
        'field' => 'shirt_upload_front',
        'product' => 'Shirt',
        'position' => 'Front',
    ],
    [
        'field' => 'shirt_upload_back',
        'product' => 'Shirt',
        'position' => 'Back',
    ],
    [
        'field' => 'shirt_upload_chest',
        'product' => 'Shirt',
        'position' => 'Chest',
    ],
    [
        'field' => 'shirt_upload_sleeve',
        'product' => 'Shirt',
        'position' => 'Sleeve',
    ],
    [
        'field' => 'shirt_upload_other',
        'product' => 'Shirt',
        'position' => 'Other',
    ],
    [
        'field' => 'koozie_upload_front',
        'product' => 'Koozie',
        'position' => 'Front',
    ],
    [
        'field' => 'koozie_upload_back',
        'product' => 'Koozie',
        'position' => 'Back',
    ],
];

foreach ($upload_fields as $upload_field) {
    $uploaded_files = array_merge(
        $uploaded_files,
        sparrow_public_order_collect_uploads(
            $upload_field['field'],
            $upload_field['product'],
            $upload_field['position']
        )
    );
}

        $first_image_path = '';

        foreach ($uploaded_files as $file) {
            $path = $file['path'] ?? '';

            if ($path !== '') {
                $first_image_path = $path;
                break;
            }
        }

        $message = sparrow_public_order_build_message($_POST, $uploaded_files);
        $quantity_summary = sparrow_public_order_build_quantity_summary($_POST);

        $raw_form_data = $_POST;
        unset($raw_form_data['agreement_checked']);

        sparrow_save_public_order_request([
            'customer_name' => $_POST['customer_name'] ?? '',
            'customer_email' => $_POST['customer_email'] ?? '',
            'customer_phone' => $_POST['customer_phone'] ?? '',
            'preferred_contact' => $_POST['preferred_contact'] ?? '',
            'order_type' => $_POST['product_type'] ?? '',
            'quantity' => $quantity_summary,
            'needed_by' => $_POST['needed_by'] ?? '',
            'message' => $message,
            'inspiration_image_path' => $first_image_path,
            'uploaded_files' => json_encode($uploaded_files, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'raw_form_data' => json_encode($raw_form_data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        ]);

        $notice = 'Thank you! Your order request has been sent. I will review it and get back with you before anything is confirmed.';
        $values = [];
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

$order_css = <<<'CSS'
.public-order-wrapper {
    max-width: 960px;
    margin: 0 auto;
}

.public-order-notice,
.public-order-error {
    max-width: 960px;
    margin: 0 auto 16px;
    border-radius: 18px;
    padding: 14px 16px;
    font-weight: bold;
}

.public-order-notice {
    border: 1px solid #b9dfc3;
    background: #f0fff4;
    color: #276738;
}

.public-order-error {
    border: 1px solid #e8b6c0;
    background: #fff4f6;
    color: #9d3146;
}

.public-order-note {
    max-width: 960px;
    margin: 0 auto 18px;
    color: var(--sparrow-muted);
    line-height: 1.5;
}

.public-order-wrapper .sparrow-order-form {
    max-width: 100%;
}

.public-order-wrapper .sparrow-form-card {
    box-shadow: 0 8px 30px rgba(70, 35, 60, 0.04);
}
CSS;

sparrow_public_header('Order Request', 'order', $order_css);

?>

<section class="public-card public-hero">
    <h1>Request a Custom Order</h1>
    <p>
        Fill out the details below, and I’ll review your request before confirming price, timing, and availability.
    </p>
</section>

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

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

<p class="public-order-note">
    This form sends a request only. Your order is not confirmed until I review the details and reply.
</p>

<section class="public-order-wrapper">
    <form
        method="post"
        action="<?php echo sparrow_escape(sparrow_url('/order.php')); ?>"
        enctype="multipart/form-data"
        class="sparrow-order-form"
    >
        <?php
        $is_admin = false;
        $values = $values ?? [];

        require __DIR__ . '/app/order-form.php';
        ?>
    </form>
</section>

<?php sparrow_public_footer(); ?>
