<?php

require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/orders.php';
require_once __DIR__ . '/../app/pricing.php';

$user = sparrow_require_backyard_login();

function sparrow_profit_loss_money(float $amount): string
{
    $prefix = $amount < 0 ? '-$' : '$';

    return $prefix . number_format(abs($amount), 2);
}

$report_filter = $_GET['report_filter'] ?? 'all';
$date_from = trim((string) ($_GET['date_from'] ?? ''));
$date_to = trim((string) ($_GET['date_to'] ?? ''));

$allowed_filters = ['all', 'active', 'delivered', 'ready', 'outstanding', 'gifts'];

if (!in_array($report_filter, $allowed_filters, true)) {
    $report_filter = 'all';
}

$orders = sparrow_get_orders();

$report_rows = [];

$totals = [
    'orders' => 0,
    'gift_orders' => 0,
    'gift_costs' => 0.00,
    'gross_revenue' => 0.00,
    'discounts' => 0.00,
    'net_revenue' => 0.00,
    'collected' => 0.00,
    'blessings' => 0.00,
    'blank_costs' => 0.00,
    'supplier_item_costs' => 0.00,
    'production_costs' => 0.00,
    'shipping_costs' => 0.00,
    'tax_costs' => 0.00,
    'other_costs' => 0.00,
    'supplier_discounts' => 0.00,
    'internal_costs' => 0.00,
    'estimated_profit' => 0.00,
    'outstanding_balance' => 0.00,
];

foreach ($orders as $order) {
    $status = trim((string) ($order['status'] ?? ''));
    $order_date = trim((string) ($order['order_date'] ?? ''));
    $is_gift = !empty($order['is_gift']);

    if ($date_from !== '' && $order_date !== '' && $order_date < $date_from) {
        continue;
    }

    if ($date_to !== '' && $order_date !== '' && $order_date > $date_to) {
        continue;
    }

    if ($report_filter === 'delivered' && $status !== 'Delivered') {
        continue;
    }

    if ($report_filter === 'ready' && $status !== 'Ready for Pickup') {
        continue;
    }

    if ($report_filter === 'active' && in_array($status, ['Delivered', 'Completed', 'Archived', 'Merged'], true)) {
        continue;
    }

    if ($report_filter === 'gifts' && !$is_gift) {
        continue;
    }

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

    if ($order_value <= 0) {
        $lookup_for_total = sparrow_calculate_order_pricing_from_lookup((int) $order['id']);
        $order_value = (float) ($lookup_for_total['retail_total'] ?? 0);
    }

    $gross_total = $is_gift ? 0.00 : $order_value;
    $customer_discount = $is_gift
        ? 0.00
        : (float) ($order['order_discount_amount'] ?? 0);
    $net_total = max(0, $gross_total - $customer_discount);

    $collected = $is_gift ? 0.00 : (float) ($order['paid_amount'] ?? 0);
    $blessing = $is_gift ? 0.00 : (float) ($order['blessing_amount'] ?? 0);
    $balance = $is_gift ? 0.00 : max(0, $net_total - $collected);

    if ($report_filter === 'outstanding' && $balance <= 0) {
        continue;
    }

    $pricing_lookup = sparrow_calculate_order_pricing_from_lookup((int) $order['id']);
    $blank_cost_estimate = (float) ($pricing_lookup['blank_cost_total'] ?? 0);
    $supplier_item_cost = (float) ($order['supplier_item_cost'] ?? 0);

    /*
     * Use actual Supplier Splitter item costs when present. Only fall back to
     * pricing-table blank estimates when no actual supplier item cost exists.
     */
    $blank_costs = $supplier_item_cost > 0 ? 0.00 : $blank_cost_estimate;
    $production_costs = $supplier_item_cost > 0
        ? $supplier_item_cost
        : $blank_costs;

    $shipping_cost = (float) ($order['shipping_cost'] ?? 0);
    $tax_cost = (float) ($order['tax_cost'] ?? 0);
    $other_cost = (float) ($order['other_cost'] ?? 0);
    $supplier_discount = (float) ($order['discount_cost'] ?? 0);

    $internal_costs = $production_costs + $shipping_cost + $tax_cost + $other_cost - $supplier_discount;
    $estimated_profit = $net_total - $internal_costs;

    $totals['orders']++;
    $totals['gift_orders'] += $is_gift ? 1 : 0;
    $totals['gift_costs'] += $is_gift ? $internal_costs : 0.00;
    $totals['gross_revenue'] += $gross_total;
    $totals['discounts'] += $customer_discount;
    $totals['net_revenue'] += $net_total;
    $totals['collected'] += $collected;
    $totals['blessings'] += $blessing;
    $totals['blank_costs'] += $blank_costs;
    $totals['supplier_item_costs'] += $supplier_item_cost;
    $totals['production_costs'] += $production_costs;
    $totals['shipping_costs'] += $shipping_cost;
    $totals['tax_costs'] += $tax_cost;
    $totals['other_costs'] += $other_cost;
    $totals['supplier_discounts'] += $supplier_discount;
    $totals['internal_costs'] += $internal_costs;
    $totals['estimated_profit'] += $estimated_profit;
    $totals['outstanding_balance'] += $balance;

    $report_rows[] = [
        'id' => (int) $order['id'],
        'order_number' => $order['order_number'] ?? '',
        'customer_name' => $order['customer_name'] ?? '',
        'order_date' => $order_date,
        'status' => $status,
        'is_gift' => $is_gift,
        'order_value' => $order_value,
        'gross_total' => $gross_total,
        'customer_discount' => $customer_discount,
        'net_total' => $net_total,
        'collected' => $collected,
        'blessing' => $blessing,
        'production_costs' => $production_costs,
        'internal_costs' => $internal_costs,
        'estimated_profit' => $estimated_profit,
        'balance' => $balance,
    ];
}

