<?php

require_once __DIR__ . '/app/auth.php';
require_once __DIR__ . '/app/customer-portal-accounts.php';
require_once __DIR__ . '/app/analytics.php';
require_once __DIR__ . '/app/public-layout.php';

sparrow_start_session();

$portal_account_id = (int) (
    $_SESSION['customer_portal_account_id'] ?? 0
);

if ($portal_account_id <= 0) {
    sparrow_redirect('/login.php');
}

$portal_account = sparrow_get_portal_account_by_id(
    $portal_account_id
);

if (!$portal_account || empty($portal_account['is_active'])) {
    unset(
        $_SESSION['customer_portal_account_id'],
        $_SESSION['customer_key']
    );

    sparrow_redirect('/login.php');
}

$customer_key = sparrow_resolve_customer_key(
    $portal_account['customer_key']
);

$_SESSION['customer_key'] = $customer_key;

/*
 * Select the customer portal section.
 */
$portal_sections = [
    'orders',
    'payments',
    'addresses',
    'account',
];

$portal_section = strtolower(trim(
    (string) ($_GET['portal_section'] ?? 'orders')
));

if (!in_array($portal_section, $portal_sections, true)) {
    $portal_section = 'orders';
}

/*
 * Create one security token for portal forms.
 */
if (empty($_SESSION['customer_portal_csrf'])) {
    $_SESSION['customer_portal_csrf'] = bin2hex(
        random_bytes(32)
    );
}

$portal_csrf = $_SESSION['customer_portal_csrf'];
$approval_error = '';
$approval_notice = $_SESSION['customer_portal_notice'] ?? '';
$address_error = '';
$account_error = '';
$password_error = '';

unset($_SESSION['customer_portal_notice']);

/*
 * Handle line-item approval responses.
 */
if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    && ($_POST['action'] ?? '')
        === 'customer_item_approval_response'
) {
    $submitted_token = (string) (
        $_POST['portal_csrf'] ?? ''
    );

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

    $response = trim(
        (string) ($_POST['approval_response'] ?? '')
    );

    $customer_notes = trim(
        (string) (
            $_POST['customer_approval_notes'] ?? ''
        )
    );

    if (
        $submitted_token === ''
        || !hash_equals(
            $portal_csrf,
            $submitted_token
        )
    ) {
        $approval_error =
            'Your form expired. Please refresh the page and try again.';
    } elseif (
        !in_array(
            $response,
            ['approved', 'changes_requested'],
            true
        )
    ) {
        $approval_error =
            'Please choose a valid approval response.';
    } else {
        $item_stmt = sparrow_db()->prepare("
            SELECT
                id,
                order_id,
                approval_status
            FROM order_items
            WHERE id = :order_item_id
            LIMIT 1
        ");

        $item_stmt->execute([
            ':order_item_id' => $order_item_id,
        ]);

        $submitted_item = $item_stmt->fetch(
            PDO::FETCH_ASSOC
        );

        $submitted_order_id = (int) (
            $submitted_item['order_id'] ?? 0
        );

        $submitted_order = $submitted_order_id > 0
            ? sparrow_get_order($submitted_order_id)
            : null;

        $submitted_order_key = $submitted_order
            ? sparrow_resolve_customer_key(
                sparrow_customer_key_from_order(
                    $submitted_order
                )
            )
            : '';

        if (
            !$submitted_item
            || !$submitted_order
            || $submitted_order_key !== $customer_key
        ) {
            $approval_error =
                'That item is not available through this account.';
        } elseif (
            empty(
                sparrow_get_order_item_approval_images(
                    $order_item_id
                )
            )
        ) {
            $approval_error =
                'This item does not have an approval image.';
        } else {
            $current_status = trim(
                (string) (
                    $submitted_item['approval_status']
                    ?? 'waiting'
                )
            );

            if ($current_status === '') {
                $current_status = 'waiting';
            }

            if ($current_status !== 'waiting') {
                $approval_error =
                    'A response has already been submitted for this item.';
            } elseif (
                $response === 'changes_requested'
                && $customer_notes === ''
            ) {
                $approval_error =
                    'Please describe the changes you would like.';
            } elseif (strlen($customer_notes) > 2000) {
                $approval_error =
                    'Your change request must be 2,000 characters or fewer.';
            } else {
                if ($response === 'approved') {
                    $customer_notes = '';
                }

                $update_stmt = sparrow_db()->prepare("
                    UPDATE order_items
                    SET
                        approval_status = :approval_status,
                        customer_approval_notes = :customer_notes,
                        approval_responded_at = NOW()
                    WHERE id = :order_item_id
                      AND order_id = :order_id
                    LIMIT 1
                ");

                $update_stmt->execute([
                    ':approval_status' => $response,
                    ':customer_notes' =>
                        $customer_notes !== ''
                            ? $customer_notes
                            : null,
                    ':order_item_id' => $order_item_id,
                    ':order_id' => $submitted_order_id,
                ]);

                $_SESSION['customer_portal_notice'] =
                    $response === 'approved'
                        ? 'Thank you! This item has been approved.'
                        : 'Your requested changes have been sent.';

                sparrow_redirect(
                    '/customer-portal.php#order-'
                    . $submitted_order_id
                );
            }
        }
    }
}

/*
 * Handle customer approval responses.
 */
if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    && ($_POST['action'] ?? '') === 'customer_approval_response'
) {
    $submitted_token = (string) (
        $_POST['portal_csrf'] ?? ''
    );

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

    $response = trim(
        (string) ($_POST['approval_response'] ?? '')
    );

    $customer_notes = trim(
        (string) ($_POST['customer_approval_notes'] ?? '')
    );

    if (
        $submitted_token === ''
        || !hash_equals($portal_csrf, $submitted_token)
    ) {
        $approval_error = 'Your form expired. Please refresh the page and try again.';
    } elseif (
        !in_array(
            $response,
            ['approved', 'changes_requested'],
            true
        )
    ) {
        $approval_error = 'Please choose a valid approval response.';
    } else {
        $submitted_order = sparrow_get_order($order_id);

        $submitted_order_key = $submitted_order
            ? sparrow_resolve_customer_key(
                sparrow_customer_key_from_order(
                    $submitted_order
                )
            )
            : '';

        if (
            !$submitted_order
            || $submitted_order_key !== $customer_key
        ) {
            $approval_error = 'That order is not available through this account.';
        } elseif (
    empty(
        sparrow_get_order_approval_images($order_id)
    )
    && empty($submitted_order['approval_image'])
) {
    $approval_error =
        'This order does not have an approval image.';
        } else {
            $current_approval_status = trim(
                (string) (
                    $submitted_order['approval_status']
                    ?? 'waiting'
                )
            );

            if ($current_approval_status === '') {
                $current_approval_status = 'waiting';
            }

            if ($current_approval_status !== 'waiting') {
                $approval_error = 'A response has already been submitted for this design.';
            } elseif (
                $response === 'changes_requested'
                && $customer_notes === ''
            ) {
                $approval_error = 'Please describe the changes you would like.';
            } elseif (strlen($customer_notes) > 2000) {
                $approval_error = 'Your change request must be 2,000 characters or fewer.';
            } else {
                if ($response === 'approved') {
                    $customer_notes = '';
                }

                $stmt = sparrow_db()->prepare("
                    UPDATE orders
                    SET
                        approval_status = :approval_status,
                        customer_approval_notes = :customer_notes,
                        approval_responded_at = NOW()
                    WHERE id = :order_id
                    LIMIT 1
                ");

                $stmt->execute([
                    ':approval_status' => $response,
                    ':customer_notes' => $customer_notes !== ''
                        ? $customer_notes
                        : null,
                    ':order_id' => $order_id,
                ]);

                $_SESSION['customer_portal_notice'] =
                    $response === 'approved'
                        ? 'Thank you! Your design has been approved.'
                        : 'Your requested changes have been sent.';

                sparrow_redirect(
                    '/customer-portal.php#order-' . $order_id
                );
            }
        }
    }
}

/*
 * Handle billing and shipping address updates.
 */
if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    && ($_POST['action'] ?? '') === 'update_portal_addresses'
) {
    $submitted_token = (string) (
        $_POST['portal_csrf'] ?? ''
    );

    $address_data = [
        'billing_name' => trim(
            (string) ($_POST['billing_name'] ?? '')
        ),
        'billing_address_1' => trim(
            (string) ($_POST['billing_address_1'] ?? '')
        ),
        'billing_address_2' => trim(
            (string) ($_POST['billing_address_2'] ?? '')
        ),
        'billing_city' => trim(
            (string) ($_POST['billing_city'] ?? '')
        ),
        'billing_state' => trim(
            (string) ($_POST['billing_state'] ?? '')
        ),
        'billing_postal_code' => trim(
            (string) ($_POST['billing_postal_code'] ?? '')
        ),
        'shipping_name' => trim(
            (string) ($_POST['shipping_name'] ?? '')
        ),
        'shipping_address_1' => trim(
            (string) ($_POST['shipping_address_1'] ?? '')
        ),
        'shipping_address_2' => trim(
            (string) ($_POST['shipping_address_2'] ?? '')
        ),
        'shipping_city' => trim(
            (string) ($_POST['shipping_city'] ?? '')
        ),
        'shipping_state' => trim(
            (string) ($_POST['shipping_state'] ?? '')
        ),
        'shipping_postal_code' => trim(
            (string) ($_POST['shipping_postal_code'] ?? '')
        ),
    ];

    $shipping_same_as_billing = !empty(
        $_POST['shipping_same_as_billing']
    );

    if (
        $submitted_token === ''
        || !hash_equals($portal_csrf, $submitted_token)
    ) {
        $address_error =
            'Your form expired. Please refresh the page and try again.';
    } elseif (
        $address_data['billing_name'] === ''
        || $address_data['billing_address_1'] === ''
        || $address_data['billing_city'] === ''
        || $address_data['billing_state'] === ''
        || $address_data['billing_postal_code'] === ''
    ) {
        $address_error =
            'Please complete all required billing address fields.';
    } else {
        if ($shipping_same_as_billing) {
            $address_data['shipping_name'] =
                $address_data['billing_name'];

            $address_data['shipping_address_1'] =
                $address_data['billing_address_1'];

            $address_data['shipping_address_2'] =
                $address_data['billing_address_2'];

            $address_data['shipping_city'] =
                $address_data['billing_city'];

            $address_data['shipping_state'] =
                $address_data['billing_state'];

            $address_data['shipping_postal_code'] =
                $address_data['billing_postal_code'];
        } elseif (
            $address_data['shipping_name'] === ''
            || $address_data['shipping_address_1'] === ''
            || $address_data['shipping_city'] === ''
            || $address_data['shipping_state'] === ''
            || $address_data['shipping_postal_code'] === ''
        ) {
            $address_error =
                'Please complete all required shipping address fields.';
        }

        if ($address_error === '') {
            try {
                sparrow_update_portal_addresses(
                    $portal_account_id,
                    $address_data
                );

                $_SESSION['customer_portal_notice'] =
                    'Your addresses have been saved.';

                sparrow_redirect(
                    '/customer-portal.php'
                    . '?portal_section=addresses'
                );
            } catch (InvalidArgumentException $exception) {
                $address_error = $exception->getMessage();
            }
        }
    }
}

/*
 * Prepare the saved or submitted address values for the form.
 */
$address_field_names = [
    'billing_name',
    'billing_address_1',
    'billing_address_2',
    'billing_city',
    'billing_state',
    'billing_postal_code',
    'shipping_name',
    'shipping_address_1',
    'shipping_address_2',
    'shipping_city',
    'shipping_state',
    'shipping_postal_code',
];

$address_values = [];

$is_address_submission =
    $_SERVER['REQUEST_METHOD'] === 'POST'
    && ($_POST['action'] ?? '') === 'update_portal_addresses';

foreach ($address_field_names as $address_field_name) {
    $address_values[$address_field_name] = trim(
        (string) (
            $is_address_submission
                ? ($_POST[$address_field_name] ?? '')
                : ($portal_account[$address_field_name] ?? '')
        )
    );
}

if ($is_address_submission) {
    $shipping_same_as_billing = !empty(
        $_POST['shipping_same_as_billing']
    );
} else {
    $shipping_is_empty =
        $address_values['shipping_name'] === ''
        && $address_values['shipping_address_1'] === ''
        && $address_values['shipping_city'] === ''
        && $address_values['shipping_state'] === ''
        && $address_values['shipping_postal_code'] === '';

    $shipping_matches_billing =
        $address_values['shipping_name']
            === $address_values['billing_name']
        && $address_values['shipping_address_1']
            === $address_values['billing_address_1']
        && $address_values['shipping_address_2']
            === $address_values['billing_address_2']
        && $address_values['shipping_city']
            === $address_values['billing_city']
        && $address_values['shipping_state']
            === $address_values['billing_state']
        && $address_values['shipping_postal_code']
            === $address_values['billing_postal_code'];

    $shipping_same_as_billing =
        $shipping_is_empty || $shipping_matches_billing;
}

/*
 * Handle customer account detail updates.
 */
if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    && ($_POST['action'] ?? '') === 'update_portal_account'
) {
    $submitted_token = (string) (
        $_POST['portal_csrf'] ?? ''
    );

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

    if (
        $submitted_token === ''
        || !hash_equals($portal_csrf, $submitted_token)
    ) {
        $account_error =
            'Your form expired. Please refresh the page and try again.';
    } else {
        try {
            sparrow_update_portal_email(
                $portal_account_id,
                $account_email
            );

            $_SESSION['customer_portal_notice'] =
                'Your account details have been saved.';

            sparrow_redirect(
                '/customer-portal.php'
                . '?portal_section=account'
            );
        } catch (InvalidArgumentException $exception) {
            $account_error = $exception->getMessage();
        }
    }
}

