<?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;
}

$client_id = intval($_GET['client_id'] ?? 0);
$fco       = intval($_GET['co'] ?? 0);
$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'";
}

// UNION ALL query for all transactions
$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
    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
    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
    FROM client_payments cp
    WHERE cp.client_id = $client_id $coWhere $dateFrom $dateTo

    ORDER BY txn_date ASC, src ASC
";

$result = $conn->query($sql);

// Compute running balance and summary
$totalInvoiced = 0;
$totalReturns  = 0;
$totalReceived = 0;
$runningBalance = 0;
$transactions   = [];

if ($result) {
    while ($row = $result->fetch_assoc()) {
        $runningBalance += $row['debit'] - $row['credit'];
        $row['running_balance'] = $runningBalance;
        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;
    }
}
$closingBalance = $totalInvoiced - $totalReturns - $totalReceived;

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

<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>
        <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 ?>">
            <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>
            <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 || $fco): ?>
            <a href="view.php?client_id=<?= $client_id ?>" 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>

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