sparrow_backyard_header('Profit / Loss');
?>

<style>
    .profit-loss-table .sale-order-pill {
        background: #e9f8ee;
        border-color: #bfe8ca;
        color: #16723a;
    }
</style>

<section class="card">
    <div class="page-heading-row">
        <div>
            <h1>Profit / Loss</h1>
            <p class="muted">
                Starter report based on current Backyard orders, pricing lookup, customer discounts, and internal costs.
            </p>
        </div>
    </div>
</section>

<section class="card">
    <h2>Filters</h2>

    <form method="get" class="profit-loss-filter-form">
        <div class="form-grid">
            <div>
                <label for="report_filter">Report View</label>
                <select id="report_filter" name="report_filter">
                    <option value="all" <?= $report_filter === 'all' ? 'selected' : '' ?>>All Orders</option>
                    <option value="active" <?= $report_filter === 'active' ? 'selected' : '' ?>>Active Orders</option>
                    <option value="delivered" <?= $report_filter === 'delivered' ? 'selected' : '' ?>>Delivered Orders</option>
                    <option value="ready" <?= $report_filter === 'ready' ? 'selected' : '' ?>>Ready for Pickup</option>
                    <option value="outstanding" <?= $report_filter === 'outstanding' ? 'selected' : '' ?>>Outstanding Balance</option>
                    <option value="gifts" <?= $report_filter === 'gifts' ? 'selected' : '' ?>>Gift Orders</option>
                </select>
            </div>

            <div>
                <label for="date_from">Date From</label>
                <input type="date" id="date_from" name="date_from" value="<?= sparrow_escape($date_from) ?>">
            </div>

            <div>
                <label for="date_to">Date To</label>
                <input type="date" id="date_to" name="date_to" value="<?= sparrow_escape($date_to) ?>">
            </div>
        </div>

        <div class="form-actions">
            <button type="submit" class="button">Apply Filters</button>
            <a class="button button-secondary" href="<?= sparrow_escape(sparrow_url('/backyard/profit-loss.php')) ?>">Reset</a>
        </div>
    </form>
</section>

<section class="profit-loss-kpi-wrap">

    <div class="profit-loss-feature-kpis">
        <div class="dashboard-kpi-card dashboard-kpi-money-green profit-loss-hero-card">
            <span>Estimated Profit</span>
            <strong><?= sparrow_profit_loss_money((float) $totals['estimated_profit']) ?></strong>
        </div>

        <div class="dashboard-kpi-card dashboard-kpi-money-blue profit-loss-hero-card">
            <span>Total Orders</span>
            <strong><?= number_format((int) $totals['orders']) ?></strong>
        </div>
    </div>

    <div class="dashboard-kpi-grid profit-loss-kpi-grid">
        <div class="dashboard-kpi-card dashboard-kpi-money-green">
            <span>Gross Revenue</span>
            <strong>$<?= number_format((float) $totals['gross_revenue'], 2) ?></strong>
        </div>

        <div class="dashboard-kpi-card dashboard-kpi-money-pink">
            <span>Customer Discounts</span>
            <strong>$<?= number_format((float) $totals['discounts'], 2) ?></strong>
        </div>

        <div class="dashboard-kpi-card dashboard-kpi-money-blue">
            <span>Net Revenue</span>
            <strong>$<?= number_format((float) $totals['net_revenue'], 2) ?></strong>
        </div>

        <div class="dashboard-kpi-card dashboard-kpi-money-blue">
            <span>Collected</span>
            <strong>$<?= number_format((float) $totals['collected'], 2) ?></strong>
        </div>

        <div class="dashboard-kpi-card dashboard-kpi-money-purple">
            <span>Gift Orders</span>
            <strong><?= number_format((int) $totals['gift_orders']) ?></strong>
        </div>

        <div class="dashboard-kpi-card dashboard-kpi-money-red">
            <span>Gift Costs</span>
            <strong>$<?= number_format((float) $totals['gift_costs'], 2) ?></strong>
        </div>

        <div class="dashboard-kpi-card dashboard-kpi-money-purple">
            <span>Blessings</span>
            <strong>$<?= number_format((float) $totals['blessings'], 2) ?></strong>
        </div>

        <div class="dashboard-kpi-card dashboard-kpi-purple">
            <span>Production Costs</span>
            <strong>$<?= number_format((float) $totals['production_costs'], 2) ?></strong>
        </div>

        <div class="dashboard-kpi-card dashboard-kpi-money-red">
            <span>Internal Costs</span>
            <strong>$<?= number_format((float) $totals['internal_costs'], 2) ?></strong>
        </div>

        <div class="dashboard-kpi-card dashboard-kpi-money-red">
            <span>Outstanding</span>
            <strong>$<?= number_format((float) $totals['outstanding_balance'], 2) ?></strong>
        </div>
    </div>

