<?php
require_once '../includes/auth.php';
require_once '../db.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

// Admin and staff only
if (!in_array($_SESSION['user_role'] ?? '', ['admin', 'staff'])) {
    header('Location: ../dashboard.php');
    exit;
}

$userRole = $_SESSION['user_role'] ?? '';
$isAdmin  = ($userRole === 'admin');

$client_id = intval($_GET['client_id'] ?? 0);
$fco       = $isAdmin ? intval($_GET['co'] ?? 0) : $cid;
$from_date = $_GET['from_date'] ?? '';
$to_date   = $_GET['to_date'] ?? '';

if (!$client_id) {
    header('Location: index.php');
    exit;
}

// Load client info
$cRes = $conn->query("SELECT id, name, phone FROM clients WHERE id = $client_id LIMIT 1");
if (!$cRes || $cRes->num_rows === 0) {
    header('Location: index.php');
    exit;
}
$client = $cRes->fetch_assoc();

// Company filter condition
$coWhere = $fco > 0 ? "AND company_id = $fco" : "";

// Date filter conditions
$dateFrom = '';
$dateTo   = '';
if ($from_date !== '') {
    $df = $conn->real_escape_string($from_date);
    $dateFrom = "AND txn_date >= '$df'";
}
if ($to_date !== '') {
    $dt = $conn->real_escape_string($to_date);
    $dateTo = "AND txn_date <= '$dt'";
}

// Explicit filters for invoice_payments (separate query — avoids UNION collation conflict)
$coWhereInv  = $fco > 0 ? "AND si2.company_id = $fco" : "";
$dateFromInv = $from_date !== '' ? "AND ip.payment_date >= '" . $conn->real_escape_string($from_date) . "'" : "";
$dateToInv   = $to_date   !== '' ? "AND ip.payment_date <= '" . $conn->real_escape_string($to_date)   . "'" : "";

// Original 3-branch UNION (invoices, returns, client_payments) — includes created_at for sorting
$sql = "
    SELECT
        si.invoice_date AS txn_date,
        'Invoice' AS txn_type,
        si.net_total AS debit,
        0 AS credit,
        si.invoice_no AS ref_no,
        si.id AS ref_id,
        'si' AS src,
        si.created_at AS created_at
    FROM sales_invoices si
    WHERE si.client_id = $client_id AND si.status = 'final' $coWhere $dateFrom $dateTo

    UNION ALL

    SELECT
        sr.return_date AS txn_date,
        'Return' AS txn_type,
        0 AS debit,
        sr.total_amount AS credit,
        sr.return_no AS ref_no,
        sr.id AS ref_id,
        'sr' AS src,
        sr.created_at AS created_at
    FROM sales_returns sr
    WHERE sr.client_id = $client_id AND sr.status = 'final' $coWhere $dateFrom $dateTo

    UNION ALL

    SELECT
        cp.payment_date AS txn_date,
        'Receipt' AS txn_type,
        0 AS debit,
        cp.amount AS credit,
        COALESCE(NULLIF(cp.reference_no,''), cp.payment_mode) AS ref_no,
        cp.id AS ref_id,
        'cp' AS src,
        cp.created_at AS created_at
    FROM client_payments cp
    WHERE cp.client_id = $client_id $coWhere $dateFrom $dateTo

    ORDER BY txn_date ASC, created_at ASC, src ASC
";

$totalInvoiced = 0;
$totalReturns  = 0;
$totalReceived = 0;
$transactions  = [];

$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
    if ($row['txn_type'] === 'Invoice') $totalInvoiced += $row['debit'];
    if ($row['txn_type'] === 'Return')  $totalReturns  += $row['credit'];
    if ($row['txn_type'] === 'Receipt') $totalReceived += $row['credit'];
    $transactions[] = $row;
}

