<?php

declare(strict_types=1);

require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/orders.php';
require_once __DIR__ . '/../app/supplier-splitter.php';

$user = sparrow_require_backyard_login();

$error = '';
$preview = null;
$file_name = '';

function supplier_import_e($value): string
{
    return htmlspecialchars(
        (string) ($value ?? ''),
        ENT_QUOTES,
        'UTF-8'
    );
}

function supplier_import_money($value): string
{
    return '$' . number_format(
        (float) ($value ?? 0),
        2
    );
}

function supplier_import_extract_json(
    string $contents
): array {
    $contents = trim($contents);

    if ($contents === '') {
        throw new RuntimeException(
            'The uploaded file is empty.'
        );
    }

    /*
     * First try normal JSON.
     */
    $decoded = json_decode($contents, true);

    if (
        json_last_error() === JSON_ERROR_NONE
        && is_array($decoded)
    ) {
        return $decoded;
    }

    /*
     * WordPress may have placed HTML before the JSON export.
     * Find the export object beginning with export_type.
     */
    $marker = '"export_type"';
    $marker_position = strpos($contents, $marker);

    if ($marker_position === false) {
        throw new RuntimeException(
            'The Supplier Splitter JSON data could not be found.'
        );
    }

    $json_start = strrpos(
        substr($contents, 0, $marker_position),
        '{'
    );

    if ($json_start === false) {
        throw new RuntimeException(
            'The start of the Supplier Splitter JSON could not be found.'
        );
    }

    $json_contents = substr($contents, $json_start);

    $decoded = json_decode($json_contents, true);

    if (
        json_last_error() !== JSON_ERROR_NONE
        || !is_array($decoded)
    ) {
        throw new RuntimeException(
            'The Supplier Splitter export could not be decoded: '
            . json_last_error_msg()
        );
    }

    return $decoded;
}

if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    && ($_POST['action'] ?? '') ===
        'import_supplier_receipts'
) {
    try {
        $confirmation = trim(
            (string) ($_POST['import_confirmation'] ?? '')
        );

        if ($confirmation !== 'IMPORT') {
            throw new RuntimeException(
                'Type IMPORT in all caps to confirm.'
            );
        }

        $import_data =
            $_SESSION['sparrow_supplier_import_data']
            ?? null;

        if (!is_array($import_data)) {
            throw new RuntimeException(
                'The import preview expired. Upload the file again.'
            );
        }

        $result =
            sparrow_supplier_import_wordpress_export(
                $import_data
            );

        unset(
            $_SESSION['sparrow_supplier_import_data']
        );

        $_SESSION['sparrow_import_notice'] =
            $result['receipts_imported']
            . ' supplier receipt(s) imported, '
            . $result['receipts_skipped']
            . ' duplicate receipt(s) skipped, '
            . $result['items_imported']
            . ' item row(s) imported, '
            . $result['applications_imported']
            . ' applied group(s) restored, and '
            . $result['applications_skipped']
            . ' applied group(s) skipped.';

        header(
            'Location: '
            . sparrow_url('/backyard/import.php')
        );
        exit;
    } catch (Throwable $e) {
        $error =
            'Supplier receipt import failed: '
            . $e->getMessage();
    }
}