/*
 * Handle portal password changes.
 */
if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    && ($_POST['action'] ?? '') === 'change_portal_password'
) {
    $submitted_token = (string) (
        $_POST['portal_csrf'] ?? ''
    );

    $current_password = (string) (
        $_POST['current_password'] ?? ''
    );

    $new_password = (string) (
        $_POST['new_password'] ?? ''
    );

    $confirm_password = (string) (
        $_POST['confirm_password'] ?? ''
    );

    if (
        $submitted_token === ''
        || !hash_equals($portal_csrf, $submitted_token)
    ) {
        $password_error =
            'Your form expired. Please refresh the page and try again.';
    } elseif ($new_password !== $confirm_password) {
        $password_error =
            'Your new password and confirmation do not match.';
    } else {
        try {
            sparrow_change_portal_password(
                $portal_account_id,
                $current_password,
                $new_password
            );

            $_SESSION['customer_portal_notice'] =
                'Your password has been changed successfully.';

            sparrow_redirect(
                '/customer-portal.php'
                . '?portal_section=account'
            );
        } catch (
            InvalidArgumentException | RuntimeException $exception
        ) {
            $password_error = $exception->getMessage();
        }
    }
}

$customer_orders = sparrow_get_customer_orders_by_key(
    $customer_key
);

$account_email_value = trim(
    (string) (
        $_SERVER['REQUEST_METHOD'] === 'POST'
        && ($_POST['action'] ?? '') ===
            'update_portal_account'
            ? ($_POST['account_email'] ?? '')
            : ($portal_account['email'] ?? '')
    )
);

$customer_name = '';
$open_order_count = 0;
$ready_order_count = 0;
$total_balance = 0.00;

$closed_statuses = [
    'Delivered',
    'Completed',
    'Complete',
    'Archived',
    'Merged',
    'Cancelled',
];

foreach ($customer_orders as $customer_order) {
    if (
        $customer_name === ''
        && !empty($customer_order['customer_name'])
    ) {
        $customer_name = trim(
            (string) $customer_order['customer_name']
        );
    }

    $status = trim(
        (string) ($customer_order['status'] ?? '')
    );

    if (!in_array($status, $closed_statuses, true)) {
        $open_order_count++;
    }

    if ($status === 'Ready for Pickup') {
        $ready_order_count++;
    }

    if (empty($customer_order['is_gift'])) {
        $total_balance += sparrow_customer_order_balance(
            $customer_order
        );
    }
}

if ($customer_name === '') {
    $customer_name = $portal_account['username'];
}

sparrow_record_analytics_event(
    'page_view',
    'page',
    null,
    'Customer Portal',
    '',
    '/customer-portal'
);


$portal_css = <<<'CSS'
.customer-portal-grid {
    display: grid;
    grid-template-columns: minmax(260px, 340px) minmax(0, 1fr);
    gap: 18px;
    align-items: start;
}

.customer-portal-menu,
.customer-portal-main-card,
.customer-portal-order-card {
    background: linear-gradient(135deg, #ffffff, var(--sparrow-bg-soft));
    border: 1px solid var(--sparrow-border);
    border-left: 5px solid var(--sparrow-pink);
    border-radius: 18px;
    box-shadow: 0 2px 12px rgba(125, 90, 106, 0.08);
}

.customer-portal-menu {
    padding: 18px;
}

.customer-portal-menu h2 {
    margin: 0 0 8px;
    color: var(--sparrow-purple-dark);
    font-size: 22px;
}

.customer-portal-menu p {
    margin: 0 0 14px;
    color: var(--sparrow-muted);
    line-height: 1.55;
}

.customer-portal-nav {
    display: grid;
    gap: 8px;
    margin-top: 14px;
}

.customer-portal-nav a {
    display: block;
    padding: 9px 12px;
    background: #ffffff;
    border: 1px solid var(--sparrow-border);
    border-radius: 999px;
    color: var(--sparrow-purple-dark);
    font-weight: bold;
    text-decoration: none;
}

.customer-portal-nav a:hover,
.customer-portal-nav a.is-active {
    background: var(--sparrow-soft-pink);
    color: var(--sparrow-pink-dark);
}

.customer-portal-main {
    display: grid;
    gap: 16px;
}

.customer-portal-main-card {
    padding: 20px;
}

.customer-portal-main-card h2 {
    margin: 0 0 8px;
    color: var(--sparrow-purple-dark);
}

.customer-portal-main-card h2::before {
    display: inline-block;
    margin-right: 8px;
    color: var(--sparrow-pink);
    font-size: 0.72em;
    vertical-align: 2px;
}

.customer-portal-main-card p {
    color: var(--sparrow-muted);
}

.customer-portal-items-box {
    display: grid;
    gap: 14px;
}

.customer-portal-items-box > h4 {
    margin: 0;
    padding-bottom: 12px;
    border-bottom: 1px solid #ead4df;
}

.customer-portal-items-box .customer-portal-items {
    gap: 12px;
    margin-top: 0;
}

.customer-portal-items-box .customer-portal-item {
    padding: 14px;
    border: 1px solid #f0dce6;
    border-radius: 11px;
    background: #fffafd;
}

.customer-portal-item > strong {
    display: inline-flex;
    margin-bottom: 8px;
    padding: 6px 11px;
    border-radius: 999px;
    background: #f4dce8;
    color: #854766;
    font-size: 14px;
}

.customer-portal-items-box .customer-portal-item p {
    margin: 6px 0;
    line-height: 1.5;
}

.customer-portal-items-box .customer-portal-item p strong {
    color: #854766;
}

.customer-portal-summary-row {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 10px;
    margin-top: 14px;
}

.customer-portal-summary-box {
    padding: 12px;
    background: #ffffff;
    border: 1px solid var(--sparrow-border);
    border-radius: 14px;
}

.customer-portal-summary-box span {
    display: block;
    margin-bottom: 4px;
    color: var(--sparrow-muted);
    font-size: 11px;
    font-weight: bold;
    text-transform: uppercase;
    letter-spacing: 0.04em;
}

.customer-portal-summary-box strong {
    color: var(--sparrow-purple-dark);
    font-size: 17px;
}

.customer-portal-order-list {
    display: grid;
    gap: 12px;
}

.customer-portal-order-card {
    display: flex;
    justify-content: space-between;
    gap: 14px;
    align-items: center;
    padding: 14px;
}

.customer-portal-order-card h3 {
    margin: 0 0 4px;
    color: var(--sparrow-purple-dark);
    font-size: 18px;
}

.customer-portal-order-card p {
    margin: 0;
    color: var(--sparrow-muted);
    font-size: 13px;
}

.customer-portal-pill {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 6px 10px;
    background: #ffffff;
    border: 1px solid var(--sparrow-border);
    border-radius: 999px;
    color: var(--sparrow-purple-dark);
    font-size: 12px;
    font-weight: bold;
    white-space: nowrap;
}

.customer-portal-placeholder-image {
    display: flex;
    min-height: 220px;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    gap: 6px;
    padding: 18px;
    background: linear-gradient(135deg, #ffffff, var(--sparrow-soft-pink));
    border: 1px dashed var(--sparrow-border);
    border-radius: 18px;
    color: var(--sparrow-muted);
    text-align: center;
}

.customer-portal-placeholder-image strong {
    color: var(--sparrow-purple-dark);
    font-size: 18px;
}

.customer-portal-order-card {
    display: block;
    padding: 0;
    overflow: hidden;
}

.customer-portal-order-summary {
    display: grid;
    grid-template-columns: minmax(0, 1fr) 110px 90px;
    gap: 14px;
    align-items: center;
    padding: 14px;
    cursor: pointer;
    list-style: none;
}

.customer-portal-order-summary .customer-portal-pill {
    justify-self: center;
}

.customer-portal-order-summary::after {
    justify-self: end;
    text-align: right;
}

.customer-portal-order-summary::-webkit-details-marker {
    display: none;
}

.customer-portal-order-summary::after {
    content: "View Details";
    color: var(--sparrow-pink-dark);
    font-size: 12px;
    font-weight: bold;
    white-space: nowrap;
}

.customer-portal-order-card[open]
.customer-portal-order-summary::after {
    content: "Hide Details";
}

.customer-portal-order-details {
    padding: 0 14px 16px;
    border-top: 1px solid var(--sparrow-border);
}

.customer-portal-detail-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 10px;
    margin-top: 14px;
}

.customer-portal-detail-box {
    padding: 12px;
    background: #ffffff;
    border: 1px solid var(--sparrow-border);
    border-radius: 14px;
}

.customer-portal-detail-box h4 {
    margin: 0 0 8px;
    color: var(--sparrow-purple-dark);
}

.customer-portal-detail-box p {
    margin: 4px 0;
}

.customer-portal-items {
    display: grid;
    gap: 8px;
    margin-top: 10px;
}

.customer-portal-item {
    padding: 10px 12px;
    background: var(--sparrow-bg-soft);
    border-radius: 12px;
}

.customer-portal-item strong {
    color: var(--sparrow-purple-dark);
}

.payment-calculation {
    display: grid;
    gap: 9px;
}

.payment-calculation p {
    display: flex;
    justify-content: space-between;
    gap: 16px;
    margin: 0;
}

.payment-subtract {
    color: #9a4668;
}

.payment-total {
    margin-top: 5px !important;
    padding-top: 12px;
    border-top: 1px solid #ead4df;
}

.payment-balance {
    margin-top: 5px !important;
    padding: 12px;
    border-radius: 10px;
    background: #fff3f8;
    color: #854766;
}

.customer-portal-delivery-box {
    display: grid;
    gap: 14px;
}

.customer-portal-delivery-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    padding-bottom: 12px;
    border-bottom: 1px solid #ead4df;
}

