<?php
require_once '../includes/auth.php';
requirePermission('reports', 'view');
require_once '../db.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

$client_id = (int)($_GET['client_id'] ?? 0);
$from_date = $_GET['from_date'] ?? date('Y-m-01');
$to_date   = $_GET['to_date'] ?? date('Y-m-d');

$clients = $conn->query("SELECT id, name, opening_balance FROM clients WHERE status=1 AND company_id = $cid ORDER BY name");

$client = null;
if ($client_id > 0) {
    $client = $conn->query("SELECT * FROM clients WHERE id=$client_id")->fetch_assoc();
}

$ledgerRows = [];
$balance = 0;

if ($client_id > 0) {
    $opening = (float)($client['opening_balance'] ?? 0);

    $invQuery = $conn->query("
        SELECT id, invoice_no, invoice_date, net_total, received_amount, payment_mode
        FROM sales_invoices
        WHERE client_id = $client_id AND status = 'final' AND company_id = $cid
          AND invoice_date BETWEEN '$from_date' AND '$to_date'
        ORDER BY invoice_date ASC, id ASC
    ");

    while ($inv = $invQuery->fetch_assoc()) {
        $ledgerRows[] = [
            'date' => $inv['invoice_date'], 'type' => 'Sales Invoice',
            'ref'  => $inv['invoice_no'], 'debit' => (float)$inv['net_total'],
            'credit' => 0, 'note' => '', 'link_type' => 'sale', 'link_id' => $inv['id']
        ];
        if ((float)$inv['received_amount'] > 0) {
            $ledgerRows[] = [
                'date' => $inv['invoice_date'], 'type' => 'Payment Received',
                'ref'  => $inv['invoice_no'], 'debit' => 0,
                'credit' => (float)$inv['received_amount'], 'note' => $inv['payment_mode'] ?? '',
                'link_type' => 'sale', 'link_id' => $inv['id']
            ];
        }
    }

    $retQuery = $conn->query("
        SELECT id, return_no, return_date, total_amount
        FROM sales_returns
        WHERE client_id = $client_id AND status = 'final' AND company_id = $cid
          AND return_date BETWEEN '$from_date' AND '$to_date'
        ORDER BY return_date ASC, id ASC
    ");

    while ($ret = $retQuery->fetch_assoc()) {
        $ledgerRows[] = [
            'date' => $ret['return_date'], 'type' => 'Sales Return',
            'ref'  => $ret['return_no'], 'debit' => 0,
            'credit' => (float)$ret['total_amount'], 'note' => '',
            'link_type' => 'sal_return', 'link_id' => $ret['id']
        ];
    }

    usort($ledgerRows, function($a, $b){ return strtotime($a['date']) <=> strtotime($b['date']); });
    $balance = $opening;
}
?>

<div class="page-header">
    <h2><i class="fas fa-address-book" style="color:var(--primary);margin-right:8px;"></i>Customer Ledger</h2>
    <?php if($client_id > 0): ?>
    <div style="display:flex;gap:8px;">
        <a href="customer_ledger_export_excel.php?client_id=<?= $client_id ?>&from_date=<?= $from_date ?>&to_date=<?= $to_date ?>"
           target="_blank" class="btn btn-success btn-sm"><i class="fas fa-file-excel"></i> Excel</a>
        <a href="customer_ledger_export_pdf.php?client_id=<?= $client_id ?>&from_date=<?= $from_date ?>&to_date=<?= $to_date ?>"
           target="_blank" class="btn btn-danger btn-sm"><i class="fas fa-file-pdf"></i> PDF</a>
    </div>
    <?php endif; ?>
</div>

<!-- Filters -->
<div class="filter-panel">
    <form method="get" class="filter-form">
        <div class="filter-group" style="flex:1;min-width:220px;">
            <label>Customer</label>
            <select name="client_id" required>
                <option value="">-- Select Customer --</option>
                <?php while($c = $clients->fetch_assoc()): ?>
                    <option value="<?= $c['id'] ?>" <?= ($client_id == $c['id'])?'selected':'' ?>>
                        <?= htmlspecialchars($c['name']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
        </div>
        <div class="filter-group">
            <label>From Date</label>
            <input type="date" name="from_date" value="<?= htmlspecialchars($from_date) ?>" required>
        </div>
        <div class="filter-group">
            <label>To Date</label>
            <input type="date" name="to_date" value="<?= htmlspecialchars($to_date) ?>" required>
        </div>
        <div class="filter-actions">
            <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Show Ledger</button>
            <a href="customer_ledger.php" class="btn btn-secondary">Reset</a>
        </div>
    </form>
</div>

<?php if($client_id > 0 && $client): ?>

<!-- Client Info -->
<div class="panel" style="margin-bottom:16px;">
    <div class="panel-body">
        <div style="display:flex;gap:32px;flex-wrap:wrap;">
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:3px;">Customer</div>
                <div style="font-size:15px;font-weight:700;"><?= htmlspecialchars($client['name']) ?></div>
            </div>
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:3px;">Phone</div>
                <div style="font-size:14px;"><?= htmlspecialchars($client['phone'] ?? '-') ?></div>
            </div>
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:3px;">GSTIN</div>
                <div style="font-size:14px;"><?= htmlspecialchars($client['gstin'] ?? '-') ?></div>
            </div>
        </div>
    </div>
</div>

<!-- Ledger Table -->
<div class="panel">
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Particular</th>
                    <th>Ref No</th>
                    <th style="text-align:right;">Debit (&#8377;)</th>
                    <th style="text-align:right;">Credit (&#8377;)</th>
                    <th style="text-align:right;">Balance (&#8377;)</th>
                    <th>Note</th>
                </tr>
            </thead>
            <tbody>
                <?php $runBalance = $balance; ?>
                <!-- Opening Balance Row -->
                <tr style="background:#fffbe6;">
                    <td><?= htmlspecialchars($from_date) ?></td>
                    <td><strong>Opening Balance</strong></td>
                    <td style="color:var(--text-muted);">-</td>
                    <td style="text-align:right;"><?= ($runBalance > 0) ? number_format($runBalance,2) : "0.00" ?></td>
                    <td style="text-align:right;"><?= ($runBalance < 0) ? number_format(abs($runBalance),2) : "0.00" ?></td>
                    <td style="text-align:right;"><strong><?= number_format($runBalance,2) ?></strong></td>
                    <td></td>
                </tr>
                <?php foreach($ledgerRows as $row):
                    $runBalance += $row['debit'];
                    $runBalance -= $row['credit'];
                ?>
                <tr>
                    <td><?= date('d-m-Y', strtotime($row['date'])) ?></td>
                    <td><?= htmlspecialchars($row['type']) ?></td>
                    <td style="font-size:12px;">
                        <?php if (!empty($row['link_type']) && !empty($row['link_id'])): ?>
                        <a href="#" onclick="openDocPopup('<?= $row['link_type'] ?>',<?= (int)$row['link_id'] ?>,'<?= htmlspecialchars($row['ref'],ENT_QUOTES) ?>');return false;" style="color:var(--primary);text-decoration:none;"><?= htmlspecialchars($row['ref']) ?></a>
                        <?php else: ?>
                        <span style="color:var(--text-secondary);"><?= htmlspecialchars($row['ref']) ?></span>
                        <?php endif; ?>
                    </td>
                    <td style="text-align:right;color:<?= $row['debit'] > 0 ? 'var(--danger)' : 'var(--text-muted)' ?>;">
                        <?= number_format($row['debit'],2) ?>
                    </td>
                    <td style="text-align:right;color:<?= $row['credit'] > 0 ? 'var(--success)' : 'var(--text-muted)' ?>;">
                        <?= number_format($row['credit'],2) ?>
                    </td>
                    <td style="text-align:right;"><strong><?= number_format($runBalance,2) ?></strong></td>
                    <td style="color:var(--text-muted);font-size:12px;"><?= htmlspecialchars($row['note']) ?></td>
                </tr>
                <?php endforeach; ?>
                <?php if(count($ledgerRows) == 0): ?>
                <tr><td colspan="7" style="text-align:center;padding:40px;color:var(--text-muted);">No ledger entries found for this period.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Closing Balance -->
<div style="display:flex;justify-content:flex-end;margin-top:8px;">
    <div class="totals-box" style="min-width:280px;">
        <div class="totals-row grand-total">
            <span>Closing Balance</span>
            <span>&#8377; <?= number_format($runBalance, 2) ?></span>
        </div>
    </div>
</div>

<?php else: ?>
<div class="panel">
    <div class="panel-body" style="text-align:center;padding:40px;color:var(--text-muted);">
        <i class="fas fa-search" style="font-size:32px;margin-bottom:12px;display:block;"></i>
        Select a customer and date range to view ledger.
    </div>
</div>
<?php endif; ?>

<?php require_once '../includes/doc_popup_modal.php'; ?>
<?php require_once '../includes/footer.php'; ?>
