<?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'];
$party_id = (int)($_GET['party_id'] ?? 0);

if (!$party_id) {
    echo "Invalid Party ID";
    exit;
}

$from = $_GET['from'] ?? date('Y-m-01');
$to   = $_GET['to']   ?? date('Y-m-d');

$party = one("SELECT * FROM accounts WHERE id = ? AND business_id = ?", [$party_id, $business_id]);
if (!$party) {
    echo "Party not found";
    exit;
}

// 1. Get Opening Balance up to $from date
// Opening = Original Opening + Transactions before $from - Payments before $from
$is_customer = $party['group_name'] === 'CUSTOMERS';

$prev_trans = 0;
$prev_paid  = 0;

if ($is_customer) {
    $prev_trans = (float)one("SELECT SUM(grand_total) FROM sales WHERE party_id = ? AND business_id = ? AND sale_date < ?", [$party_id, $business_id, $from])['SUM(grand_total)'];
    $prev_paid  = (float)one("SELECT SUM(amount) FROM payments WHERE party_id = ? AND business_id = ? AND payment_type = 'RECEIPT' AND payment_date < ?", [$party_id, $business_id, $from])['SUM(amount)'];
    $initial_net = ($party['drcr'] == 'Dr' ? (float)$party['opening_balance'] : -(float)$party['opening_balance']) + $prev_trans - $prev_paid;
} else {
    $prev_trans = (float)one("SELECT SUM(grand_total) FROM purchases WHERE party_id = ? AND business_id = ? AND purchase_date < ?", [$party_id, $business_id, $from])['SUM(grand_total)'];
    $prev_paid  = (float)one("SELECT SUM(amount) FROM payments WHERE party_id = ? AND business_id = ? AND payment_type = 'PAYMENT' AND payment_date < ?", [$party_id, $business_id, $from])['SUM(amount)'];
    $initial_net = ($party['drcr'] == 'Cr' ? (float)$party['opening_balance'] : -(float)$party['opening_balance']) + $prev_trans - $prev_paid;
}

// 2. Combine Transactions in range
$ledger = [];

if ($is_customer) {
    $sales = all_rows("SELECT 'SALE' as type, bill_no as ref, sale_date as date, grand_total as amount FROM sales WHERE party_id = ? AND business_id = ? AND sale_date BETWEEN ? AND ?", [$party_id, $business_id, $from, $to]);
    foreach ($sales as $s) {
        $ledger[] = ['date' => $s['date'], 'type' => 'Sale', 'ref' => $s['ref'] ?: 'Bill #'.$s['ref'], 'dr' => $s['amount'], 'cr' => 0];
    }
    $receipts = all_rows("SELECT 'RECEIPT' as type, id as ref, payment_date as date, amount, payment_mode FROM payments WHERE party_id = ? AND business_id = ? AND payment_type = 'RECEIPT' AND payment_date BETWEEN ? AND ?", [$party_id, $business_id, $from, $to]);
    foreach ($receipts as $r) {
        $ledger[] = ['date' => $r['date'], 'type' => 'Receipt', 'ref' => $r['payment_mode'], 'dr' => 0, 'cr' => $r['amount']];
    }
} else {
    $purchases = all_rows("SELECT 'PURCHASE' as type, bill_no as ref, purchase_date as date, grand_total as amount FROM purchases WHERE party_id = ? AND business_id = ? AND purchase_date BETWEEN ? AND ?", [$party_id, $business_id, $from, $to]);
    foreach ($purchases as $p) {
        $ledger[] = ['date' => $p['date'], 'type' => 'Purchase', 'ref' => $p['ref'] ?: 'Inv #'.$p['ref'], 'dr' => 0, 'cr' => $p['amount']];
    }
    $payments = all_rows("SELECT 'PAYMENT' as type, id as ref, payment_date as date, amount, payment_mode FROM payments WHERE party_id = ? AND business_id = ? AND payment_type = 'PAYMENT' AND payment_date BETWEEN ? AND ?", [$party_id, $business_id, $from, $to]);
    foreach ($payments as $p) {
        $ledger[] = ['date' => $p['date'], 'type' => 'Payment', 'ref' => $p['payment_mode'], 'dr' => $p['amount'], 'cr' => 0];
    }
}

usort($ledger, function($a, $b) {
    return strtotime($a['date']) - strtotime($b['date']);
});