.customer-portal-delivery-header h4 {
    margin: 0;
}

.customer-portal-delivery-method {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 6px 12px;
    border-radius: 999px;
    background: #854766;
    color: #ffffff;
    font-size: 13px;
    font-weight: 700;
    line-height: 1;
}

.customer-portal-delivery-detail {
    padding: 13px 14px;
    border: 1px solid #f0dce6;
    border-radius: 11px;
    background: #fffafd;
}

.customer-portal-delivery-label {
    display: block;
    margin-bottom: 7px;
    color: #854766;
    font-size: 14px;
}

.customer-portal-delivery-detail address {
    margin: 0;
    font-style: normal;
    line-height: 1.5;
}

.customer-portal-delivery-detail p {
    margin: 0;
    line-height: 1.5;
}

@media (max-width: 500px) {
    .customer-portal-delivery-header {
        align-items: flex-start;
        flex-direction: column;
    }
}

.customer-portal-item-approvals-box {
    grid-column: 1 / -1;
}

.customer-portal-item-approvals {
    display: grid;
    gap: 18px;
    margin-top: 18px;
}

.customer-portal-item-approval-card {
    padding: 16px;
    border: 1px solid #f0dce6;
    border-radius: 14px;
    background: #fffafd;
}

.customer-portal-item-approval-card h5 {
    margin: 0 0 8px;
    color: var(--sparrow-purple-dark);
    font-size: 17px;
}

.customer-portal-item-approval-card > p {
    margin: 5px 0;
}

.customer-portal-item-approval-card
.customer-portal-approval-gallery {
    justify-content: start;
    margin-top: 16px;
}

.customer-portal-item-approval-card
.customer-portal-approval-item {
    padding: 12px;
    border: 1px solid #f0dce6;
    border-radius: 12px;
    background: #ffffff;
    box-sizing: border-box;
}

.customer-portal-approval-box {
    grid-column: 1 / -1;
}

.customer-portal-approval-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 12px;
    margin-bottom: 12px;
}

.customer-portal-approval-header h4 {
    margin: 0;
}

.customer-portal-approval-status {
    display: inline-flex;
    align-items: center;
    padding: 5px 10px;
    border-radius: 999px;
    font-size: 12px;
    font-weight: bold;
    white-space: nowrap;
}

.customer-portal-approval-waiting {
    color: #735b18;
    background: #fff4c7;
}

.customer-portal-approval-approved {
    color: #22613c;
    background: #dff5e7;
}

.customer-portal-approval-changes_requested {
    color: #8a3f57;
    background: #f9dfe8;
}

.customer-portal-approval-image {
    display: block;
    width: 100%;
    max-width: 200px;
    max-height: 200px;
    margin: 0 auto;
    object-fit: contain;
    border: 1px solid var(--sparrow-border);
    border-radius: 14px;
    background: #ffffff;
}

.customer-portal-approval-gallery {
    display: grid;
    grid-template-columns: repeat(
        auto-fit,
        minmax(180px, 240px)
    );
    justify-content: center;
    gap: 18px;
}

.customer-portal-approval-item {
    text-align: center;
}

.customer-portal-approval-item h5 {
    margin: 0 0 8px;
    font-size: 15px;
}

.customer-portal-approval-button,
.customer-portal-watermarked-image {
    position: relative;
    overflow: hidden;
}

.customer-portal-watermarked-image {
    display: inline-flex;
    max-width: 100%;
}

.customer-portal-watermark {
    position: absolute;
    top: 50%;
    left: 50%;
    z-index: 2;
    width: 130%;
    padding: 8px 12px;
    color: rgba(255, 255, 255, 0.72);
    background: rgba(65, 45, 60, 0.28);
    font-size: clamp(13px, 2vw, 22px);
    font-weight: 700;
    letter-spacing: 1px;
    text-align: center;
    text-transform: uppercase;
    text-shadow: 0 1px 3px rgba(0, 0, 0, 0.65);
    pointer-events: none;
    transform: translate(-50%, -50%) rotate(-24deg);
}

.customer-portal-approval-notes {
    margin-top: 12px;
    padding: 10px 12px;
    background: var(--sparrow-bg-soft);
    border-radius: 12px;
}

.customer-portal-approval-button {
    display: block;
    margin: 0 auto;
    padding: 0;
    border: 0;
    border-radius: 14px;
    background: transparent;
    cursor: zoom-in;
}

.customer-portal-approval-lightbox {
    width: min(92vw, 1000px);
    max-width: 1000px;
    padding: 14px;
    border: 0;
    border-radius: 18px;
    background: #ffffff;
    box-shadow: 0 18px 55px rgba(70, 45, 75, 0.35);
}

.customer-portal-approval-lightbox::backdrop {
    background: rgba(35, 25, 40, 0.82);
}

.customer-portal-lightbox-image {
    display: block;
    width: auto;
    max-width: 100%;
    max-height: 82vh;
    margin: 0 auto;
    object-fit: contain;
    border-radius: 12px;
}

.customer-portal-lightbox-close {
    display: block;
    margin: 0 0 10px auto;
    padding: 7px 12px;
    border: 0;
    border-radius: 999px;
    color: #ffffff;
    background: var(--sparrow-purple-dark);
    font-weight: bold;
    cursor: pointer;
}

.customer-portal-message {
    margin-bottom: 16px;
    padding: 12px 14px;
    border-radius: 14px;
    font-weight: bold;
}

.customer-portal-message-success {
    color: #22613c;
    background: #dff5e7;
    border: 1px solid #b9dfc8;
}

.customer-portal-message-error {
    color: #8a3f57;
    background: #f9dfe8;
    border: 1px solid #ecc0cf;
}

.customer-portal-approval-actions {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    align-items: flex-start;
    margin-top: 16px;
}

.customer-portal-approval-actions form {
    margin: 0;
}

.customer-portal-approval-action {
    padding: 9px 15px;
    border: 0;
    border-radius: 999px;
    font-weight: bold;
    cursor: pointer;
}

.customer-portal-approve-button {
    color: #ffffff;
    background: #43865f;
}

.customer-portal-change-request {
    min-width: min(100%, 360px);
}

.customer-portal-change-request > summary {
    display: inline-block;
    padding: 9px 15px;
    border-radius: 999px;
    color: #8a3f57;
    background: #f9dfe8;
    font-weight: bold;
    cursor: pointer;
    list-style: none;
}

.customer-portal-change-request > summary::-webkit-details-marker {
    display: none;
}

.customer-portal-change-form {
    display: grid;
    gap: 10px;
    margin-top: 10px !important;
    padding: 14px;
    border: 1px solid var(--sparrow-border);
    border-radius: 14px;
    background: var(--sparrow-bg-soft);
}

.customer-portal-change-form label {
    color: var(--sparrow-purple-dark);
    font-weight: bold;
}

.customer-portal-change-form textarea {
    width: 100%;
    min-height: 110px;
    padding: 10px;
    border: 1px solid var(--sparrow-border);
    border-radius: 10px;
    resize: vertical;
    font: inherit;
}

.customer-portal-send-change-button {
    display: inline-block;
    justify-self: start;
    color: #ffffff;
    background: #b85d87;
}

.customer-portal-customer-response {
    margin-top: 14px;
    padding: 12px;
    border-radius: 12px;
    background: var(--sparrow-bg-soft);
}

.customer-portal-paid-pill {
    display: inline-flex;
    align-items: center;
    margin-left: 6px;
    padding: 5px 11px;
    color: #24613d;
    font-size: 0.88rem;
    font-weight: 700;
    line-height: 1.2;
    background: #e2f4e8;
    border: 1px solid #b8dfc5;
    border-radius: 999px;
}

@media (max-width: 650px) {
    .customer-portal-approval-header {
        align-items: flex-start;
        flex-direction: column;
    }
}

@media (max-width: 650px) {
    .customer-portal-order-summary {
    grid-template-columns: minmax(0, 1fr) auto;
    align-items: start;
}

.customer-portal-order-summary .customer-portal-pill {
    justify-self: end;
}

.customer-portal-order-summary::after {
    grid-column: 1 / -1;
    justify-self: end;
}

    .customer-portal-detail-grid {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 850px) {
    .customer-portal-grid {
        grid-template-columns: 1fr;
    }

    .customer-portal-summary-row {
        grid-template-columns: 1fr;
    }

    .customer-portal-order-card {
        display: grid;
    }
}

/* Customer portal address form */

.customer-portal-address-form {
    margin-top: 24px;
}

.customer-portal-address-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 24px;
    align-items: start;
}

.customer-portal-address-card {
    padding: 24px;
    background: #fffafd;
    border: 1px solid #ead9e5;
    border-radius: 16px;
    box-shadow: 0 8px 22px rgba(83, 53, 75, 0.07);
}

.customer-portal-address-card h3 {
    margin: 0 0 20px;
    color: #704b67;
    font-size: 1.2rem;
}

.customer-portal-address-card > label {
    display: grid;
    gap: 7px;
    margin-bottom: 16px;
    color: #4f3c4a;
    font-weight: 700;
}

.customer-portal-address-card input[type="text"] {
    width: 100%;
    min-height: 46px;
    padding: 10px 12px;
    color: #3d3039;
    font: inherit;
    font-weight: 400;
    background: #ffffff;
    border: 1px solid #d9c9d4;
    border-radius: 10px;
    box-sizing: border-box;
}

