<?php

require_once __DIR__ . '/db.php';

function sparrow_public_order_statuses(): array
{
    return ['New', 'Reviewing', 'Quoted', 'Accepted', 'Declined', 'Converted'];
}

function sparrow_public_order_normalize_status(string $status): string
{
    $allowed = sparrow_public_order_statuses();

    return in_array($status, $allowed, true) ? $status : 'New';
}

function sparrow_save_public_order_request(array $data): int
{
    $pdo = sparrow_db();

    $customer_name = trim($data['customer_name'] ?? '');
    $customer_email = trim($data['customer_email'] ?? '');
    $customer_phone = trim($data['customer_phone'] ?? '');
    $preferred_contact = trim($data['preferred_contact'] ?? '');
    $order_type = trim($data['order_type'] ?? '');
    $quantity = trim($data['quantity'] ?? '');
    $needed_by = trim($data['needed_by'] ?? '');
    $message = trim($data['message'] ?? '');
    $inspiration_image_path = trim($data['inspiration_image_path'] ?? '');
    $uploaded_files = trim($data['uploaded_files'] ?? '');
    $raw_form_data = trim($data['raw_form_data'] ?? '');

    if ($customer_name === '') {
        throw new InvalidArgumentException('Name is required.');
    }

    if ($customer_email === '' && $customer_phone === '') {
        throw new InvalidArgumentException('Please enter either an email or phone number.');
    }

    $needed_by = $needed_by !== '' ? $needed_by : null;

    $stmt = $pdo->prepare("
        INSERT INTO public_order_requests (
            customer_name,
            customer_email,
            customer_phone,
            preferred_contact,
            order_type,
            quantity,
            needed_by,
            message,
            inspiration_image_path,
            uploaded_files,
            raw_form_data,
            status
        ) VALUES (
            :customer_name,
            :customer_email,
            :customer_phone,
            :preferred_contact,
            :order_type,
            :quantity,
            :needed_by,
            :message,
            :inspiration_image_path,
            :uploaded_files,
            :raw_form_data,
            'New'
        )
    ");

    $stmt->execute([
        ':customer_name' => $customer_name,
        ':customer_email' => $customer_email,
        ':customer_phone' => $customer_phone,
        ':preferred_contact' => $preferred_contact,
        ':order_type' => $order_type,
        ':quantity' => $quantity,
        ':needed_by' => $needed_by,
        ':message' => $message,
        ':inspiration_image_path' => $inspiration_image_path,
        ':uploaded_files' => $uploaded_files !== '' ? $uploaded_files : null,
        ':raw_form_data' => $raw_form_data !== '' ? $raw_form_data : null,
    ]);

    return (int) $pdo->lastInsertId();
}

function sparrow_get_public_order_requests(): array
{
    $pdo = sparrow_db();

    $stmt = $pdo->query("
        SELECT *
        FROM public_order_requests
        ORDER BY created_at DESC, id DESC
    ");

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function sparrow_get_public_order_request(int $id): ?array
{
    $pdo = sparrow_db();

    $stmt = $pdo->prepare("
        SELECT *
        FROM public_order_requests
        WHERE id = :id
        LIMIT 1
    ");

    $stmt->execute([
        ':id' => $id,
    ]);

    $request = $stmt->fetch(PDO::FETCH_ASSOC);

    return $request ?: null;
}

function sparrow_update_public_order_request_admin(
    int $id,
    string $status,
    string $admin_notes,
    float $quote_amount = 0.00,
    string $quote_notes = '',
    string $customer_message = ''
): void {
    $pdo = sparrow_db();

    $status = sparrow_public_order_normalize_status($status);

    $stmt = $pdo->prepare("
        UPDATE public_order_requests
        SET
            status = :status,
            admin_notes = :admin_notes,
            quote_amount = :quote_amount,
            quote_notes = :quote_notes,
            customer_message = :customer_message
        WHERE id = :id
        LIMIT 1
    ");

    $stmt->execute([
        ':status' => $status,
        ':admin_notes' => trim($admin_notes),
        ':quote_amount' => $quote_amount,
        ':quote_notes' => trim($quote_notes),
        ':customer_message' => trim($customer_message),
        ':id' => $id,
    ]);
}

function sparrow_delete_public_order_request(int $id): void
{
    $pdo = sparrow_db();

    $request = sparrow_get_public_order_request($id);

    if (!$request) {
        return;
    }

    $paths_to_delete = [];

    if (!empty($request['inspiration_image_path'])) {
        $paths_to_delete[] = $request['inspiration_image_path'];
    }

    if (!empty($request['uploaded_files'])) {
        $uploaded_files = json_decode($request['uploaded_files'], true);

        if (is_array($uploaded_files)) {
            foreach ($uploaded_files as $file) {
                if (!empty($file['path'])) {
                    $paths_to_delete[] = $file['path'];
                }
            }
        }
    }

    $paths_to_delete = array_unique($paths_to_delete);

    foreach ($paths_to_delete as $path) {
        $path = (string) $path;

        if (strpos($path, '/storage/order-requests/') !== 0) {
            continue;
        }

        $full_path = dirname(__DIR__) . $path;

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

    $stmt = $pdo->prepare("
        DELETE FROM public_order_requests
        WHERE id = :id
        LIMIT 1
    ");

    $stmt->execute([
        ':id' => $id,
    ]);
}

function sparrow_mark_public_order_request_converted(int $request_id, int $order_id): void
{
    $pdo = sparrow_db();

    $request = sparrow_get_public_order_request($request_id);

    if (!$request) {
        return;
    }

    $existing_notes = trim((string) ($request['admin_notes'] ?? ''));

    $conversion_note = 'Converted to Backyard order #' . $order_id . ' on ' . date('M j, Y g:i A') . '.';

    $admin_notes = trim($existing_notes . "\n\n" . $conversion_note);

    $stmt = $pdo->prepare("
        UPDATE public_order_requests
        SET
            status = 'Converted',
            converted_order_id = :converted_order_id,
            converted_at = NOW(),
            admin_notes = :admin_notes
        WHERE id = :id
        LIMIT 1
    ");

    $stmt->execute([
        ':converted_order_id' => $order_id,
        ':admin_notes' => $admin_notes,
        ':id' => $request_id,
    ]);
}