<?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();

$notice = '';
$error = '';

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

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

/*
 * Reverse one application.
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'reverse_supplier_application') {
        try {
            $application_id = (int) (
                $_POST['application_id'] ?? 0
            );

            $confirmation = trim(
                (string) (
                    $_POST['reverse_confirmation'] ?? ''
                )
            );

            $reason = trim(
                (string) (
                    $_POST['reversal_reason'] ?? ''
                )
            );

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

            $reverse_result =
                sparrow_supplier_reverse_application(
                    $application_id,
                    $reason
                );

            $query = http_build_query([
                'reversed' => 1,
                'order_number' =>
                    $reverse_result['order_number'] ?? '',
                'reversed_total' =>
                    $reverse_result['reversed_total'] ?? 0,
            ]);

            header(
                'Location: supplier-history.php?'
                . $query
            );
            exit;
        } catch (Throwable $e) {
            $error =
                'Supplier application could not be reversed: '
                . $e->getMessage();
        }
    }
}

if (isset($_GET['reversed'])) {
    $order_number = trim(
        (string) ($_GET['order_number'] ?? '')
    );

    $reversed_total = (float) (
        $_GET['reversed_total'] ?? 0
    );

    $notice =
        'Supplier costs reversed from '
        . $order_number
        . '. Total removed: $'
        . number_format($reversed_total, 2)
        . '.';
}

$applied_history =
    sparrow_supplier_get_applied_history();

$history_summary = [
    'count' => count($applied_history),
    'applied_count' => 0,
    'reversed_count' => 0,
    'order_count' => 0,
    'active_total' => 0.00,
];

$history_orders = [];

foreach ($applied_history as $history_row) {
    $order_number = trim(
        (string) (
            $history_row['order_number'] ?? ''
        )
    );

    if ($order_number !== '') {
        $history_orders[$order_number] = true;
    }

    if (
        ($history_row['status'] ?? '')
        === 'reversed'
    ) {
        $history_summary['reversed_count']++;
    } else {
        $history_summary['applied_count']++;

        $history_summary['active_total'] +=
            (float) (
                $history_row[
                    'total_internal_cost'
                ] ?? 0
            );
    }
}

$history_summary['order_count'] =
    count($history_orders);

sparrow_backyard_header('Supplier Applied History');

?>

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

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

<section class="card">
    <h1>Supplier Applied History</h1>

    <p class="muted">
        Review supplier costs applied to orders, open the
        matching order, or reverse an application when needed.
    </p>

    <div class="form-actions">
        <a
            class="button button-secondary"
            href="<?= supplier_history_e(
                sparrow_url(
                    '/backyard/supplier-splitter.php'
                )
            ) ?>"
        >
            Back to Supplier Splitter
        </a>

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

<section class="card">
    <div class="supplier-preview-summary">
        <div>
            <span>History Records</span>
            <strong>
                <?= number_format(
                    (int) $history_summary['count']
                ) ?>
            </strong>
        </div>

        <div>
            <span>Applied</span>
            <strong>
                <?= number_format(
                    (int) $history_summary[
                        'applied_count'
                    ]
                ) ?>
            </strong>
        </div>

        <div>
            <span>Reversed</span>
            <strong>
                <?= number_format(
                    (int) $history_summary[
                        'reversed_count'
                    ]
                ) ?>
            </strong>
        </div>

        <div>
            <span>Orders</span>
            <strong>
                <?= number_format(
                    (int) $history_summary[
                        'order_count'
                    ]
                ) ?>
            </strong>
        </div>

        <div>
            <span>Active Applied Total</span>
            <strong>
                <?= supplier_history_money(
                    $history_summary[
                        'active_total'
                    ]
                ) ?>
            </strong>
        </div>
    </div>
</section>

<section class="card">
    <h2>Application Records</h2>

    <?php if (!$applied_history): ?>
        <p class="muted">
            No supplier applications have been recorded.
        </p>
    <?php else: ?>
        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>Applied</th>
                        <th>Supplier</th>
                        <th>Receipt #</th>
                        <th>Order</th>
                        <th>Customer</th>
                        <th>Items</th>
                        <th>Shipping</th>
                        <th>Tax</th>
                        <th>Travel</th>
                        <th>Discount</th>
                        <th>Total</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach (
                        $applied_history as $history
                    ): ?>
                        <tr>
                            <td>
                                <?= supplier_history_e(
                                    $history[
                                        'applied_date'
                                    ] ?? ''
                                ) ?>
                            </td>

                            <td>
                                <strong>
                                    <?= supplier_history_e(
                                        $history[
                                            'supplier_name'
                                        ] ?? ''
                                    ) ?>
                                </strong>
                            </td>

                            <td>
                                <?= supplier_history_e(
                                    $history[
                                        'receipt_number'
                                    ] ?? ''
                                ) ?>
                            </td>

                            <td>
                                <?php if (
                                    !empty(
                                        $history[
                                            'matched_order_id'
                                        ]
                                    )
                                ): ?>
                                    <a href="<?= supplier_history_e(
                                        sparrow_url(
                                            '/backyard/order-view.php?id='
                                            . (int) $history[
                                                'matched_order_id'
                                            ]
                                        )
                                    ) ?>">
                                        <?= supplier_history_e(
                                            $history[
                                                'order_number'
                                            ] ?? ''
                                        ) ?>
                                    </a>
                                <?php else: ?>
                                    <?= supplier_history_e(
                                        $history[
                                            'order_number'
                                        ] ?? ''
                                    ) ?>
                                <?php endif; ?>
                            </td>

                            <td>
                                <?= supplier_history_e(
                                    $history[
                                        'customer_name'
                                    ] ?? ''
                                ) ?>
                            </td>

                            <td>
                                <?= supplier_history_money(
                                    $history[
                                        'item_total'
                                    ] ?? 0
                                ) ?>
                            </td>

                            <td>
                                <?= supplier_history_money(
                                    $history[
                                        'shipping_share'
                                    ] ?? 0
                                ) ?>
                            </td>

                            <td>
                                <?= supplier_history_money(
                                    $history[
                                        'tax_share'
                                    ] ?? 0
                                ) ?>
                            </td>

                            <td>
                                <?= supplier_history_money(
                                    $history[
                                        'travel_share'
                                    ] ?? 0
                                ) ?>
                            </td>

                            <td>
                                -<?= supplier_history_money(
                                    $history[
                                        'discount_share'
                                    ] ?? 0
                                ) ?>
                            </td>

                            <td>
                                <strong>
                                    <?= supplier_history_money(
                                        $history[
                                            'total_internal_cost'
                                        ] ?? 0
                                    ) ?>
                                </strong>
                            </td>

                            <td>
                                <?php if (
                                    ($history['status'] ?? '')
                                    === 'reversed'
                                ): ?>
                                    <span
                                        class="status-pill supplier-status-reviewed"
                                    >
                                        Reversed
                                    </span>

                                    <?php if (
                                        !empty(
                                            $history[
                                                'reversed_at'
                                            ]
                                        )
                                    ): ?>
                                        <div
                                            class="muted supplier-match-detail"
                                        >
                                            <?= supplier_history_e(
                                                $history[
                                                    'reversed_at'
                                                ]
                                            ) ?>
                                        </div>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span
                                        class="status-pill supplier-applied-pill"
                                    >
                                        Applied
                                    </span>
                                <?php endif; ?>
                            </td>

                            <td>
                                <?php if (
                                    ($history['status'] ?? '')
                                    === 'applied'
                                ): ?>
                                    <div
                                        class="supplier-reverse-control"
                                    >
                                        <button
                                            type="button"
                                            class="button button-secondary button-small supplier-reverse-toggle"
                                            aria-expanded="false"
                                        >
                                            Reverse
                                        </button>

                                        <form
                                            method="post"
                                            class="supplier-reverse-form"
                                            style="display:none; margin-top:10px; min-width:240px;"
                                            onsubmit="return confirm(
                                                'Reverse these exact supplier costs from this order?'
                                            );"
                                        >
                                            <input
                                                type="hidden"
                                                name="action"
                                                value="reverse_supplier_application"
                                            >

                                            <input
                                                type="hidden"
                                                name="application_id"
                                                value="<?= (int) (
                                                    $history[
                                                        'application_id'
                                                    ] ?? 0
                                                ) ?>"
                                            >

                                            <div>
                                                <label>
                                                    Reason
                                                </label>

                                                <input
                                                    type="text"
                                                    name="reversal_reason"
                                                    placeholder="Refund, wrong order, duplicate..."
                                                    required
                                                >
                                            </div>

                                            <div
                                                style="margin-top:10px;"
                                            >
                                                <label>
                                                    Type REVERSE
                                                </label>

                                                <input
                                                    type="text"
                                                    name="reverse_confirmation"
                                                    autocomplete="off"
                                                    placeholder="REVERSE"
                                                    required
                                                >
                                            </div>

                                            <div
                                                class="form-actions"
                                                style="margin-top:10px;"
                                            >
                                                <button
                                                    type="submit"
                                                    class="button button-secondary button-small"
                                                >
                                                    Confirm Reversal
                                                </button>

                                                <button
                                                    type="button"
                                                    class="button button-secondary button-small supplier-reverse-cancel"
                                                >
                                                    Cancel
                                                </button>
                                            </div>
                                        </form>
                                    </div>
                                <?php else: ?>
                                    <div class="muted">
                                        <?= supplier_history_e(
                                            $history[
                                                'reversal_reason'
                                            ]
                                            ?? 'Already reversed'
                                        ) ?>
                                    </div>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</section>

<script>
document.addEventListener('DOMContentLoaded', function () {
    document
        .querySelectorAll('.supplier-reverse-control')
        .forEach(function (control) {
            const toggleButton = control.querySelector(
                '.supplier-reverse-toggle'
            );

            const cancelButton = control.querySelector(
                '.supplier-reverse-cancel'
            );

            const form = control.querySelector(
                '.supplier-reverse-form'
            );

            if (!toggleButton || !form) {
                return;
            }

            toggleButton.addEventListener(
                'click',
                function () {
                    const isOpen =
                        form.style.display !== 'none';

                    form.style.display =
                        isOpen ? 'none' : 'block';

                    toggleButton.setAttribute(
                        'aria-expanded',
                        isOpen ? 'false' : 'true'
                    );
                }
            );

            if (cancelButton) {
                cancelButton.addEventListener(
                    'click',
                    function () {
                        form.style.display = 'none';

                        toggleButton.setAttribute(
                            'aria-expanded',
                            'false'
                        );
                    }
                );
            }
        });
});
</script>

<?php sparrow_backyard_footer(); ?>