.customer-portal-address-card input[type="text"]:focus {
    outline: none;
    border-color: #bb739f;
    box-shadow: 0 0 0 3px rgba(187, 115, 159, 0.16);
}

.customer-portal-address-row {
    display: grid;
    grid-template-columns: minmax(0, 1fr) minmax(120px, 0.7fr);
    gap: 14px;
}

.customer-portal-address-row label {
    display: grid;
    gap: 7px;
    color: #4f3c4a;
    font-weight: 700;
}

.customer-portal-address-checkbox {
    display: flex !important;
    grid-template-columns: none !important;
    flex-direction: row;
    align-items: flex-start;
    gap: 10px !important;
    margin: 0 0 8px !important;
    padding: 12px 14px;
    background: #f8edf4;
    border: 1px solid #ead4e2;
    border-radius: 10px;
    cursor: pointer;
}

.customer-portal-address-checkbox input {
    width: 18px;
    height: 18px;
    margin: 2px 0 0;
    flex: 0 0 auto;
    accent-color: #a85f8e;
}

.customer-portal-address-checkbox span {
    line-height: 1.4;
}

.customer-portal-address-help {
    margin: 0 0 18px;
    color: #75636f;
    font-size: 0.9rem;
    line-height: 1.5;
}

.customer-portal-address-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 22px;
}

.customer-portal-address-save {
    min-height: 44px;
    padding: 11px 22px;
    color: #ffffff;
    font: inherit;
    font-weight: 700;
    background: #9b5b83;
    border: 0;
    border-radius: 10px;
    cursor: pointer;
    transition:
        background-color 0.2s ease,
        transform 0.2s ease;
}

.customer-portal-address-save:hover {
    background: #82496d;
    transform: translateY(-1px);
}

.customer-portal-address-save:focus-visible {
    outline: 3px solid rgba(155, 91, 131, 0.3);
    outline-offset: 3px;
}

@media (max-width: 850px) {
    .customer-portal-address-grid {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 520px) {
    .customer-portal-address-card {
        padding: 18px;
    }

    .customer-portal-address-row {
        grid-template-columns: 1fr;
    }

    .customer-portal-address-actions {
        display: block;
    }

    .customer-portal-address-save {
        width: 100%;
    }
}

/* Customer portal account details */

.customer-portal-account-form {
    margin-top: 24px;
}

.customer-portal-account-fields {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 18px;
    padding: 24px;
    background: #fffafd;
    border: 1px solid #ead9e5;
    border-radius: 16px;
    box-shadow: 0 8px 22px rgba(83, 53, 75, 0.07);
}

.customer-portal-account-fields label {
    display: grid;
    gap: 7px;
    color: #4f3c4a;
    font-weight: 700;
}

.customer-portal-account-fields label:last-child {
    grid-column: 1 / -1;
}

.customer-portal-account-fields input {
    width: 100%;
    min-height: 46px;
    padding: 10px 12px;
    color: #3d3039;
    font: inherit;
    font-weight: 400;
    background: #ffffff;
    border: 1px solid #d9c9d4;
    border-radius: 10px;
    box-sizing: border-box;
}

.customer-portal-account-fields input:focus {
    outline: none;
    border-color: #bb739f;
    box-shadow: 0 0 0 3px rgba(187, 115, 159, 0.16);
}

.customer-portal-account-fields input:disabled {
    color: #74656f;
    background: #f3edf1;
    border-color: #e2d7de;
    cursor: not-allowed;
    opacity: 1;
}

.customer-portal-account-help {
    margin: 16px 0 0;
    color: #75636f;
    font-size: 0.9rem;
    line-height: 1.5;
}

.customer-portal-account-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 22px;
}

.customer-portal-account-save {
    min-height: 44px;
    padding: 11px 22px;
    color: #ffffff;
    font: inherit;
    font-weight: 700;
    background: #9b5b83;
    border: 0;
    border-radius: 10px;
    cursor: pointer;
    transition:
        background-color 0.2s ease,
        transform 0.2s ease;
}

.customer-portal-account-save:hover {
    background: #82496d;
    transform: translateY(-1px);
}

.customer-portal-account-save:focus-visible {
    outline: 3px solid rgba(155, 91, 131, 0.3);
    outline-offset: 3px;
}

@media (max-width: 650px) {
    .customer-portal-account-fields {
        grid-template-columns: 1fr;
        padding: 18px;
    }

    .customer-portal-account-fields label:last-child {
        grid-column: auto;
    }

    .customer-portal-account-actions {
        display: block;
    }

    .customer-portal-account-save {
        width: 100%;
    }
}

/* Customer portal password form */

.customer-portal-password-card {
    padding: 24px;
    background: #fffafd;
    border: 1px solid #ead9e5;
    border-radius: 16px;
    box-shadow: 0 8px 22px rgba(83, 53, 75, 0.07);
}

.customer-portal-password-card h3 {
   margin: 0 0 20px;
    color: #704b67;
    font-size: 1.2rem;
}

.customer-portal-password-card > p {
    margin: 0 0 20px;
    color: #75636f;
    line-height: 1.5;
}

.customer-portal-password-form {
    margin-top: 20px;
}

.customer-portal-password-fields {
	display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 18px;
    padding: 24px;
    background: #fffafd;
    border: 1px solid #ead9e5;
    border-radius: 16px;
    box-shadow: 0 8px 22px rgba(83, 53, 75, 0.07);
}

.customer-portal-password-fields label {
    display: grid;
    gap: 7px;
    color: #4f3c4a;
    font-weight: 700;
}

.customer-portal-password-fields label:first-child {
    grid-column: 1 / -1;
}

.customer-portal-password-fields input {
    width: 100%;
    min-height: 46px;
    padding: 10px 12px;
    color: #3d3039;
    font: inherit;
    font-weight: 400;
    background: #ffffff;
    border: 1px solid #d9c9d4;
    border-radius: 10px;
    box-sizing: border-box;
}

.customer-portal-password-fields input:focus {
    outline: none;
    border-color: #bb739f;
    box-shadow: 0 0 0 3px rgba(187, 115, 159, 0.16);
}

.customer-portal-password-help {
    margin: 16px 0 0;
    color: #75636f;
    font-size: 0.9rem;
    line-height: 1.5;
}

.customer-portal-password-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 22px;
}

.customer-portal-password-save {
    min-height: 44px;
    padding: 11px 22px;
    color: #ffffff;
    font: inherit;
    font-weight: 700;
    background: #9b5b83;
    border: 0;
    border-radius: 10px;
    cursor: pointer;
    transition:
        background-color 0.2s ease,
        transform 0.2s ease;
}

.customer-portal-password-save:hover {
    background: #82496d;
    transform: translateY(-1px);
}

.customer-portal-password-save:focus-visible {
    outline: 3px solid rgba(155, 91, 131, 0.3);
    outline-offset: 3px;
}

@media (max-width: 650px) {
    .customer-portal-password-card {
        padding: 18px;
    }

    .customer-portal-password-fields {
        grid-template-columns: 1fr;
    }

    .customer-portal-password-fields label:first-child {
        grid-column: auto;
    }

    .customer-portal-password-actions {
        display: block;
    }

    .customer-portal-password-save {
        width: 100%;
    }
}
CSS;

sparrow_public_header('Customer Portal', 'customer-portal', $portal_css);

?>

<?php if ($approval_notice !== ''): ?>
    <div class="customer-portal-message customer-portal-message-success">
        <?php echo sparrow_escape($approval_notice); ?>
    </div>
<?php endif; ?>

<?php if ($approval_error !== ''): ?>
    <div class="customer-portal-message customer-portal-message-error">
        <?php echo sparrow_escape($approval_error); ?>
    </div>
<?php endif; ?>

<section class="public-card public-hero">
    <h1>Customer Portal</h1>
    <p>
        A cozy little place to check custom order updates, payment information, pickup details, and approval images.
    </p>
</section>

<section class="customer-portal-grid home-section-space">
    <aside class="customer-portal-menu">
        <h2>Welcome</h2>

        <p>
    Hi, <?php echo sparrow_escape($customer_name); ?>!
    You can view your Sparrow &amp; Seed orders and current balances here.
</p>

<nav
    class="customer-portal-nav"
    aria-label="Customer portal menu"
>
    <a
        class="<?php echo $portal_section === 'orders'
            ? 'is-active'
            : ''; ?>"
        href="<?php echo sparrow_escape(
            sparrow_url(
                '/customer-portal.php?portal_section=orders'
            )
        ); ?>"
    >
        My Orders
    </a>

    <a
        class="<?php echo $portal_section === 'payments'
            ? 'is-active'
            : ''; ?>"
        href="<?php echo sparrow_escape(
            sparrow_url(
                '/customer-portal.php?portal_section=payments'
            )
        ); ?>"
    >
        Payments
    </a>

    <a
        class="<?php echo $portal_section === 'addresses'
            ? 'is-active'
            : ''; ?>"
        href="<?php echo sparrow_escape(
            sparrow_url(
                '/customer-portal.php?portal_section=addresses'
            )
        ); ?>"
    >
        Addresses
    </a>

    <a
        class="<?php echo $portal_section === 'account'
            ? 'is-active'
            : ''; ?>"
        href="<?php echo sparrow_escape(
            sparrow_url(
                '/customer-portal.php?portal_section=account'
            )
        ); ?>"
    >
        Account Details
    </a>

    <a
        href="<?php echo sparrow_escape(
            sparrow_url('/logout.php')
        ); ?>"
    >
        Log Out
    </a>
</nav>
    </aside>

    <main class="customer-portal-main">
	<?php if ($portal_section === 'orders'): ?>
        <section
    class="customer-portal-main-card"
    id="my-orders"
>
    <h2>My Custom Orders</h2>

            <p>
    Your orders are connected directly to your customer history.
    Only orders belonging to your portal account are shown.
</p>

            <div class="customer-portal-summary-row">
                <div class="customer-portal-summary-box">
                    <span>Open Orders</span>
                    <strong><?php echo $open_order_count; ?></strong>
                </div>

                <div class="customer-portal-summary-box">
                    <span>Balance Due</span>
                    <strong>
    $<?php echo number_format($total_balance, 2); ?>
</strong>
                </div>

                <div class="customer-portal-summary-box">
                    <span>Ready for Pickup</span>
                    <strong><?php echo $ready_order_count; ?></strong>
                </div>
            </div>
        </section>

        <section class="customer-portal-main-card">
    <h2>Your Orders</h2>

    <?php if (!$customer_orders): ?>
        <div class="customer-portal-placeholder-image">
            <strong>No Orders Found</strong>

            <span>
                There are no orders connected to this portal account yet.
            </span>
        </div>
    <?php else: ?>
        <div class="customer-portal-order-list">
            <?php foreach ($customer_orders as $customer_order): ?>
                <?php
                $order_status = trim(
                    (string) ($customer_order['status'] ?? 'Order Received')
                );

                $order_balance = !empty($customer_order['is_gift'])
                    ? 0.00
                    : sparrow_customer_order_balance($customer_order);

                $order_date = trim(
                    (string) ($customer_order['order_date'] ?? '')
                );

                $formatted_date = $order_date !== ''
                    ? date('F j, Y', strtotime($order_date))
                    : 'Date not available';

                $item_summary = trim(
                    (string) ($customer_order['item_summary'] ?? '')
                );
				
				$order_id = (int) ($customer_order['id'] ?? 0);

