<?php

require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/customers.php';

$user = sparrow_require_backyard_login();

$customer_keys = [];

/*
 * Single customer history.
 */
$customer_key = trim(
    (string) ($_GET['key'] ?? '')
);

if ($customer_key !== '') {
    $customer_key = sparrow_resolve_customer_key(
        $customer_key
    );

    if ($customer_key !== '') {
        $customer_keys[] = $customer_key;
    }
}

/*
 * Bulk customer histories selected
 * from dashboard order checkboxes.
 */
$order_ids_raw = trim(
    (string) ($_GET['order_ids'] ?? '')
);

if ($order_ids_raw !== '') {
    $order_ids = array_values(
        array_unique(
            array_filter(
                array_map(
                    'intval',
                    explode(',', $order_ids_raw)
                )
            )
        )
    );

    foreach ($order_ids as $order_id) {
        $selected_order = sparrow_get_order(
            $order_id
        );

        if (!$selected_order) {
            continue;
        }

        $selected_customer_key =
            sparrow_customer_key_from_order(
                $selected_order
            );

        $selected_customer_key =
            sparrow_resolve_customer_key(
                $selected_customer_key
            );

        if ($selected_customer_key !== '') {
            $customer_keys[] =
                $selected_customer_key;
        }
    }
}

$customer_keys = array_values(
    array_unique($customer_keys)
);

if (!$customer_keys) {
    sparrow_redirect('/backyard/customers.php');
}

$is_bulk = count($customer_keys) > 1;

$customer_histories = [];

foreach ($customer_keys as $customer_key) {
    $orders = sparrow_get_customer_orders_by_key(
        $customer_key
    );

    if (!$orders) {
        continue;
    }

    usort($orders, function ($a, $b) {
        $date_a = strtotime(
            (string) ($a['order_date'] ?? '')
        );

        $date_b = strtotime(
            (string) ($b['order_date'] ?? '')
        );

        if ($date_a === $date_b) {
            return (int) ($a['id'] ?? 0)
                <=> (int) ($b['id'] ?? 0);
        }

        return $date_a <=> $date_b;
    });

$customer_profile =
    sparrow_get_customer_profile(
        $customer_key
    );

$first_order = $orders[0];

$total_ordered = 0.00;
$total_paid = 0.00;
$total_balance = 0.00;
$total_blessings = 0.00;
$active_orders = 0;
$delivered_orders = 0;

foreach ($orders as $order) {
    $order_total = (float) (
        $order['total_amount'] ?? 0
    );

    $paid = (float) (
        $order['paid_amount'] ?? 0
    );

    $blessing = (float) (
        $order['blessing_amount'] ?? 0
    );

    $balance =
        sparrow_customer_order_balance(
            $order
        );

    $total_ordered += $order_total;
    $total_paid += $paid;
    $total_balance += $balance;
    $total_blessings += $blessing;

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

    if (
        in_array(
            $status,
            [
                'Delivered',
                'Completed',
                'Complete'
            ],
            true
        )
    ) {
        $delivered_orders++;
    } else {
        $active_orders++;
    }
}

$customer_histories[] = [
    'customer_key' => $customer_key,
    'orders' => $orders,

    'customer_name' => trim(
        (string) (
            $first_order['customer_name']
            ?? 'Unknown Customer'
        )
    ),

    'customer_phone' =>
        sparrow_format_phone_number(
            $first_order[
                'customer_phone'
            ] ?? ''
        ),

    'customer_email' => trim(
        (string) (
            $first_order[
                'customer_email'
            ] ?? ''
        )
    ),

    'customer_notes' => trim(
        (string) (
            $customer_profile[
                'customer_notes'
            ] ?? ''
        )
    ),

    'total_ordered' => $total_ordered,
    'total_paid' => $total_paid,
    'total_balance' => $total_balance,
    'total_blessings' =>
        $total_blessings,
    'active_orders' =>
        $active_orders,
    'delivered_orders' =>
        $delivered_orders,
];

}

if (!$customer_histories) {
    sparrow_redirect(
        '/backyard/customers.php'
    );
}