</section>

<section class="card">
    <h2>Order Profit / Loss</h2>

    <?php if (!$report_rows): ?>
        <p class="muted">No orders match this report.</p>
    <?php else: ?>
        <div class="table-wrap">
            <table class="profit-loss-table">
                <thead>
                    <tr>
                        <th>Order</th>
                        <th>Date</th>
                        <th>Customer</th>
                        <th>Type</th>
                        <th>Status</th>
                        <th>Order Value</th>
                        <th>Gross</th>
                        <th>Discount</th>
                        <th>Net</th>
                        <th>Collected</th>
                        <th>Production Cost</th>
                        <th>Internal Cost</th>
                        <th>Profit</th>
                        <th>Balance</th>
                        <th>Open</th>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach ($report_rows as $row): ?>
                        <tr>
                            <td><strong><?= sparrow_escape($row['order_number']) ?></strong></td>
                            <td><?= sparrow_escape($row['order_date']) ?></td>
                            <td><?= sparrow_escape($row['customer_name']) ?></td>
                            <td>
                                <?php if ($row['is_gift']): ?>
                                    <span class="dashboard-mini-pill gift-order-pill">Gift</span>
                                <?php else: ?>
                                    <span class="dashboard-mini-pill sale-order-pill">Sale</span>
                                <?php endif; ?>
                            </td>
                            <td><?= sparrow_escape($row['status']) ?></td>
                            <td>$<?= number_format((float) $row['order_value'], 2) ?></td>
                            <td>$<?= number_format((float) $row['gross_total'], 2) ?></td>
                            <td>$<?= number_format((float) $row['customer_discount'], 2) ?></td>
                            <td>$<?= number_format((float) $row['net_total'], 2) ?></td>
                            <td>$<?= number_format((float) $row['collected'], 2) ?></td>
                            <td>$<?= number_format((float) $row['production_costs'], 2) ?></td>
                            <td>$<?= number_format((float) $row['internal_costs'], 2) ?></td>
                            <td>
                                <strong><?= sparrow_profit_loss_money((float) $row['estimated_profit']) ?></strong>
                            </td>
                            <td>$<?= number_format((float) $row['balance'], 2) ?></td>
                            <td>
                                <a
                                    class="button button-small"
                                    href="<?= sparrow_escape(sparrow_url('/backyard/order-view.php?id=' . (int) $row['id'])) ?>"
                                >
                                    View
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</section>

<section class="card">
    <h2>Cost Breakdown</h2>

    <div class="profit-loss-breakdown-grid">
        <div>
            <div class="detail-label">Estimated Blank Costs Used</div>
            <div class="detail-value">$<?= number_format((float) $totals['blank_costs'], 2) ?></div>
        </div>

        <div>
            <div class="detail-label">Supplier Item Costs</div>
            <div class="detail-value">$<?= number_format((float) $totals['supplier_item_costs'], 2) ?></div>
        </div>

        <div>
            <div class="detail-label">Shipping Costs</div>
            <div class="detail-value">$<?= number_format((float) $totals['shipping_costs'], 2) ?></div>
        </div>

        <div>
            <div class="detail-label">Tax Costs</div>
            <div class="detail-value">$<?= number_format((float) $totals['tax_costs'], 2) ?></div>
        </div>

        <div>
            <div class="detail-label">Other Costs</div>
            <div class="detail-value">$<?= number_format((float) $totals['other_costs'], 2) ?></div>
        </div>

        <div>
            <div class="detail-label">Supplier Discounts / Credits</div>
            <div class="detail-value">-$<?= number_format((float) $totals['supplier_discounts'], 2) ?></div>
        </div>
    </div>
</section>

<?php sparrow_backyard_footer(); ?>