$order_items = $order_id > 0
    ? sparrow_get_order_items($order_id)
    : [];
	
	$item_approval_images_by_item = [];

foreach ($order_items as $order_item) {
    $portal_order_item_id = (int) (
        $order_item['id'] ?? 0
    );

    if ($portal_order_item_id <= 0) {
        continue;
    }

    $item_approval_images_by_item[
        $portal_order_item_id
    ] = sparrow_get_order_item_approval_images(
        $portal_order_item_id
    );
}

$order_total = (float) (
    $customer_order['total_amount'] ?? 0
);

if (
    $order_total <= 0
    && $order_id > 0
    && function_exists(
        'sparrow_calculate_order_pricing_from_lookup'
    )
) {
    $pricing = sparrow_calculate_order_pricing_from_lookup(
        $order_id
    );

    $order_total = (float) (
        $pricing['retail_total'] ?? 0
    );
}

$order_subtotal = $order_total;

$order_discount = max(
    0,
    (float) (
        $customer_order['order_discount_amount']
        ?? 0
    )
);

$delivery_method = trim(
    (string) (
        $customer_order['delivery_method']
        ?? 'Pickup'
    )
);

$is_shipping = strcasecmp(
    $delivery_method,
    'Shipping'
) === 0;

$shipping_amount = $is_shipping
    ? max(
        0,
        (float) (
            $customer_order['order_shipping_amount']
            ?? 0
        )
    )
    : 0.00;

$paid_amount = max(
    0,
    (float) (
        $customer_order['paid_amount']
        ?? 0
    )
);

$customer_total =
    max(0, $order_subtotal - $order_discount)
    + $shipping_amount;

$order_balance = max(
    0,
    $customer_total - $paid_amount
);

if (!empty($customer_order['is_gift'])) {
    $customer_total = 0.00;
    $order_balance = 0.00;
}

$approval_image_positions =
    sparrow_get_approval_image_positions();

$approval_images =
    sparrow_get_order_approval_images($order_id);

/*
 * Preserve the original single approval image for older orders.
 * It is used only when no labeled images have been uploaded.
 */
$legacy_approval_image = trim(
    (string) ($customer_order['approval_image'] ?? '')
);

if (
    empty($approval_images)
    && $legacy_approval_image !== ''
) {
    $approval_images['legacy'] = [
        'image_position' => 'legacy',
        'image_path' => $legacy_approval_image,
    ];
}

$approval_status = trim(
    (string) ($customer_order['approval_status'] ?? 'waiting')
);

$approval_notes = trim(
    (string) ($customer_order['approval_notes'] ?? '')
);

$approval_status_labels = [
    'waiting' => 'Waiting for Approval',
    'approved' => 'Approved',
    'changes_requested' => 'Changes Requested',
];

$approval_status_label = $approval_status_labels[
    $approval_status
] ?? 'Waiting for Approval';

$approval_status_class = in_array(
    $approval_status,
    ['waiting', 'approved', 'changes_requested'],
    true
)
    ? $approval_status
    : 'waiting';
$customer_approval_notes = trim(
    (string) (
        $customer_order['customer_approval_notes']
        ?? ''
    )
);

$approval_responded_at = trim(
    (string) (
        $customer_order['approval_responded_at']
        ?? ''
    )
);

$approval_response_date = '';

if ($approval_responded_at !== '') {
    $response_timestamp = strtotime(
        $approval_responded_at
    );

    if ($response_timestamp !== false) {
        $approval_response_date = date(
            'F j, Y \a\t g:i A',
            $response_timestamp
        );
    }
}
   ?>

<details
    class="customer-portal-order-card"
    id="order-<?php echo $order_id; ?>"
>
    <summary class="customer-portal-order-summary">
        <div>
            <h3>
                <?php echo sparrow_escape(
                    $customer_order['order_number']
                    ?? 'Custom Order'
                ); ?>
            </h3>

            <p>
                <?php echo sparrow_escape($formatted_date); ?>
            </p>
        </div>

        <span class="customer-portal-pill">
            <?php echo sparrow_escape($order_status); ?>
        </span>
    </summary>

    <div class="customer-portal-order-details">
        <div class="customer-portal-detail-grid">
            <section
    class="
        customer-portal-detail-box
        customer-portal-items-box
    "
>
                <h4>Order Items</h4>

                <?php if (!$order_items): ?>
                    <p>No item details are available.</p>
                <?php else: ?>
                    <div class="customer-portal-items">
                        <?php foreach ($order_items as $order_item): ?>
                            <div class="customer-portal-item">
                                <strong>
                                    <?php echo (int) (
                                        $order_item['quantity'] ?? 1
                                    ); ?>
                                    ×
                                    <?php echo sparrow_escape(
                                        $order_item['item_type']
                                        ?? 'Item'
                                    ); ?>
                                </strong>

                                <?php if (!empty($order_item['shirt_size'])): ?>
                                    <p>
                                        <strong>Size / Style:</strong>
                                        <?php echo sparrow_escape(
                                            $order_item['shirt_size']
                                        ); ?>
                                    </p>
                                <?php endif; ?>

                                <?php if (!empty($order_item['shirt_color'])): ?>
                                    <p>
                                        <strong>Color:</strong>
                                        <?php echo sparrow_escape(
                                            $order_item['shirt_color']
                                        ); ?>
                                    </p>
                                <?php endif; ?>

                                <?php if (!empty($order_item['specialty'])): ?>
                                    <p>
                                        <strong>Specialty:</strong>
                                        <?php echo sparrow_escape(
                                            $order_item['specialty']
                                        ); ?>
                                    </p>
                                <?php endif; ?>

                                <?php if (!empty($order_item['print_location'])): ?>
                                    <p>
                                        <strong>Print Location:</strong>
                                        <?php echo sparrow_escape(
                                            $order_item['print_location']
                                        ); ?>
                                    </p>
                                <?php endif; ?>

                                <?php if (!empty($order_item['item_notes'])): ?>
                                    <p>
                                        <?php echo nl2br(
                                            sparrow_escape(
                                                $order_item['item_notes']
                                            )
                                        ); ?>
                                    </p>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </section>

            <section class="customer-portal-detail-box">
    <h4>Payment Summary</h4>

    <?php if (!empty($customer_order['is_gift'])): ?>
        <p>
            <strong>Gift Order</strong><br>
            No customer payment is required.
        </p>
    <?php else: ?>
<div class="payment-calculation">
    <p>
        <strong>Merchandise Subtotal:</strong>
        <span>$<?php echo number_format($order_subtotal, 2); ?></span>
    </p>

    <?php if ($order_discount > 0): ?>
        <p>
            <strong>Customer Discount:</strong>
            <span class="payment-subtract">
                −$<?php echo number_format($order_discount, 2); ?>
            </span>
        </p>
    <?php endif; ?>

    <?php if ($shipping_amount > 0): ?>
        <p>
            <strong>Shipping:</strong>
            <span>
                +$<?php echo number_format($shipping_amount, 2); ?>
            </span>
        </p>
    <?php endif; ?>

    <p class="payment-total">
        <strong>Final Order Total:</strong>
        <span>$<?php echo number_format($customer_total, 2); ?></span>
    </p>

    <?php if ($paid_amount > 0): ?>
        <p>
            <strong>Amount Paid:</strong>
            <span class="payment-subtract">
                $<?php echo number_format($paid_amount, 2); ?>
            </span>
        </p>
    <?php endif; ?>

    <p class="payment-balance">
        <strong>Remaining Balance:</strong>
        <span>$<?php echo number_format($order_balance, 2); ?></span>
    </p>
</div>

        <?php if (!empty($customer_order['payment_method'])): ?>
            <p>
                <strong>Payment Method:</strong>
                <?php echo sparrow_escape(
                    $customer_order['payment_method']
                ); ?>
            </p>
        <?php endif; ?>
    <?php endif; ?>
</section>

<section
    class="
        customer-portal-detail-box
        customer-portal-delivery-box
    "
>
    <div class="customer-portal-delivery-header">
        <h4>Pickup / Delivery</h4>

        <span class="customer-portal-delivery-method">
            <?php echo sparrow_escape($delivery_method); ?>
        </span>
    </div>

    <?php if ($is_shipping): ?>
        <div class="customer-portal-delivery-detail">
            <strong class="customer-portal-delivery-label">
                Shipping Address
            </strong>

            <?php if (
                !empty($portal_account['shipping_address_1'])
            ): ?>
                <address>
                    <?php if (
                        !empty($portal_account['shipping_name'])
                    ): ?>
                        <?php echo sparrow_escape(
                            $portal_account['shipping_name']
                        ); ?><br>
                    <?php endif; ?>

                    <?php echo sparrow_escape(
                        $portal_account['shipping_address_1']
                    ); ?><br>

                    <?php if (
                        !empty($portal_account['shipping_address_2'])
                    ): ?>
                        <?php echo sparrow_escape(
                            $portal_account['shipping_address_2']
                        ); ?><br>
                    <?php endif; ?>

                    <?php echo sparrow_escape(
                        $portal_account['shipping_city']
                    ); ?>,
                    <?php echo sparrow_escape(
                        $portal_account['shipping_state']
                    ); ?>
                    <?php echo sparrow_escape(
                        $portal_account['shipping_postal_code']
                    ); ?>
                </address>
            <?php else: ?>
                <p>
                    No shipping address has been saved.
                    Please add one under
                    <a href="<?php echo sparrow_escape(
                        sparrow_url(
                            '/customer-portal.php'
                            . '?portal_section=addresses'
                        )
                    ); ?>">
                        Addresses
                    </a>.
                </p>
            <?php endif; ?>
        </div>
    <?php endif; ?>


        <div class="customer-portal-delivery-detail">
            <strong class="customer-portal-delivery-label">
                Delivery Notes
            </strong>

            <p>
                <?php echo nl2br(
                    sparrow_escape(
                        $customer_order['delivery_notes']
                    )
                ); ?>
            </p>
        </div>

</section>

<?php
$has_item_approvals = false;

foreach ($item_approval_images_by_item as $portal_images) {
    if (!empty($portal_images)) {
        $has_item_approvals = true;
        break;
    }
}
?>