// Fetch invoice_payments in a separate query to avoid UNION collation conflict
$_ledgerError = null;
try {
    $ipResult = $conn->query("
        SELECT
            ip.payment_date AS txn_date,
            'Receipt' AS txn_type,
            0 AS debit,
            ip.amount AS credit,
            CONCAT(si2.invoice_no, ' (', ip.payment_mode, ')') AS ref_no,
            ip.id AS ref_id,
            'ip' AS src,
            ip.created_at AS created_at
        FROM invoice_payments ip
        JOIN sales_invoices si2 ON si2.id = ip.sales_invoice_id
        WHERE si2.client_id = $client_id $coWhereInv $dateFromInv $dateToInv
    ");
    while ($row = $ipResult->fetch_assoc()) {
        $totalReceived += $row['credit'];
        $transactions[] = $row;
    }
} catch (mysqli_sql_exception $e) {
    $_ledgerError = $e->getMessage();
    error_log('Client ledger invoice_payments error: ' . $_ledgerError);
}

// Sort by business date first, then created_at (insertion time) as tiebreaker, then src
usort($transactions, function($a, $b) {
    $cmp = strcmp($a['txn_date'], $b['txn_date']);
    if ($cmp !== 0) return $cmp;
    $cmp2 = strcmp($a['created_at'] ?? '', $b['created_at'] ?? '');
    return $cmp2 !== 0 ? $cmp2 : strcmp($a['src'], $b['src']);
});

// Compute running balance after sort
$runningBalance = 0;
foreach ($transactions as &$txn) {
    $runningBalance += $txn['debit'] - $txn['credit'];
    $txn['running_balance'] = $runningBalance;
}
unset($txn);

$closingBalance = $totalInvoiced - $totalReturns - $totalReceived;

// Companies for filter dropdown — admin only
$companies = $isAdmin ? $conn->query("SELECT id, company_name FROM company_master ORDER BY company_name") : null;
?>

<div class="page-header">
    <h2>
        <i class="fas fa-book" style="color:var(--primary);margin-right:8px;"></i>
        Client Ledger &mdash; <?= htmlspecialchars($client['name']) ?>
    </h2>
    <div style="display:flex;gap:8px;">
        <a href="add_payment.php?client_id=<?= $client_id ?>&co=<?= $fco ?>"
           class="btn btn-success">
            <i class="fas fa-plus"></i> Record Receipt
        </a>
        <?php
        $printBase = 'print.php?client_id=' . $client_id . '&co=' . $fco . '&from_date=' . urlencode($from_date) . '&to_date=' . urlencode($to_date);
        ?>
        <button onclick="openLedgerPrint('<?= htmlspecialchars($printBase.'&format=a4', ENT_QUOTES) ?>', 'Client Statement — A4', 'a4')" class="btn btn-secondary">
            <i class="fas fa-file-alt"></i> Print A4
        </button>
        <button onclick="openLedgerPrint('<?= htmlspecialchars($printBase.'&format=thermal', ENT_QUOTES) ?>', 'Client Statement — Thermal', 'thermal')" class="btn btn-outline" style="color:var(--primary);border-color:var(--primary);">
            <i class="fas fa-receipt"></i> Thermal
        </button>
        <a href="index.php<?= $fco ? '?co='.$fco : '' ?>" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> Back to List
        </a>
    </div>
</div>

<!-- Summary Panel -->
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:14px;margin-bottom:18px;">
    <div class="panel" style="border-left:4px solid var(--warning);margin:0;">
        <div class="panel-body" style="padding:14px 18px;">
            <div style="font-size:11px;font-weight:600;text-transform:uppercase;color:var(--text-secondary);letter-spacing:.05em;">Total Invoiced</div>
            <div style="font-size:20px;font-weight:700;color:var(--warning);margin-top:4px;">&#8377; <?= number_format($totalInvoiced, 2) ?></div>
        </div>
    </div>
    <div class="panel" style="border-left:4px solid var(--success);margin:0;">
        <div class="panel-body" style="padding:14px 18px;">
            <div style="font-size:11px;font-weight:600;text-transform:uppercase;color:var(--text-secondary);letter-spacing:.05em;">Total Returns</div>
            <div style="font-size:20px;font-weight:700;color:var(--success);margin-top:4px;">&#8377; <?= number_format($totalReturns, 2) ?></div>
        </div>
    </div>
    <div class="panel" style="border-left:4px solid var(--primary);margin:0;">
        <div class="panel-body" style="padding:14px 18px;">
            <div style="font-size:11px;font-weight:600;text-transform:uppercase;color:var(--text-secondary);letter-spacing:.05em;">Total Received</div>
            <div style="font-size:20px;font-weight:700;color:var(--primary);margin-top:4px;">&#8377; <?= number_format($totalReceived, 2) ?></div>
        </div>
    </div>
    <div class="panel" style="border-left:4px solid <?= $closingBalance > 0 ? 'var(--danger)' : 'var(--success)' ?>;margin:0;">
        <div class="panel-body" style="padding:14px 18px;">
            <div style="font-size:11px;font-weight:600;text-transform:uppercase;color:var(--text-secondary);letter-spacing:.05em;">Closing Balance</div>
            <div style="font-size:20px;font-weight:700;color:<?= $closingBalance > 0 ? 'var(--danger)' : 'var(--success)' ?>;margin-top:4px;">
                &#8377; <?= number_format($closingBalance, 2) ?>
            </div>
            <div style="font-size:11px;color:var(--text-muted);margin-top:2px;">
                <?= $closingBalance > 0 ? 'Client owes you' : ($closingBalance < 0 ? 'Credit balance' : 'Settled') ?>
            </div>
        </div>
    </div>
</div>

<!-- Client Info + Filter -->
<div class="panel" style="margin-bottom:14px;">
    <div class="panel-body" style="padding:10px 16px;">
        <div style="display:flex;align-items:center;gap:16px;flex-wrap:wrap;margin-bottom:10px;">
            <div style="font-size:13px;">
                <i class="fas fa-phone" style="color:var(--text-muted);margin-right:4px;"></i>
                <strong>Phone:</strong> <?= htmlspecialchars($client['phone'] ?: '—') ?>
            </div>
        </div>
        <form method="get" style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
            <input type="hidden" name="client_id" value="<?= $client_id ?>">
            <?php if ($isAdmin && $companies): ?>
            <label style="font-size:13px;font-weight:600;color:var(--text-secondary);margin:0;">Company:</label>
            <select name="co" style="font-size:13px;padding:5px 10px;border:1px solid var(--border);border-radius:6px;">
                <option value="0" <?= $fco == 0 ? 'selected' : '' ?>>All Companies</option>
                <?php while ($co = $companies->fetch_assoc()): ?>
                <option value="<?= $co['id'] ?>" <?= $fco == $co['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($co['company_name']) ?>
                </option>
                <?php endwhile; ?>
            </select>
            <?php else: ?>
            <input type="hidden" name="co" value="<?= $fco ?>">
            <?php endif; ?>
            <label style="font-size:13px;font-weight:600;color:var(--text-secondary);margin:0;">From:</label>
            <input type="date" name="from_date" value="<?= htmlspecialchars($from_date) ?>"
                   style="font-size:13px;padding:5px 10px;border:1px solid var(--border);border-radius:6px;">
            <label style="font-size:13px;font-weight:600;color:var(--text-secondary);margin:0;">To:</label>
            <input type="date" name="to_date" value="<?= htmlspecialchars($to_date) ?>"
                   style="font-size:13px;padding:5px 10px;border:1px solid var(--border);border-radius:6px;">
            <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-filter"></i> Apply</button>
            <?php if ($from_date || $to_date || ($isAdmin && $fco)): ?>
            <a href="view.php?client_id=<?= $client_id ?><?= !$isAdmin ? '&co='.$fco : '' ?>" class="btn btn-secondary btn-sm">
                <i class="fas fa-times"></i> Clear
            </a>
            <?php endif; ?>
        </form>
    </div>
</div>

<!-- Ledger Table -->
<div class="panel">
    <div class="panel-header">
        <span class="panel-title">Transaction Ledger</span>
        <span style="font-size:12px;color:var(--text-muted);"><?= count($transactions) ?> transactions</span>
    </div>
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Type</th>
                    <th>Reference</th>
                    <th style="text-align:right;">Debit (Client Owes)</th>
                    <th style="text-align:right;">Credit (Received/Returned)</th>
                    <th style="text-align:right;">Balance</th>
                    <th style="text-align:center;">Action</th>
                </tr>
            </thead>
            <tbody>
            <?php if (!empty($transactions)): foreach ($transactions as $txn): ?>
            <tr>
                <td><?= date('d-m-Y', strtotime($txn['txn_date'])) ?></td>
                <td>
                    <?php
                    $badgeClass = 'badge-warning';
                    if ($txn['txn_type'] === 'Return')  $badgeClass = 'badge-success';
                    if ($txn['txn_type'] === 'Receipt') $badgeClass = 'badge-primary';
                    ?>
                    <span class="badge <?= $badgeClass ?>"><?= $txn['txn_type'] ?></span>
                </td>
                <td>
                    <?php if ($txn['src'] === 'si'): ?>
                        <a href="../sales/view.php?id=<?= $txn['ref_id'] ?>" style="color:var(--primary);">
                            <?= htmlspecialchars($txn['ref_no']) ?>
                        </a>
                    <?php elseif ($txn['src'] === 'sr'): ?>
                        <a href="../sales_return/view.php?id=<?= $txn['ref_id'] ?>" style="color:var(--primary);">
                            <?= htmlspecialchars($txn['ref_no']) ?>
                        </a>
                    <?php else: ?>
                        <span style="color:var(--text-secondary);"><?= htmlspecialchars($txn['ref_no'] ?: '—') ?></span>
                    <?php endif; ?>
                </td>
                <td style="text-align:right;color:<?= $txn['debit'] > 0 ? 'var(--danger)' : 'var(--text-muted)' ?>;">
                    <?= $txn['debit'] > 0 ? '&#8377; '.number_format($txn['debit'], 2) : '—' ?>
                </td>
                <td style="text-align:right;color:<?= $txn['credit'] > 0 ? 'var(--success)' : 'var(--text-muted)' ?>;">
                    <?= $txn['credit'] > 0 ? '&#8377; '.number_format($txn['credit'], 2) : '—' ?>
                </td>
                <td style="text-align:right;font-weight:600;color:<?= $txn['running_balance'] > 0 ? 'var(--danger)' : 'var(--success)' ?>;">
                    &#8377; <?= number_format($txn['running_balance'], 2) ?>
                </td>
                <td style="text-align:center;">
                    <?php if ($txn['src'] === 'cp'): ?>
                    <a href="delete_payment.php?id=<?= $txn['ref_id'] ?>&client_id=<?= $client_id ?>&co=<?= $fco ?>"
                       class="action-btn delete"
                       onclick="return confirm('Delete this receipt record?')"
                       title="Delete Receipt">
                        <i class="fas fa-trash-alt"></i>
                    </a>
                    <?php else: ?>
                    <span style="color:var(--text-muted);">—</span>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; else: ?>
            <tr><td colspan="7" style="text-align:center;padding:40px;color:var(--text-muted);">
                <i class="fas fa-inbox" style="font-size:28px;display:block;margin-bottom:8px;"></i>
                No transactions found for this client.
            </td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Print Preview Modal -->
<div id="ledgerPrintModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:4000;align-items:center;justify-content:center;">
    <div id="ledgerPrintInner" style="background:#fff;border-radius:10px;display:flex;flex-direction:column;box-shadow:0 8px 40px rgba(0,0,0,.3);max-height:95vh;overflow:hidden;">
        <div style="display:flex;align-items:center;justify-content:space-between;padding:10px 16px;border-bottom:1px solid var(--border);flex-shrink:0;">
            <span id="ledgerPrintTitle" style="font-weight:600;font-size:14px;">Print Preview</span>
            <div style="display:flex;gap:8px;">
                <button onclick="document.getElementById('ledgerPrintFrame').contentWindow.print()" class="btn btn-primary btn-sm">
                    <i class="fas fa-print"></i> Print
                </button>
                <button onclick="closeLedgerPrint()" class="btn btn-secondary btn-sm">
                    <i class="fas fa-times"></i> Close
                </button>
            </div>
        </div>
        <iframe id="ledgerPrintFrame" style="border:none;flex:1;min-height:0;display:block;"></iframe>
    </div>
</div>
<script>
function openLedgerPrint(url, title, format) {
    document.getElementById('ledgerPrintTitle').textContent = title;
    const inner = document.getElementById('ledgerPrintInner');
    if (format === 'thermal') {
        inner.style.width  = '420px';
        inner.style.height = '88vh';
    } else {
        inner.style.width    = '92vw';
        inner.style.maxWidth = '980px';
        inner.style.height   = '92vh';
    }
    document.getElementById('ledgerPrintFrame').src = url;
    document.getElementById('ledgerPrintModal').style.display = 'flex';
}
function closeLedgerPrint() {
    document.getElementById('ledgerPrintModal').style.display = 'none';
    document.getElementById('ledgerPrintFrame').src = '';
}
document.getElementById('ledgerPrintModal').addEventListener('click', function(e) {
    if (e.target === this) closeLedgerPrint();
});
</script>

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