$page_title = $is_bulk
    ? 'Customer Histories'
    : 'Customer History - '
        . $customer_histories[0][
            'customer_name'
        ];

sparrow_backyard_header(
    $page_title
);
?>

<body class="customer-print-page">

<div class="print-page">

    <div class="print-actions">
<?php if ($is_bulk): ?>
    <a
        class="button"
        href="<?= sparrow_escape(
            sparrow_url(
                '/backyard/dashboard.php'
            )
        ) ?>"
    >
        Back to Dashboard
    </a>
<?php else: ?>
    <a
        class="button"
        href="<?= sparrow_escape(
            sparrow_url(
                '/backyard/customer-view.php?key='
                . urlencode($customer_key)
            )
        ) ?>"
    >
        Back to Customer
    </a>
<?php endif; ?>

        <button
            type="button"
            class="button"
            onclick="window.print();"
        >
            <?= $is_bulk
    ? 'Print Customer Histories'
    : 'Print Customer History' ?>
        </button>
    </div>
	
	<?php foreach (
    $customer_histories as $history_index => $history
): ?>

<?php
$customer_key =
    $history['customer_key'];

$orders =
    $history['orders'];

$customer_name =
    $history['customer_name'];

$customer_phone =
    $history['customer_phone'];

$customer_email =
    $history['customer_email'];

$customer_notes =
    $history['customer_notes'];

$total_ordered =
    $history['total_ordered'];

$total_paid =
    $history['total_paid'];

$total_balance =
    $history['total_balance'];

$total_blessings =
    $history['total_blessings'];

$active_orders =
    $history['active_orders'];

$delivered_orders =
    $history['delivered_orders'];
?>

<div
    class="customer-history-block
    <?= $history_index > 0
        ? 'customer-history-new-page'
        : '' ?>"
>

    <section class="section">
        <h2>Customer Information</h2>

        <div class="customer-grid">
            <div class="customer-field">
                <span class="label">
                    Customer
                </span>

                <span class="value">
                    <?= sparrow_escape(
                        $customer_name
                    ) ?>
                </span>
            </div>

            <div class="customer-field">
                <span class="label">
                    Phone
                </span>

                <span class="value">
                    <?= sparrow_escape(
                        $customer_phone
                    ) ?>
                </span>
            </div>

            <div class="customer-field">
                <span class="label">
                    Email
                </span>

                <span class="value">
                    <?= sparrow_escape(
                        $customer_email
                    ) ?>
                </span>
            </div>
        </div>
    </section>

    <section class="section">
        <h2>Customer Summary</h2>

        <div class="kpi-grid">
            <div class="kpi">
                <span>Total Ordered</span>
                <strong>
                    $<?= number_format(
                        $total_ordered,
                        2
                    ) ?>
                </strong>
            </div>

            <div class="kpi">
                <span>Paid</span>
                <strong>
                    $<?= number_format(
                        $total_paid,
                        2
                    ) ?>
                </strong>
            </div>

            <div class="kpi">
                <span>Balance</span>
                <strong>
                    $<?= number_format(
                        $total_balance,
                        2
                    ) ?>
                </strong>
            </div>

            <div class="kpi">
                <span>Blessings</span>
                <strong>
                    $<?= number_format(
                        $total_blessings,
                        2
                    ) ?>
                </strong>
            </div>

            <div class="kpi">
                <span>Active Orders</span>
                <strong>
                    <?= number_format(
                        $active_orders
                    ) ?>
                </strong>
            </div>

            <div class="kpi">
                <span>Delivered</span>
                <strong>
                    <?= number_format(
                        $delivered_orders
                    ) ?>
                </strong>
            </div>
        </div>
    </section>

<?php if ($customer_notes !== ''): ?>
    <section class="section">
        <h2>Internal Customer Notes</h2>

        <div class="notes-box">
            <?= nl2br(
                sparrow_escape(
                    $customer_notes
                )
            ) ?>
        </div>
    </section>