<?php if ($has_item_approvals): ?>
    <section
        class="
            customer-portal-detail-box
            customer-portal-item-approvals-box
        "
    >
        <h4>Item Approvals</h4>

        <p>
            Please review each item’s design below.
            Each item will be approved separately.
        </p>

        <div class="customer-portal-item-approvals">
            <?php foreach (
                $order_items
                as $item_index => $order_item
            ): ?>
                <?php
                $portal_order_item_id = (int) (
                    $order_item['id'] ?? 0
                );

                $portal_item_images =
                    $item_approval_images_by_item[
                        $portal_order_item_id
                    ] ?? [];

                if (!$portal_item_images) {
                    continue;
                }

                $portal_item_status = (string) (
                    $order_item['approval_status']
                    ?? 'waiting'
                );

                $portal_item_status_labels = [
                    'waiting' => 'Waiting for Your Response',
                    'approved' => 'Approved',
                    'changes_requested' =>
                        'Changes Requested',
                ];

                $portal_item_status_label =
                    $portal_item_status_labels[
                        $portal_item_status
                    ] ?? 'Waiting for Your Response';

                $portal_item_status_class = in_array(
                    $portal_item_status,
                    [
                        'waiting',
                        'approved',
                        'changes_requested',
                    ],
                    true
                )
                    ? $portal_item_status
                    : 'waiting';
                ?>

                <div class="customer-portal-item-approval-card">
                    <h5>
                        Item <?php echo $item_index + 1; ?>:
                        <?php echo sparrow_escape(
                            $order_item['item_type']
                            ?? 'Item'
                        ); ?>
                    </h5>

                    <p>
                        <strong>Quantity:</strong>
                        <?php echo (int) (
                            $order_item['quantity'] ?? 1
                        ); ?>

                        <?php if (
                            !empty($order_item['shirt_size'])
                        ): ?>
                            |
                            <strong>Size:</strong>
                            <?php echo sparrow_escape(
                                $order_item['shirt_size']
                            ); ?>
                        <?php endif; ?>

                        <?php if (
                            !empty($order_item['shirt_color'])
                        ): ?>
                            |
                            <strong>Color:</strong>
                            <?php echo sparrow_escape(
                                $order_item['shirt_color']
                            ); ?>
                        <?php endif; ?>
                    </p>

                    <p>
                        <strong>Approval Status:</strong>

                        <span
                            class="
                                customer-portal-approval-status
                                customer-portal-approval-<?php
                                    echo sparrow_escape(
                                        $portal_item_status_class
                                    );
                                ?>
                            "
                        >
                            <?php echo sparrow_escape(
                                $portal_item_status_label
                            ); ?>
                        </span>
                    </p>

                    <?php if (
                        !empty($order_item['approval_notes'])
                    ): ?>
                        <div class="customer-portal-approval-notes">
                            <strong>Approval Notes:</strong>

                            <p>
                                <?php echo nl2br(
                                    sparrow_escape(
                                        $order_item[
                                            'approval_notes'
                                        ]
                                    )
                                ); ?>
                            </p>
                        </div>
                    <?php endif; ?>

                    <div class="customer-portal-approval-gallery">
                        <?php foreach (
                            $portal_item_images
                            as $portal_position => $portal_image
                        ): ?>
                            <?php
                            $portal_image_path = (string) (
                                $portal_image['image_path']
                                ?? ''
                            );

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

                            $portal_position_label =
                                $approval_image_positions[
                                    $portal_position
                                ]
                                ?? ucwords(
                                    str_replace(
                                        '_',
                                        ' ',
                                        $portal_position
                                    )
                                );

                            $portal_image_url = sparrow_url(
                                $portal_image_path
                            );

                            $portal_image_alt =
                                $portal_position_label
                                . ' approval image for item '
                                . ($item_index + 1);
                            ?>

                            <div class="customer-portal-approval-item">
                                <h5>
                                    <?php echo sparrow_escape(
                                        $portal_position_label
                                    ); ?>
                                </h5>

                                <button
                                    type="button"
                                    class="customer-portal-approval-button"
                                    data-approval-image="<?php
                                        echo sparrow_escape(
                                            $portal_image_url
                                        );
                                    ?>"
                                    data-approval-alt="<?php
                                        echo sparrow_escape(
                                            $portal_image_alt
                                        );
                                    ?>"
                                    aria-label="View <?php
                                        echo sparrow_escape(
                                            $portal_position_label
                                        );
                                    ?> approval image at full size"
                                >
                                    <span
                                        class="customer-portal-watermark"
                                    >
                                        Sparrow &amp; Seed Creations
                                        • PROOF
                                    </span>

                                    <img
                                        class="customer-portal-approval-image"
                                        src="<?php
                                            echo sparrow_escape(
                                                $portal_image_url
                                            );
                                        ?>"
                                        alt="<?php
                                            echo sparrow_escape(
                                                $portal_image_alt
                                            );
                                        ?>"
                                    >
                                </button>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <?php if (
                        $portal_item_status
                            === 'changes_requested'
                        && !empty(
                            $order_item[
                                'customer_approval_notes'
                            ]
                        )
                    ): ?>
                        <div class="customer-portal-approval-notes">
                            <strong>Your Requested Changes:</strong>

                            <p>
                                <?php echo nl2br(
                                    sparrow_escape(
                                        $order_item[
                                            'customer_approval_notes'
                                        ]
                                    )
                                ); ?>
                            </p>
                        </div>
                    <?php endif; ?>
					<?php if (
    $portal_item_status_class === 'waiting'
): ?>
    <div class="customer-portal-approval-actions">
        <form method="post">
            <input
                type="hidden"
                name="action"
                value="customer_item_approval_response"
            >

            <input
                type="hidden"
                name="portal_csrf"
                value="<?php echo sparrow_escape(
                    $portal_csrf
                ); ?>"
            >

            <input
                type="hidden"
                name="order_item_id"
                value="<?php echo $portal_order_item_id; ?>"
            >

            <input
                type="hidden"
                name="approval_response"
                value="approved"
            >

            <button
                type="submit"
                class="
                    customer-portal-approval-action
                    customer-portal-approve-button
                "
                onclick="return confirm(
                    'Are you ready to approve this item?'
                );"
            >
                Approve Item
            </button>
        </form>

        <details class="customer-portal-change-request">
            <summary>Request Changes</summary>

            <form
                method="post"
                class="customer-portal-change-form"
            >
                <input
                    type="hidden"
                    name="action"
                    value="customer_item_approval_response"
                >

                <input
                    type="hidden"
                    name="portal_csrf"
                    value="<?php echo sparrow_escape(
                        $portal_csrf
                    ); ?>"
                >

                <input
                    type="hidden"
                    name="order_item_id"
                    value="<?php echo $portal_order_item_id; ?>"
                >

                <input
                    type="hidden"
                    name="approval_response"
                    value="changes_requested"
                >

                <label
                    for="item-change-notes-<?php
                        echo $portal_order_item_id;
                    ?>"
                >
                    What would you like changed?
                </label>

                <textarea
                    id="item-change-notes-<?php
                        echo $portal_order_item_id;
                    ?>"
                    name="customer_approval_notes"
                    maxlength="2000"
                    required
                ></textarea>

                <button
                    type="submit"
                    class="
                        customer-portal-approval-action
                        customer-portal-send-change-button
                    "
                >
                    Send Change Request
                </button>
            </form>
        </details>
    </div>
<?php else: ?>
    <?php
    $portal_item_response_date = '';

    if (!empty($order_item['approval_responded_at'])) {
        $portal_item_response_timestamp = strtotime(
            (string) $order_item[
                'approval_responded_at'
            ]
        );

        if ($portal_item_response_timestamp !== false) {
            $portal_item_response_date = date(
                'F j, Y \a\t g:i A',
                $portal_item_response_timestamp
            );
        }
    }
    ?>

    <div class="customer-portal-customer-response">
        <?php if (
            $portal_item_status_class === 'approved'
        ): ?>
            <strong>You approved this item.</strong>
        <?php else: ?>
            <strong>You requested changes to this item.</strong>
        <?php endif; ?>

        <?php if (
            $portal_item_response_date !== ''
        ): ?>
            <p>
                Submitted
                <?php echo sparrow_escape(
                    $portal_item_response_date
                ); ?>
            </p>
        <?php endif; ?>
    </div>
<?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </section>
<?php endif; ?>
			
			<?php if (!empty($approval_images)): ?>
    <section
        class="
            customer-portal-detail-box
            customer-portal-approval-box
        "
    >
        <div class="customer-portal-approval-header">
            <h4>Design Approval</h4>

            <span
                class="
                    customer-portal-approval-status
                    customer-portal-approval-<?php
                        echo sparrow_escape(
                            $approval_status_class
                        );
                    ?>
                "
            >
                <?php echo sparrow_escape(
                    $approval_status_label
                ); ?>
            </span>
        </div>

<div class="customer-portal-approval-gallery">
    <?php foreach (
        $approval_images
        as $image_position => $approval_image_data
    ): ?>
        <?php
        $position_label = $image_position === 'legacy'
            ? 'Design'
            : (
                $approval_image_positions[$image_position]
                ?? ucwords(
                    str_replace('_', ' ', $image_position)
                )
            );

        $image_url = sparrow_url(
            $approval_image_data['image_path']
        );

        $image_alt =
            $position_label
            . ' approval design for '
            . (
                $customer_order['order_number']
                ?? 'custom order'
            );
        ?>

        <div class="customer-portal-approval-item">
            <h5>
                <?php echo sparrow_escape($position_label); ?>
            </h5>

            <button
                type="button"
                class="customer-portal-approval-button"
                data-approval-image="<?php echo sparrow_escape(
                    $image_url
                ); ?>"
                data-approval-alt="<?php echo sparrow_escape(
                    $image_alt
                ); ?>"
                aria-label="View <?php echo sparrow_escape(
                    $position_label
                ); ?> approval image at full size"
            >
			<span class="customer-portal-watermark">
    Sparrow &amp; Seed Creations • PROOF
</span>
                <img
                    class="customer-portal-approval-image"
                    src="<?php echo sparrow_escape(
                        $image_url
                    ); ?>"
                    alt="<?php echo sparrow_escape(
                        $image_alt
                    ); ?>"
                >
            </button>
        </div>
    <?php endforeach; ?>
</div>

        <?php if ($approval_notes !== ''): ?>
            <div class="customer-portal-approval-notes">
                <strong>Approval Notes:</strong>

                <p>
                    <?php echo nl2br(
                        sparrow_escape($approval_notes)
                    ); ?>
                </p>
            </div>
        <?php endif; ?>

        <p>Select the image to enlarge it.</p>
		
		<?php if ($approval_status_class === 'waiting'): ?>
    <div class="customer-portal-approval-actions">
        <form method="post">
            <input
                type="hidden"
                name="action"
                value="customer_approval_response"
            >

            <input
                type="hidden"
                name="portal_csrf"
                value="<?php echo sparrow_escape($portal_csrf); ?>"
            >

            <input
                type="hidden"
                name="order_id"
                value="<?php echo $order_id; ?>"
            >

            <input
                type="hidden"
                name="approval_response"
                value="approved"
            >

            <button
                type="submit"
                class="
                    customer-portal-approval-action
                    customer-portal-approve-button
                "
                onclick="return confirm(
                    'Are you ready to approve this design?'
                );"
            >
                Approve Design
            </button>
        </form>

        <details class="customer-portal-change-request">
            <summary>Request Changes</summary>

            <form
                method="post"
                class="customer-portal-change-form"
            >
                <input
                    type="hidden"
                    name="action"
                    value="customer_approval_response"
                >

                <input
                    type="hidden"
                    name="portal_csrf"
                    value="<?php echo sparrow_escape($portal_csrf); ?>"
                >

                <input
                    type="hidden"
                    name="order_id"
                    value="<?php echo $order_id; ?>"
                >

                <input
                    type="hidden"
                    name="approval_response"
                    value="changes_requested"
                >

                <label
                    for="customer-approval-notes-<?php echo $order_id; ?>"
                >
                    What would you like changed?
                </label>

