<?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';
require_once __DIR__ . '/../app/orders.php';
require_once __DIR__ . '/../app/settings.php';

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

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

$request_id = (int) ($_POST['request_id'] ?? 0);

if ($request_id <= 0) {
    header('Location: ' . sparrow_url('/backyard/order-requests.php?error=convert'));
    exit;
}

try {
    $request = sparrow_get_public_order_request($request_id);

    if (!$request) {
        throw new RuntimeException('Order request not found.');
    }

    if (!empty($request['converted_order_id'])) {
        header('Location: ' . sparrow_url('/backyard/order-view.php?id=' . (int) $request['converted_order_id']));
        exit;
    }

    $quote_amount = (float) ($request['quote_amount'] ?? 0);

    if ($quote_amount <= 0) {
        header('Location: ' . sparrow_url('/backyard/order-requests.php?error=missing_quote'));
        exit;
    }

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

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

    if (!is_array($raw_form_data) || !$raw_form_data) {
        throw new RuntimeException('This request does not have saved form data to convert.');
    }

    $default_order_status = trim(
        sparrow_get_setting_value($pdo, 'default_order_status', 'Order Received')
    );

    if ($default_order_status === '') {
        $default_order_status = 'Order Received';
    }

    /*
     * This uses the same order builder as the regular Backyard New Order form.
     * true = admin mode, so it does not require the public agreement checkbox.
     * A converted request always starts at the saved default Backyard status.
     */
    $raw_form_data['order_status'] = $default_order_status;
    $data = sparrow_build_order_data_from_post($raw_form_data, true);

    $notes = trim((string) ($data['notes'] ?? ''));
    $quote_notes = trim((string) ($request['quote_notes'] ?? ''));
    $customer_message = trim((string) ($request['customer_message'] ?? ''));

    $converted_note = 'Converted from public order request #' . $request_id . '.';
    $converted_note .= "\nQuote Amount: $" . number_format($quote_amount, 2);

    if ($quote_notes !== '') {
        $converted_note .= "\n\nQuote Notes:\n" . $quote_notes;
    }

    if ($customer_message !== '') {
        $converted_note .= "\n\nCustomer Message:\n" . $customer_message;
    }

    if (!empty($request['needed_by'])) {
        $converted_note .= "\nNeeded By / Event Date: " . date('M j, Y', strtotime($request['needed_by']));
    }

    if (!empty($request['preferred_contact'])) {
        $converted_note .= "\nPreferred Contact: " . $request['preferred_contact'];
    }

    $data['notes'] = trim($notes . "\n\n" . $converted_note);

    $order_id = sparrow_create_order($data);
	
	$reference_error = false;
$site_root = dirname(__DIR__);

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

    if (
        $stored_path === ''
        || !str_starts_with(
            $stored_path,
            '/storage/order-requests/'
        )
    ) {
        continue;
    }

    $source_path = $site_root . $stored_path;

    if (!is_file($source_path)) {
        $reference_error = true;

        error_log(
            'Order request reference file was not found: '
            . $source_path
        );

        continue;
    }

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

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

    $image_position = strtolower(
        trim(
            (string) (
                $file['position']
                ?? $file['image_position']
                ?? 'other'
            )
        )
    );

    $original_name = trim(
        (string) (
            $file['original_name']
            ?? basename($stored_path)
        )
    );

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

    if (
        !in_array(
            $extension,
            ['jpg', 'jpeg', 'png', 'gif', 'webp', 'pdf'],
            true
        )
    ) {
        $reference_error = true;
        continue;
    }

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

    if (
        !is_dir($upload_dir)
        && !mkdir($upload_dir, 0755, true)
        && !is_dir($upload_dir)
    ) {
        $reference_error = true;

        error_log(
            'The converted order reference folder '
            . 'could not be created.'
        );

        continue;
    }

    $safe_product = preg_replace(
        '/[^a-z0-9]+/',
        '-',
        strtolower($product_type)
    );

    $safe_position = preg_replace(
        '/[^a-z0-9]+/',
        '-',
        $image_position
    );

    $file_name =
        'reference-order-'
        . $order_id
        . '-'
        . trim($safe_product, '-')
        . '-'
        . $item_number
        . '-'
        . trim($safe_position, '-')
        . '-'
        . time()
        . '-'
        . bin2hex(random_bytes(4))
        . '.'
        . $extension;

    $destination = $upload_dir . $file_name;

    if (!copy($source_path, $destination)) {
        $reference_error = true;

        error_log(
            'The order request reference could not be copied: '
            . $source_path
        );

        continue;
    }

    $new_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,
            $new_image_path
        );
    } catch (Throwable $exception) {
        $reference_error = true;

        if (is_file($destination)) {
            unlink($destination);
        }

        error_log(
            'Converted order reference could not be recorded: '
            . $exception->getMessage()
        );
    }
}

    /*
     * sparrow_create_order() creates the order and its items, but payment totals
     * are stored through the dedicated payment helper.
     */
    sparrow_update_order_payment($order_id, [
        'total_amount' => $quote_amount,
        'paid_amount' => 0,
        'payment_method' => '',
        'blessing_amount' => 0,
        'order_discount_amount' => 0,
    ]);

    sparrow_mark_public_order_request_converted($request_id, $order_id);

    header('Location: ' . sparrow_url('/backyard/order-view.php?id=' . (int) $order_id . '&notice=converted'));
    exit;
} catch (Throwable $e) {
    echo '<pre style="padding:20px;background:#fff4f6;border:1px solid #e8b6c0;color:#9d3146;">';
    echo htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
    echo '</pre>';
    exit;
}
