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


// Create vendor_payments table if not exists
$conn->query("
    CREATE TABLE IF NOT EXISTS vendor_payments (
        id INT AUTO_INCREMENT PRIMARY KEY,
        vendor_id INT NOT NULL,
        company_id INT NOT NULL,
        payment_date DATE NOT NULL,
        amount DECIMAL(12,2) NOT NULL,
        payment_mode VARCHAR(30) DEFAULT 'Cash',
        reference_no VARCHAR(100),
        notes TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
");

// Company filter — only admin can switch companies
$userRole = $_SESSION['user_role'] ?? '';
$isAdmin  = ($userRole === 'admin');
$fco      = $isAdmin ? (isset($_GET['co']) ? (int)$_GET['co'] : $cid) : $cid;
$companies = $isAdmin ? $conn->query("SELECT id, company_name FROM company_master ORDER BY company_name") : null;

// Search filter
$search = trim($_GET['search'] ?? '');

// Build vendor list query
$coWhere  = $fco > 0 ? "AND v.company_id = $fco" : "";
$srchWhere = '';
if ($search !== '') {
    $s = $conn->real_escape_string($search);
    $srchWhere = "AND (v.name LIKE '%$s%' OR v.phone LIKE '%$s%')";
}

$vendors = $conn->query("
    SELECT v.id, v.name, v.phone,
        COALESCE((SELECT SUM(po.net_amount) FROM purchase_orders po
                  WHERE po.vendor_id = v.id AND po.status='final'
                    AND ($fco = 0 OR po.company_id = $fco)), 0) AS total_purchased,
        COALESCE((SELECT SUM(pr.net_amount) FROM purchase_returns pr
                  WHERE pr.vendor_id = v.id AND pr.status='final'
                    AND ($fco = 0 OR pr.company_id = $fco)), 0) AS total_returns,
        COALESCE((SELECT SUM(vp.amount) FROM vendor_payments vp
                  WHERE vp.vendor_id = v.id
                    AND ($fco = 0 OR vp.company_id = $fco)), 0) +
        COALESCE((SELECT SUM(pp.amount) FROM purchase_payments pp
                  JOIN purchase_orders po ON po.id = pp.purchase_order_id
                  WHERE po.vendor_id = v.id
                    AND ($fco = 0 OR po.company_id = $fco)), 0) AS total_paid
    FROM vendors v
    WHERE v.status = 1 $coWhere $srchWhere
    ORDER BY v.name
");

// Compute overall outstanding
$totalOutstanding = 0;
$vendorRows = [];
while ($row = $vendors->fetch_assoc()) {
    $row['balance'] = $row['total_purchased'] - $row['total_returns'] - $row['total_paid'];
    $totalOutstanding += $row['balance'];
    $vendorRows[] = $row;
}
?>

<div class="page-header">
    <h2><i class="fas fa-industry" style="color:var(--primary);margin-right:8px;"></i>Vendor Ledger</h2>
</div>

<!-- Summary banner -->
<div class="panel" style="margin-bottom:16px;border-left:4px solid <?= $totalOutstanding > 0 ? 'var(--danger)' : 'var(--success)' ?>;">
    <div class="panel-body" style="padding:14px 20px;display:flex;align-items:center;gap:12px;">
        <i class="fas fa-wallet" style="font-size:22px;color:<?= $totalOutstanding > 0 ? 'var(--danger)' : 'var(--success)' ?>;"></i>
        <div>
            <div style="font-size:12px;color:var(--text-secondary);font-weight:600;text-transform:uppercase;letter-spacing:.05em;">Total Outstanding Balance (All Vendors)</div>
            <div style="font-size:22px;font-weight:700;color:<?= $totalOutstanding > 0 ? 'var(--danger)' : 'var(--success)' ?>;">
                &#8377; <?= number_format($totalOutstanding, 2) ?>
            </div>
        </div>
    </div>
</div>

<!-- Filters -->
<div class="panel" style="margin-bottom:14px;">
    <div class="panel-body" style="padding:10px 16px;">
        <form method="get" style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
            <?php if ($isAdmin && $companies): ?>
            <label style="font-size:13px;font-weight:600;color:var(--text-secondary);margin:0;">Company:</label>
            <select name="co" onchange="this.form.submit()" 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
                $companies->data_seek(0);
                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; ?>
            <input type="text" name="search" placeholder="Search vendor name, phone..."
                   value="<?= htmlspecialchars($search) ?>"
                   style="font-size:13px;padding:5px 10px;border:1px solid var(--border);border-radius:6px;min-width:200px;">
            <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-search"></i> Search</button>
            <?php if ($search || ($isAdmin && $fco != $cid)): ?>
            <a href="index.php" class="btn btn-secondary btn-sm"><i class="fas fa-times"></i> Clear</a>
            <?php endif; ?>
        </form>
    </div>
</div>

<!-- Vendor Table -->
<div class="panel">
    <div class="panel-header">
        <span class="panel-title">Vendor Balances</span>
        <span style="font-size:12px;color:var(--text-muted);"><?= count($vendorRows) ?> vendors</span>
    </div>
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>Vendor</th>
                    <th>Phone</th>
                    <th style="text-align:right;">Total Purchased</th>
                    <th style="text-align:right;">Total Returns</th>
                    <th style="text-align:right;">Total Paid</th>
                    <th style="text-align:right;">Balance</th>
                    <th style="text-align:center;">Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if (!empty($vendorRows)): foreach ($vendorRows as $row): ?>
            <tr>
                <td>
                    <a href="view.php?vendor_id=<?= $row['id'] ?>&co=<?= $fco ?>"
                       style="font-weight:600;color:var(--primary);">
                        <?= htmlspecialchars($row['name']) ?>
                    </a>
                </td>
                <td style="color:var(--text-secondary);"><?= htmlspecialchars($row['phone']) ?></td>
                <td style="text-align:right;">&#8377; <?= number_format($row['total_purchased'], 2) ?></td>
                <td style="text-align:right;">&#8377; <?= number_format($row['total_returns'], 2) ?></td>
                <td style="text-align:right;">&#8377; <?= number_format($row['total_paid'], 2) ?></td>
                <td style="text-align:right;font-weight:700;color:<?= $row['balance'] > 0 ? 'var(--danger)' : 'var(--success)' ?>;">
                    &#8377; <?= number_format($row['balance'], 2) ?>
                </td>
                <td>
                    <div class="action-links" style="justify-content:center;gap:6px;">
                        <a href="view.php?vendor_id=<?= $row['id'] ?>&co=<?= $fco ?>"
                           class="action-btn view" title="View Ledger">
                            <i class="fas fa-eye"></i>
                        </a>
                        <a href="add_payment.php?vendor_id=<?= $row['id'] ?>"
                           class="btn btn-success btn-sm" title="Add Payment"
                           style="padding:3px 10px;font-size:12px;">
                            <i class="fas fa-plus"></i> Pay
                        </a>
                    </div>
                </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 vendors found.
            </td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

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