<textarea
    id="customer-approval-notes-<?php echo $order_id; ?>"
    name="customer_approval_notes"
    maxlength="2000"
    required
></textarea>

<button
    type="submit"
    class="
        customer-portal-approval-action
        customer-portal-send-change-button
    "
>
    Send Change Request
</button>
</form>
        </details>
    </div>
<?php else: ?>
    <div class="customer-portal-customer-response">
        <?php if ($approval_status_class === 'approved'): ?>
            <strong>You approved this design.</strong>
        <?php else: ?>
            <strong>You requested changes.</strong>

            <?php if ($customer_approval_notes !== ''): ?>
                <p>
                    <?php echo nl2br(
                        sparrow_escape(
                            $customer_approval_notes
                        )
                    ); ?>
                </p>
            <?php endif; ?>
        <?php endif; ?>

        <?php if ($approval_response_date !== ''): ?>
            <p>
                Submitted
                <?php echo sparrow_escape(
                    $approval_response_date
                ); ?>
            </p>
        <?php endif; ?>
    </div>
<?php endif; ?>
    </section>
<?php endif; ?>

            <?php if (!empty($customer_order['notes'])): ?>
                <section class="customer-portal-detail-box">
                    <h4>Order Notes</h4>

                    <p>
                        <?php echo nl2br(
                            sparrow_escape(
                                $customer_order['notes']
                            )
                        ); ?>
                    </p>
                </section>
            <?php endif; ?>
        </div>
    </div>
</details>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</section>

<?php elseif ($portal_section === 'payments'): ?>
    <?php
    /*
     * Calculate the customer's payment totals.
     */
    $portal_order_total = 0.00;
    $portal_paid_total = 0.00;

    foreach ($customer_orders as $payment_order) {
        if (!empty($payment_order['is_gift'])) {
            continue;
        }

        $payment_order_id = (int) (
            $payment_order['id'] ?? 0
        );

        $payment_order_total = (float) (
            $payment_order['total_amount'] ?? 0
        );

        if (
            $payment_order_total <= 0
            && $payment_order_id > 0
            && function_exists(
                'sparrow_calculate_order_pricing_from_lookup'
            )
        ) {
            $payment_pricing =
                sparrow_calculate_order_pricing_from_lookup(
                    $payment_order_id
                );

            $payment_order_total = (float) (
                $payment_pricing['retail_total'] ?? 0
            );
        }

        $payment_discount = (float) (
            $payment_order['order_discount_amount'] ?? 0
        );

        $portal_order_total += max(
            0,
            $payment_order_total - $payment_discount
        );

        $portal_paid_total += max(
            0,
            (float) ($payment_order['paid_amount'] ?? 0)
        );
    }
    ?>

    <section class="customer-portal-main-card">
        <h2>Payments</h2>

        <p>
            Review your order totals, recorded payments, and
            remaining balances.
        </p>

        <div class="customer-portal-summary-row">
            <div class="customer-portal-summary-box">
                <span>Order Total</span>

                <strong>
                    $<?php echo number_format(
                        $portal_order_total,
                        2
                    ); ?>
                </strong>
            </div>

            <div class="customer-portal-summary-box">
                <span>Paid</span>

                <strong>
                    $<?php echo number_format(
                        $portal_paid_total,
                        2
                    ); ?>
                </strong>
            </div>

            <div class="customer-portal-summary-box">
                <span>Balance</span>

                <strong>
                    $<?php echo number_format(
                        $total_balance,
                        2
                    ); ?>
                </strong>
            </div>
        </div>
    </section>

<section class="customer-portal-main-card">
    <h2>Payment Details</h2>

    <?php if (!$customer_orders): ?>
        <p>No order payment information is available yet.</p>
    <?php else: ?>
        <div class="customer-portal-order-list">
            <?php foreach ($customer_orders as $payment_order): ?>
                <?php
                $payment_order_id = (int) (
                    $payment_order['id'] ?? 0
                );

                $payment_order_number = trim(
                    (string) (
                        $payment_order['order_number']
                        ?? 'Custom Order'
                    )
                );

                $payment_order_date = trim(
                    (string) (
                        $payment_order['order_date'] ?? ''
                    )
                );

                $payment_date_timestamp =
                    $payment_order_date !== ''
                        ? strtotime($payment_order_date)
                        : false;

                $formatted_payment_date =
                    $payment_date_timestamp
                        ? date(
                            'F j, Y',
                            $payment_date_timestamp
                        )
                        : 'Date not available';

                $payment_order_total = max(
                    0,
                    (float) (
                        $payment_order['total_amount'] ?? 0
                    )
                );

                if (
                    $payment_order_total <= 0
                    && $payment_order_id > 0
                    && function_exists(
                        'sparrow_calculate_order_pricing_from_lookup'
                    )
                ) {
                    $payment_pricing =
                        sparrow_calculate_order_pricing_from_lookup(
                            $payment_order_id
                        );

                    $payment_order_total = max(
                        0,
                        (float) (
                            $payment_pricing['retail_total'] ?? 0
                        )
                    );
                }

                $payment_discount = max(
                    0,
                    (float) (
                        $payment_order[
                            'order_discount_amount'
                        ] ?? 0
                    )
                );

                $payment_delivery_method = trim(
                    (string) (
                        $payment_order['delivery_method']
                        ?? 'Pickup'
                    )
                );

                $payment_is_shipping = strcasecmp(
                    $payment_delivery_method,
                    'Shipping'
                ) === 0;

                $payment_shipping = $payment_is_shipping
                    ? max(
                        0,
                        (float) (
                            $payment_order[
                                'order_shipping_amount'
                            ] ?? 0
                        )
                    )
                    : 0.00;

                $payment_customer_total =
                    max(
                        0,
                        $payment_order_total
                        - $payment_discount
                    )
                    + $payment_shipping;

                $payment_paid = max(
                    0,
                    (float) (
                        $payment_order['paid_amount'] ?? 0
                    )
                );

                $payment_balance = !empty(
                    $payment_order['is_gift']
                )
                    ? 0.00
                    : max(
                        0,
                        $payment_customer_total
                        - $payment_paid
                    );

                if (!empty($payment_order['is_gift'])) {
                    $payment_label = 'Gift';
                } elseif ($payment_balance <= 0) {
                    $payment_label = 'Paid';
                } elseif ($payment_paid > 0) {
                    $payment_label = 'Partially Paid';
                } else {
                    $payment_label = 'Payment Due';
                }
                ?>

                <section
    class="
        customer-portal-detail-box
        customer-portal-payment-card
    "
>
                    <div class="customer-portal-payment-header">
                        <div>
                            <h4>
                                <?php echo sparrow_escape(
                                    $payment_order_number
                                ); ?>
                            </h4>

                            <span
                                class="customer-portal-payment-date"
                            >
                                <?php echo sparrow_escape(
                                    $formatted_payment_date
                                ); ?>
                            </span>
                        </div>

                        <span
                            class="customer-portal-payment-status"
                        >
                            <?php echo sparrow_escape(
                                $payment_label
                            ); ?>
                        </span>
                    </div>

                    <?php if (
                        !empty($payment_order['is_gift'])
                    ): ?>
                        <div
                            class="customer-portal-payment-message"
                        >
                            This is a gift order. No customer
                            payment is required.
                        </div>
                    <?php else: ?>
                        <div
                            class="
                                customer-portal-payment-calculation
                            "
                        >
                            <p>
                                <strong>
                                    Merchandise Subtotal
                                </strong>

                                <span>
                                    $<?php echo number_format(
                                        $payment_order_total,
                                        2
                                    ); ?>
                                </span>
                            </p>

                            <?php if (
                                $payment_discount > 0
                            ): ?>
                                <p>
                                    <strong>
                                        Customer Discount
                                    </strong>

                                    <span class="payment-subtract">
                                        −$<?php echo number_format(
                                            $payment_discount,
                                            2
                                        ); ?>
                                    </span>
                                </p>
                            <?php endif; ?>

                            <?php if (
                                $payment_shipping > 0
                            ): ?>
                                <p>
                                    <strong>Shipping</strong>

                                    <span>
                                        +$<?php echo number_format(
                                            $payment_shipping,
                                            2
                                        ); ?>
                                    </span>
                                </p>
                            <?php endif; ?>

                            <p
                                class="
                                    customer-portal-payment-total
                                "
                            >
                                <strong>Final Order Total</strong>

                                <span>
                                    $<?php echo number_format(
                                        $payment_customer_total,
                                        2
                                    ); ?>
                                </span>
                            </p>

                            <?php if ($payment_paid > 0): ?>
                                <p>
                                    <strong>Amount Paid</strong>

                                    <span>
                                        $<?php echo number_format(
                                            $payment_paid,
                                            2
                                        ); ?>
                                    </span>
                                </p>
                            <?php endif; ?>
                        </div>

                        <?php if ($payment_balance > 0): ?>
                            <div
                                class="
                                    customer-portal-payment-balance
                                    is-due
                                "
                            >
                                <strong>Remaining Balance</strong>

                                <span>
                                    $<?php echo number_format(
                                        $payment_balance,
                                        2
                                    ); ?>
                                </span>
                            </div>
                        <?php else: ?>
                            <div
                                class="
                                    customer-portal-payment-balance
                                    is-paid
                                "
                            >
                                <strong>Payment Status</strong>
                                <span>Paid in Full</span>
                            </div>
                        <?php endif; ?>

                        <?php if (
                            !empty(
                                $payment_order['payment_method']
                            )
                        ): ?>
                            <div
                                class="
                                    customer-portal-payment-method
                                "
                            >
                                <strong>Payment Method:</strong>

                                <?php echo sparrow_escape(
                                    $payment_order[
                                        'payment_method'
                                    ]
                                ); ?>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                </section>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</section>