if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    && ($_POST['action'] ?? '') !==
        'import_supplier_receipts'
) {
    try {
        if (
            empty($_FILES['supplier_json'])
            || (
                $_FILES['supplier_json']['error']
                ?? UPLOAD_ERR_NO_FILE
            ) !== UPLOAD_ERR_OK
        ) {
            throw new RuntimeException(
                'Please choose the Supplier Splitter export file.'
            );
        }

        $uploaded_file = $_FILES['supplier_json'];

        $file_name = basename(
            (string) ($uploaded_file['name'] ?? '')
        );

        $file_size = (int) (
            $uploaded_file['size'] ?? 0
        );

        if ($file_size <= 0) {
            throw new RuntimeException(
                'The uploaded file is empty.'
            );
        }

        if ($file_size > 5 * 1024 * 1024) {
            throw new RuntimeException(
                'The uploaded file is larger than 5 MB.'
            );
        }

        $contents = file_get_contents(
            (string) $uploaded_file['tmp_name']
        );

        if ($contents === false) {
            throw new RuntimeException(
                'The uploaded file could not be read.'
            );
        }

        $data = supplier_import_extract_json(
            $contents
        );

        if (
            ($data['export_type'] ?? '')
            !== 'sparrow_supplier_splitter'
        ) {
            throw new RuntimeException(
                'This is not a Sparrow Supplier Splitter export.'
            );
        }

        $drafts = $data['drafts'] ?? [];
        $adjustments = $data['adjustments'] ?? [];

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

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

        $summary = [
            'receipt_count' => count($drafts),
            'adjustment_count' => count($adjustments),
            'item_count' => 0,
            'applied_group_count' => 0,
            'subtotal_total' => 0.00,
            'shipping_total' => 0.00,
            'tax_total' => 0.00,
            'discount_total' => 0.00,
        ];

        foreach ($drafts as $draft) {
            if (!is_array($draft)) {
                continue;
            }

            $items = $draft['items'] ?? [];
            $applied_groups =
                $draft['applied_groups'] ?? [];

            if (is_array($items)) {
                $summary['item_count'] +=
                    count($items);
            }

            if (is_array($applied_groups)) {
                $summary['applied_group_count'] +=
                    count($applied_groups);
            }

            $summary['subtotal_total'] +=
                (float) ($draft['subtotal'] ?? 0);

            $summary['shipping_total'] +=
                (float) ($draft['shipping'] ?? 0);

            $summary['tax_total'] +=
                (float) ($draft['tax'] ?? 0);

            $summary['discount_total'] +=
                (float) ($draft['discount'] ?? 0);
        }
		
		$_SESSION['sparrow_supplier_import_data'] = $data;

        $preview = [
            'meta' => [
                'exported_at' =>
                    $data['exported_at'] ?? '',
                'site_url' =>
                    $data['site_url'] ?? '',
                'export_version' =>
                    $data['export_version'] ?? '',
            ],
            'drafts' => $drafts,
            'adjustments' => $adjustments,
            'summary' => $summary,
        ];
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

sparrow_backyard_header(
    'Preview Supplier Receipt Import'
);

?>

<?php if ($error !== ''): ?>
    <div class="notice-error">
        <?= supplier_import_e($error) ?>
    </div>
<?php endif; ?>

<section class="card">
    <h1>Preview Supplier Receipt Import</h1>

    <p class="muted">
        Review the old WordPress Supplier Splitter data.
        Nothing on this page imports or changes any records.
    </p>

    <a
        class="button button-secondary"
        href="<?= supplier_import_e(
            sparrow_url('/backyard/import.php')
        ) ?>"
    >
        Back to Imports
    </a>
</section>

<?php if ($preview): ?>
    <section class="card">
        <h2>Export Summary</h2>

        <div class="supplier-preview-summary">
            <div>
                <span>Receipts</span>
                <strong>
                    <?= number_format(
                        (int) $preview['summary'][
                            'receipt_count'
                        ]
                    ) ?>
                </strong>
            </div>

            <div>
                <span>Item Rows</span>
                <strong>
                    <?= number_format(
                        (int) $preview['summary'][
                            'item_count'
                        ]
                    ) ?>
                </strong>
            </div>

            <div>
                <span>Applied Groups</span>
                <strong>
                    <?= number_format(
                        (int) $preview['summary'][
                            'applied_group_count'
                        ]
                    ) ?>
                </strong>
            </div>

            <div>
                <span>Adjustments</span>
                <strong>
                    <?= number_format(
                        (int) $preview['summary'][
                            'adjustment_count'
                        ]
                    ) ?>
                </strong>
            </div>
        </div>

        <p>
            <strong>File:</strong>
            <?= supplier_import_e($file_name) ?>
        </p>

        <p>
            <strong>Exported:</strong>
            <?= supplier_import_e(
                $preview['meta']['exported_at']
            ) ?>
        </p>

        <p>
            <strong>Source:</strong>
            <?= supplier_import_e(
                $preview['meta']['site_url']
            ) ?>
        </p>
    </section>

    <section class="card">
        <h2>Receipt Preview</h2>

        <?php if (!$preview['drafts']): ?>
            <p class="muted">
                No supplier receipts were found.
            </p>
        <?php else: ?>
            <div class="table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th>Supplier</th>
                            <th>Receipt #</th>
                            <th>Date</th>
                            <th>Status</th>
                            <th>Items</th>
                            <th>Subtotal</th>
                            <th>Shipping</th>
                            <th>Tax</th>
                            <th>Discount</th>
                            <th>Applied Groups</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php foreach (
                            $preview['drafts'] as $draft
                        ): ?>
                            <?php
                            if (!is_array($draft)) {
                                continue;
                            }

                            $items = is_array(
                                $draft['items'] ?? null
                            )
                                ? $draft['items']
                                : [];

                            $applied_groups = is_array(
                                $draft['applied_groups']
                                ?? null
                            )
                                ? $draft['applied_groups']
                                : [];
                            ?>

                            <tr>
                                <td>
                                    <?= supplier_import_e(
                                        $draft[
                                            'supplier_name'
                                        ] ?? ''
                                    ) ?>
                                </td>

                                <td>
                                    <?= supplier_import_e(
                                        $draft[
                                            'receipt_number'
                                        ] ?? ''
                                    ) ?>
                                </td>

                                <td>
                                    <?= supplier_import_e(
                                        $draft[
                                            'order_date'
                                        ] ?? ''
                                    ) ?>
                                </td>

                                <td>
                                    <?= supplier_import_e(
                                        $draft['status']
                                        ?? ''
                                    ) ?>
                                </td>

                                <td>
                                    <?= number_format(
                                        count($items)
                                    ) ?>
                                </td>

                                <td>
                                    <?= supplier_import_money(
                                        $draft['subtotal']
                                        ?? 0
                                    ) ?>
                                </td>

                                <td>
                                    <?= supplier_import_money(
                                        $draft['shipping']
                                        ?? 0
                                    ) ?>
                                </td>

                                <td>
                                    <?= supplier_import_money(
                                        $draft['tax']
                                        ?? 0
                                    ) ?>
                                </td>

                                <td>
                                    <?= supplier_import_money(
                                        $draft['discount']
                                        ?? 0
                                    ) ?>
                                </td>

                                <td>
                                    <?php if ($applied_groups): ?>
                                        <?= supplier_import_e(
                                            implode(
                                                ', ',
                                                array_keys(
                                                    $applied_groups
                                                )
                                            )
                                        ) ?>
                                    <?php else: ?>
                                        <span class="muted">
                                            None
                                        </span>
                                    <?php endif; ?>
                                </td>
                            </tr>

                            <?php if ($items): ?>
                                <tr>
                                    <td></td>

                                    <td colspan="9">
                                        <div class="supplier-mini-items">
                                            <strong>Items:</strong>

                                            <ul>
                                                <?php foreach (
                                                    $items as $item
                                                ): ?>
                                                    <?php if (
                                                        is_array($item)
                                                    ): ?>
                                                        <li>
                                                            <?= supplier_import_e(
                                                                $item[
                                                                    'type'
                                                                ] ?? ''
                                                            ) ?>
                                                            —
                                                            <?= supplier_import_e(
                                                                $item[
                                                                    'label'
                                                                ] ?? ''
                                                            ) ?>
                                                            —
                                                            <?= supplier_import_e(
                                                                $item[
                                                                    'description'
                                                                ] ?? ''
                                                            ) ?>
                                                            —
                                                            <?= supplier_import_money(
                                                                $item[
                                                                    'amount'
                                                                ] ?? 0
                                                            ) ?>
                                                        </li>
                                                    <?php endif; ?>
                                                <?php endforeach; ?>
                                            </ul>
                                        </div>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>

        <div class="notice-success" style="margin-top: 16px;">
            Preview only. No supplier receipts were imported.
        </div>
		
		<form
    method="post"
    style="margin-top: 18px;"
    onsubmit="return confirm(
        'Import these receipts and restore the saved WordPress supplier costs to matching Backyard orders?'
    );"
>
    <input
        type="hidden"
        name="action"
        value="import_supplier_receipts"
    >

    <div style="max-width: 420px;">
        <label for="import_confirmation">
            Type IMPORT to confirm
        </label>

        <input
            type="text"
            id="import_confirmation"
            name="import_confirmation"
            autocomplete="off"
            placeholder="IMPORT"
            required
        >
    </div>

    <p class="muted">
        Applied WordPress groups will restore supplier items,
        shipping, tax, and supplier discounts. Old travel costs
        will remain $0.00.
    </p>

    <button type="submit" class="button">
        Import Supplier Receipts
    </button>
</form>
    </section>
<?php endif; ?>

<?php sparrow_backyard_footer(); ?>