<?php
// public/backyard/order-save.php

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

$user = sparrow_require_backyard_login();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header(
        'Location: '
        . sparrow_url('/backyard/order-new.php')
    );
    exit;
}

function sparrow_store_order_reference_file(
    int $order_id,
    string $field_name,
    string $product_type,
    string $image_position
): void {
    if (
        empty($_FILES[$field_name]['name'])
        || !is_array($_FILES[$field_name]['name'])
    ) {
        return;
    }

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

    $upload_dir =
        __DIR__
        . '/../storage/order-references/order-'
        . $order_id
        . '/';

    foreach (
        $_FILES[$field_name]['name']
        as $index => $original_name
    ) {
        $original_name = trim((string) $original_name);

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

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

        if ($error_code === UPLOAD_ERR_NO_FILE) {
            continue;
        }

        if ($error_code !== UPLOAD_ERR_OK) {
            throw new RuntimeException(
                'A reference file could not be uploaded.'
            );
        }

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

        if (
            $tmp_name === ''
            || !is_uploaded_file($tmp_name)
        ) {
            throw new RuntimeException(
                'The uploaded reference file is invalid.'
            );
        }

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

        if (
            !in_array(
                $extension,
                $allowed_extensions,
                true
            )
        ) {
            throw new RuntimeException(
                'Reference files must be JPG, PNG, GIF, '
                . 'WEBP, or PDF.'
            );
        }

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

        $item_number = ((int) $index) + 1;

        $file_name =
            'reference-order-'
            . $order_id
            . '-'
            . strtolower($product_type)
            . '-'
            . $item_number
            . '-'
            . strtolower($image_position)
            . '-'
            . time()
            . '-'
            . bin2hex(random_bytes(4))
            . '.'
            . $extension;

        $destination = $upload_dir . $file_name;

        if (
            !move_uploaded_file(
                $tmp_name,
                $destination
            )
        ) {
            throw new RuntimeException(
                'The reference file could not be saved.'
            );
        }

        $image_path =
            '/storage/order-references/order-'
            . $order_id
            . '/'
            . $file_name;

        try {
            sparrow_save_order_reference_image(
                $order_id,
                $product_type,
                $item_number,
                $image_position,
                $original_name,
                $image_path
            );
        } catch (Throwable $exception) {
            if (is_file($destination)) {
                unlink($destination);
            }

            throw $exception;
        }
    }
}

$order_id = 0;

try {
    $data = sparrow_build_order_data_from_post(
        $_POST,
        true
    );

    $order_id = sparrow_create_order($data);

    $reference_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 ($reference_fields as $reference_field) {
        sparrow_store_order_reference_file(
            $order_id,
            $reference_field['field'],
            $reference_field['product'],
            $reference_field['position']
        );
    }

    header(
        'Location: '
        . sparrow_url(
            '/backyard/order-view.php?id='
            . $order_id
            . '&notice=created'
        )
    );
    exit;
} catch (Throwable $exception) {
    error_log(
        'Sparrow order save failed: '
        . $exception->getMessage()
    );

    if ($order_id > 0) {
        header(
            'Location: '
            . sparrow_url(
                '/backyard/order-view.php?id='
                . $order_id
                . '&notice=created'
                . '&reference_error=1'
            )
        );
        exit;
    }

    header(
        'Location: '
        . sparrow_url('/backyard/order-new.php?error=1')
    );
    exit;
}