<?php elseif ($portal_section === 'addresses'): ?>
<section class="customer-portal-main-card">
    <h2>Addresses</h2>

    <p>
        Add or update the billing and shipping addresses
        connected to your account.
    </p>

    <?php if ($address_error !== ''): ?>
        <div
            class="
                customer-portal-message
                customer-portal-message-error
            "
        >
            <?php echo sparrow_escape($address_error); ?>
        </div>
    <?php endif; ?>

    <form
        class="customer-portal-address-form"
        method="post"
        action="<?php echo sparrow_escape(
            sparrow_url(
                '/customer-portal.php'
                . '?portal_section=addresses'
            )
        ); ?>"
    >
        <input
            type="hidden"
            name="action"
            value="update_portal_addresses"
        >

        <input
            type="hidden"
            name="portal_csrf"
            value="<?php echo sparrow_escape($portal_csrf); ?>"
        >

        <div class="customer-portal-address-grid">
            <section class="customer-portal-address-card">
                <h3>Billing Address</h3>

                <label>
                    Full Name

                    <input
                        type="text"
                        name="billing_name"
                        maxlength="150"
                        autocomplete="billing name"
                        value="<?php echo sparrow_escape(
                            $address_values['billing_name']
                        ); ?>"
                        required
                    >
                </label>

                <label>
                    Address Line 1

                    <input
                        type="text"
                        name="billing_address_1"
                        maxlength="190"
                        autocomplete="billing address-line1"
                        value="<?php echo sparrow_escape(
                            $address_values[
                                'billing_address_1'
                            ]
                        ); ?>"
                        required
                    >
                </label>

                <label>
                    Address Line 2

                    <input
                        type="text"
                        name="billing_address_2"
                        maxlength="190"
                        autocomplete="billing address-line2"
                        value="<?php echo sparrow_escape(
                            $address_values[
                                'billing_address_2'
                            ]
                        ); ?>"
                        placeholder="Apartment, suite, etc."
                    >
                </label>

                <label>
                    City

                    <input
                        type="text"
                        name="billing_city"
                        maxlength="100"
                        autocomplete="billing address-level2"
                        value="<?php echo sparrow_escape(
                            $address_values['billing_city']
                        ); ?>"
                        required
                    >
                </label>

                <div class="customer-portal-address-row">
                    <label>
                        State

                        <input
                            type="text"
                            name="billing_state"
                            maxlength="100"
                            autocomplete="billing address-level1"
                            value="<?php echo sparrow_escape(
                                $address_values[
                                    'billing_state'
                                ]
                            ); ?>"
                            required
                        >
                    </label>

                    <label>
                        ZIP Code

                        <input
                            type="text"
                            name="billing_postal_code"
                            maxlength="20"
                            autocomplete="billing postal-code"
                            value="<?php echo sparrow_escape(
                                $address_values[
                                    'billing_postal_code'
                                ]
                            ); ?>"
                            required
                        >
                    </label>
                </div>
            </section>

            <section class="customer-portal-address-card">
                <h3>Shipping Address</h3>

                <label
                    class="
                        customer-portal-address-checkbox
                    "
                >
                    <input
                        type="checkbox"
                        name="shipping_same_as_billing"
                        value="1"
                        <?php echo $shipping_same_as_billing
                            ? 'checked'
                            : ''; ?>
                    >

                    <span>
                        Shipping address is the same as
                        billing address
                    </span>
                </label>

                <p class="customer-portal-address-help">
                    When checked, the billing address will
                    also be saved as the shipping address.
                </p>

                <label>
                    Full Name

                    <input
                        type="text"
                        name="shipping_name"
                        maxlength="150"
                        autocomplete="shipping name"
                        value="<?php echo sparrow_escape(
                            $address_values['shipping_name']
                        ); ?>"
                    >
                </label>

                <label>
                    Address Line 1

                    <input
                        type="text"
                        name="shipping_address_1"
                        maxlength="190"
                        autocomplete="shipping address-line1"
                        value="<?php echo sparrow_escape(
                            $address_values[
                                'shipping_address_1'
                            ]
                        ); ?>"
                    >
                </label>

                <label>
                    Address Line 2

                    <input
                        type="text"
                        name="shipping_address_2"
                        maxlength="190"
                        autocomplete="shipping address-line2"
                        value="<?php echo sparrow_escape(
                            $address_values[
                                'shipping_address_2'
                            ]
                        ); ?>"
                        placeholder="Apartment, suite, etc."
                    >
                </label>

                <label>
                    City

                    <input
                        type="text"
                        name="shipping_city"
                        maxlength="100"
                        autocomplete="shipping address-level2"
                        value="<?php echo sparrow_escape(
                            $address_values['shipping_city']
                        ); ?>"
                    >
                </label>

                <div class="customer-portal-address-row">
                    <label>
                        State

                        <input
                            type="text"
                            name="shipping_state"
                            maxlength="100"
                            autocomplete="shipping address-level1"
                            value="<?php echo sparrow_escape(
                                $address_values[
                                    'shipping_state'
                                ]
                            ); ?>"
                        >
                    </label>

                    <label>
                        ZIP Code

                        <input
                            type="text"
                            name="shipping_postal_code"
                            maxlength="20"
                            autocomplete="shipping postal-code"
                            value="<?php echo sparrow_escape(
                                $address_values[
                                    'shipping_postal_code'
                                ]
                            ); ?>"
                        >
                    </label>
                </div>
            </section>
        </div>

        <div class="customer-portal-address-actions">
            <button
                class="customer-portal-address-save"
                type="submit"
            >
                Save Addresses
            </button>
        </div>
    </form>
</section>

<?php elseif ($portal_section === 'account'): ?>
<section class="customer-portal-main-card">
    <h2>Account Details</h2>

    <p>
    Review your account information and update your
    contact email.
</p>

    <?php if ($account_error !== ''): ?>
        <div
            class="
                customer-portal-message
                customer-portal-message-error
            "
        >
            <?php echo sparrow_escape($account_error); ?>
        </div>
    <?php endif; ?>

    <form
        class="customer-portal-account-form"
        method="post"
        action="<?php echo sparrow_escape(
            sparrow_url(
                '/customer-portal.php'
                . '?portal_section=account'
            )
        ); ?>"
    >
        <input
            type="hidden"
            name="action"
            value="update_portal_account"
        >

        <input
            type="hidden"
            name="portal_csrf"
            value="<?php echo sparrow_escape(
                $portal_csrf
            ); ?>"
        >

        <div class="customer-portal-account-fields">
            <label>
                Customer Name

                <input
                    type="text"
                    value="<?php echo sparrow_escape(
                        $customer_name
                    ); ?>"
                    disabled
                >
            </label>

            <label>
                Username

                <input
                    type="text"
                    value="<?php echo sparrow_escape(
                        $portal_account['username'] ?? ''
                    ); ?>"
                    disabled
                >
            </label>

            <label>
                Email Address

                <input
                    type="email"
                    name="account_email"
                    maxlength="190"
                    autocomplete="email"
                    value="<?php echo sparrow_escape(
                        $account_email_value
                    ); ?>"
                >
            </label>
        </div>

        <p class="customer-portal-account-help">
            Your customer name and username are connected to
            your existing orders and cannot be changed here.
			 If your name is misspelled or needs
    to be changed, please use the
    <a href="<?php echo sparrow_escape(
        sparrow_url('/contact.php')
    ); ?>">
        Contact Form</a> 
		and tell me what it should be changed to. Proof may
    be required for a legal name change.
        </p>

        <div class="customer-portal-account-actions">
            <button
                class="customer-portal-account-save"
                type="submit"
            >
                Save Account Details
            </button>
        </div>
    </form>
	</section>

        <section class="customer-portal-password-card">
            <h3>Change Password</h3>

            <p>
                Enter your current password before choosing a
                new password.
            </p>

            <?php if ($password_error !== ''): ?>
                <div
                    class="
                        customer-portal-message
                        customer-portal-message-error
                    "
                >
                    <?php echo sparrow_escape(
                        $password_error
                    ); ?>
                </div>
            <?php endif; ?>
            <form
                class="customer-portal-password-form"
                method="post"
                action="<?php echo sparrow_escape(
                    sparrow_url(
                        '/customer-portal.php'
                        . '?portal_section=account'
                    )
                ); ?>"
            >
                <input
                    type="hidden"
                    name="action"
                    value="change_portal_password"
                >

                <input
                    type="hidden"
                    name="portal_csrf"
                    value="<?php echo sparrow_escape(
                        $portal_csrf
                    ); ?>"
                >

                <div class="customer-portal-password-fields">
                    <label>
                        Current Password

                        <input
                            type="password"
                            name="current_password"
                            autocomplete="current-password"
                            required
                        >
                    </label>

                    <label>
                        New Password

                        <input
                            type="password"
                            name="new_password"
                            minlength="8"
                            maxlength="72"
                            autocomplete="new-password"
                            required
                        >
                    </label>

                    <label>
                        Confirm New Password

                        <input
                            type="password"
                            name="confirm_password"
                            minlength="8"
                            maxlength="72"
                            autocomplete="new-password"
                            required
                        >
                    </label>
                </div>

                <p class="customer-portal-password-help">
                    Your new password must contain at least
                    8 characters and must be different from
                    your current password.
                </p>

                <div class="customer-portal-password-actions">
                    <button
                        class="customer-portal-password-save"
                        type="submit"
                    >
                        Change Password
                    </button>
                </div>
            </form>
        </section>
    </section>
</section>
<?php endif; ?>

    </main>
</section>

<dialog
    class="customer-portal-approval-lightbox"
    id="approval-lightbox"
>
    <button
        type="button"
        class="customer-portal-lightbox-close"
        id="approval-lightbox-close"
    >
        Close
    </button>

<div class="customer-portal-watermarked-image">
    <img
        class="customer-portal-lightbox-image"
        id="approval-lightbox-image"
        src=""
        alt=""
    >

    <span class="customer-portal-watermark">
        Sparrow &amp; Seed Creations • PROOF
    </span>
</div>
</dialog>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const requestedOrder = window.location.hash
        ? document.querySelector(window.location.hash)
        : null;

    if (
        requestedOrder
        && requestedOrder.matches(
            'details.customer-portal-order-card'
        )
    ) {
        requestedOrder.open = true;
    }

    const lightbox = document.getElementById('approval-lightbox');
    const lightboxImage = document.getElementById(
        'approval-lightbox-image'
    );
    const closeButton = document.getElementById(
        'approval-lightbox-close'
    );

    if (!lightbox || !lightboxImage || !closeButton) {
        return;
    }

    document.querySelectorAll(
        '.customer-portal-approval-button'
    ).forEach(function (button) {
        button.addEventListener('click', function () {
            lightboxImage.src = button.dataset.approvalImage || '';
            lightboxImage.alt = button.dataset.approvalAlt || '';

            lightbox.showModal();
        });
    });

    closeButton.addEventListener('click', function () {
        lightbox.close();
    });

    lightbox.addEventListener('click', function (event) {
        if (event.target === lightbox) {
            lightbox.close();
        }
    });

    lightbox.addEventListener('close', function () {
        lightboxImage.src = '';
        lightboxImage.alt = '';
    });
});
</script>

<?php sparrow_public_footer(); ?>