?>
<!DOCTYPE html>
<html>
<head>
    <title>Party Ledger - <?= e($party['name']) ?></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;
        }
        .ledger-card { border-radius: 8px; border: none; box-shadow: 0 2px 10px rgba(0,0,0,0.08); background: white; }
        .table thead th { background: #007cf8; color: white; border: none; }
        .bg-opening { background: #eef2f7; font-weight: bold; }
        .text-dr { color: #0d6efd; }
        .text-cr { color: #dc3545; }
    </style>
</head>
<body>

<div class="container-fluid mt-3">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h4>Ledger: <?= e($party['name']) ?> <small class="text-muted">(<?= e($party['group_name']) ?>)</small></h4>
        <a href="<?= BASE_URL ?>/public/index.php?r=reports/party_balance" class="btn btn-outline-secondary btn-sm">Back to List</a>
    </div>

    <form class="row g-2 align-items-end mb-3">
        <input type="hidden" name="r" value="reports/ledger">
        <input type="hidden" name="party_id" value="<?= $party_id ?>">
        <div class="col-auto">
            <label class="form-label">From</label>
            <input type="date" name="from" class="form-control" value="<?= e($from) ?>">
        </div>
        <div class="col-auto">
            <label class="form-label">To</label>
            <input type="date" name="to" class="form-control" value="<?= e($to) ?>">
        </div>
        <div class="col-auto">
            <button class="btn btn-primary">Filter</button>
        </div>
    </form>

    <div class="ledger-card overflow-hidden">
        <table class="table table-bordered mb-0">
            <thead>
                <tr>
                    <th width="120">Date</th>
                    <th>Particulars</th>
                    <th>Reference</th>
                    <th class="text-end" width="150">Debit (Dr)</th>
                    <th class="text-end" width="150">Credit (Cr)</th>
                    <th class="text-end" width="150">Balance</th>
                </tr>
            </thead>
            <tbody>
                <tr class="bg-opening">
                    <td colspan="3">Opening Balance (as on <?= date('d-m-Y', strtotime($from)) ?>)</td>
                    <td class="text-end"><?= $initial_net > 0 ? number_format(abs($initial_net), 2) : '' ?></td>
                    <td class="text-end"><?= $initial_net < 0 ? number_format(abs($initial_net), 2) : '' ?></td>
                    <td class="text-end">
                        ₹ <?= number_format(abs($initial_net), 2) ?> 
                        <?= $is_customer ? ($initial_net >= 0 ? 'Dr' : 'Cr') : ($initial_net >= 0 ? 'Cr' : 'Dr') ?>
                    </td>
                </tr>

                <?php 
                $running_net = $initial_net;
                foreach ($ledger as $l): 
                    if ($is_customer) {
                        $running_net += ($l['dr'] - $l['cr']);
                        $bal_str = $running_net >= 0 ? 'Dr' : 'Cr';
                    } else {
                        $running_net += ($l['cr'] - $l['dr']);
                        $bal_str = $running_net >= 0 ? 'Cr' : 'Dr';
                    }
                ?>
                <tr>
                    <td><?= date('d-m-Y', strtotime($l['date'])) ?></td>
                    <td><?= e($l['type']) ?></td>
                    <td><small class="text-muted"><?= e($l['ref']) ?></small></td>
                    <td class="text-end text-dr"><?= $l['dr'] > 0 ? number_format($l['dr'], 2) : '-' ?></td>
                    <td class="text-end text-cr"><?= $l['cr'] > 0 ? number_format($l['cr'], 2) : '-' ?></td>
                    <td class="text-end fw-bold">₹ <?= number_format(abs($running_net), 2) ?> <?= $bal_str ?></td>
                </tr>
                <?php endforeach; ?>

                <?php if (empty($ledger)): ?>
                <tr>
                    <td colspan="6" class="text-center py-4 text-muted">No transactions in this period</td>
                </tr>
                <?php endif; ?>
            </tbody>
            <tfoot class="bg-light fw-bold">
                <tr>
                    <td colspan="5" class="text-end">Closing Balance</td>
                    <td class="text-end">
                        ₹ <?= number_format(abs($running_net), 2) ?> 
                        <?= $is_customer ? ($running_net >= 0 ? 'Dr' : 'Cr') : ($running_net >= 0 ? 'Cr' : 'Dr') ?>
                    </td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>

</body>
</html>
