<?php
require_once __DIR__ . "/../db.php";
require_once __DIR__ . "/../session.php";

requireAuth();

$current_business = getCurrentBusiness();
if (!$current_business) {
    header('Location: ' . BASE_URL . '/public/login.php');
    exit;
}

$business_id = $current_business['business_id'];

// Get all accounts
$accounts = all_rows("SELECT id, name, group_name, opening_balance, drcr FROM accounts WHERE business_id = ? ORDER BY name", [$business_id]);

// Get total Sales by party (Credit only)
$sales_raw = all_rows("SELECT party_id, SUM(grand_total) as total FROM sales WHERE business_id = ? AND payment_terms = 'Credit' GROUP BY party_id", [$business_id]);
$sale_map = [];
foreach($sales_raw as $s) $sale_map[$s['party_id']] = (float)$s['total'];

// Get total Purchases by party
$purchases_raw = all_rows("SELECT party_id, SUM(grand_total) as total FROM purchases WHERE business_id = ? GROUP BY party_id", [$business_id]);
$purchase_map = [];
foreach($purchases_raw as $p) $purchase_map[$p['party_id']] = (float)$p['total'];

// Get total Payments/Receipts by party
$payments_raw = all_rows("SELECT party_id, payment_type, SUM(amount) as total FROM payments WHERE business_id = ? GROUP BY party_id, payment_type", [$business_id]);
$payment_map = [];
foreach($payments_raw as $pm) {
    if(!isset($payment_map[$pm['party_id']])) $payment_map[$pm['party_id']] = ['RECEIPT' => 0, 'PAYMENT' => 0];
    $payment_map[$pm['party_id']][$pm['payment_type']] = (float)$pm['total'];
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Party Balance Report</title>
    <style>
        body { 
            /* Merged background styles so image works */
            background-image: url("<?= BASE_URL ?>/public/grocery.png");
            background-size: cover;
            background-repeat: no-repeat;
            background-attachment: fixed;
            background-position: center;
            background-color: #f4f6f9; /* Fallback */
            font-size: 14px;
        }
        .card { border-radius: 8px; padding: 15px; border:none; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .table th { background: #fd7e14; color: white; font-weight: 500; }
        .dr { color: #0d6efd; font-weight: bold; }
        .cr { color: #dc3545; font-weight: bold; }
    </style>
</head>
<body>

<div class="container-fluid mt-3">
    <h4 class="mb-3">Party Wise Credit Balances</h4>

    <div class="card p-0">
        <table class="table table-hover mb-0">
            <thead>
                <tr>
                    <th>Party Name</th>
                    <th>Group</th>
                    <th class="text-end">Opening</th>
                    <th class="text-end">Transactions</th>
                    <th class="text-end">Payments</th>
                    <th class="text-end">Current Balance</th>
                    <th class="text-center">Action</th>
                </tr>
            </thead>
            <tbody>
<?php foreach ($accounts as $a): 

    $party_id = $a['id'];

    // Opening Balance
    $opening = (float)($a['opening_balance'] ?? 0);
    $drcr    = $a['drcr'] ?? 'Dr';

    // Convert opening to signed value
    $opening_signed = ($drcr === 'Cr') ? -$opening : $opening;

    // Transactions (Sales + Purchases)
    $sales     = $sale_map[$party_id] ?? 0;
    $purchases = $purchase_map[$party_id] ?? 0;
    $trans     = $sales + $purchases;

    // Payments / Receipts
    $receipt = $payment_map[$party_id]['RECEIPT'] ?? 0;
    $payment = $payment_map[$party_id]['PAYMENT'] ?? 0;
    $paid    = $receipt + $payment;

    // Net Balance Calculation
    $net = $opening_signed + $trans - $paid;

    $abs_net    = abs($net);
    $final_drcr = ($net >= 0) ? 'Dr' : 'Cr';

?>

                <!-- line 91 -->
                <tr>
                    <td><?= e($a['name']) ?> <small class="text-muted">(<?= e($a['group_name']) ?>)</small></td>
                    <td><small class="badge bg-light text-dark"><?= e($a['group_name']) ?></small></td>
                    <td class="text-end"><?= number_format($opening, 2) ?> <?= $drcr ?></td>
                    <td class="text-end">+ <?= number_format($trans, 2) ?></td>
                    <td class="text-end">- <?= number_format($paid, 2) ?></td>
                    <td class="text-end <?= strtolower($final_drcr) ?>">
                        ₹ <?= number_format($abs_net, 2) ?> <?= $final_drcr ?>
                    </td>
                    <td class="text-center">
                        <a href="<?= BASE_URL ?>/public/index.php?r=reports/ledger&party_id=<?= $a['id'] ?>" class="btn btn-sm btn-outline-primary py-0">View Ledger</a>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if(empty($accounts)): ?>
                    <tr><td colspan="6" class="text-center py-4">No accounts found</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

</body>
</html>