<?php endif; ?>

    <section class="section">
        <h2>Complete Order History</h2>

        <?php foreach ($orders as $order): ?>
            <?php
            $order_id = (int) (
                $order['id'] ?? 0
            );

            $order_items =
                sparrow_get_order_items(
                    $order_id
                );

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

            $paid = (float) (
                $order['paid_amount'] ?? 0
            );

            $discount = (float) (
                $order[
                    'order_discount_amount'
                ] ?? 0
            );

            $balance =
                sparrow_customer_order_balance(
                    $order
                );
            ?>

            <article class="order-card">
                <div class="order-heading">
                    <h3>
                        <?= sparrow_escape(
                            $order[
                                'order_number'
                            ] ?? ''
                        ) ?>
                    </h3>

                    <div class="order-date">
                        <?= sparrow_escape(
                            $order[
                                'order_date'
                            ] ?? ''
                        ) ?>
                    </div>
                </div>

                <div class="order-summary">
                    <div>
                        <span class="label">
                            Status
                        </span>

                        <?= sparrow_escape(
                            $order['status'] ?? ''
                        ) ?>
                    </div>

                    <div>
                        <span class="label">
                            Total
                        </span>

                        $<?= number_format(
                            $order_total,
                            2
                        ) ?>
                    </div>

                    <div>
                        <span class="label">
                            Paid
                        </span>

                        $<?= number_format(
                            $paid,
                            2
                        ) ?>
                    </div>

                    <div>
                        <span class="label">
                            Balance
                        </span>

                        $<?= number_format(
                            $balance,
                            2
                        ) ?>
                    </div>
                </div>

                <?php if ($discount > 0): ?>
                    <p>
                        <strong>
                            Order Discount:
                        </strong>

                        $<?= number_format(
                            $discount,
                            2
                        ) ?>
                    </p>
                <?php endif; ?>

                <?php if ($order_items): ?>
                    <table>
                        <thead>
                            <tr>
                                <th>Qty</th>
                                <th>Item</th>
                                <th>Size</th>
                                <th>Color</th>
                                <th>Print</th>
                                <th>Notes</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php foreach (
                                $order_items as $item
                            ): ?>
                                <tr>
                                    <td>
                                        <?= (int) (
                                            $item[
                                                'quantity'
                                            ] ?? 1
                                        ) ?>
                                    </td>

                                    <td>
                                        <?= sparrow_escape(
                                            $item[
                                                'item_type'
                                            ] ?? ''
                                        ) ?>

                                        <?php if (
                                            !empty(
                                                $item[
                                                    'customer_supplied'
                                                ]
                                            )
                                        ): ?>
                                            <br>
                                            <small>
                                                Customer Supplied
                                            </small>
                                        <?php endif; ?>
                                    </td>

                                    <td>
                                        <?= sparrow_escape(
                                            $item[
                                                'shirt_size'
                                            ] ?? ''
                                        ) ?>
                                    </td>

                                    <td>
                                        <?= sparrow_escape(
                                            $item[
                                                'shirt_color'
                                            ] ?? ''
                                        ) ?>
                                    </td>

                                    <td>
                                        <?= sparrow_escape(
                                            $item[
                                                'print_location'
                                            ] ?? ''
                                        ) ?>
                                    </td>

                                    <td>
                                        <?= sparrow_escape(
                                            $item[
                                                'item_notes'
                                            ] ?? ''
                                        ) ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>

                <?php if (
                    trim(
                        (string) (
                            $order['notes'] ?? ''
                        )
                    ) !== ''
                ): ?>
                    <p>
                        <strong>
                            Order Notes:
                        </strong>

                        <?= nl2br(
                            sparrow_escape(
                                $order['notes']
                            )
                        ) ?>
                    </p>
                <?php endif; ?>

                <?php if (
                    trim(
                        (string) (
                            $order[
                                'admin_notes'
                            ] ?? ''
                        )
                    ) !== ''
                ): ?>
                    <p>
                        <strong>
                            Admin Notes:
                        </strong>

                        <?= nl2br(
                            sparrow_escape(
                                $order[
                                    'admin_notes'
                                ]
                            )
                        ) ?>
                    </p>
                <?php endif; ?>
            </article>
        <?php endforeach; ?>
    </section>

    </div>

<?php endforeach; ?>

</div>

<?php sparrow_backyard_footer(); ?>