<?php
include '../../includes/header.php';
require_once __DIR__ . '/../../classes/Suppliers.php';
require_once __DIR__ . '/../../includes/payment_options.php';

$suppliers = new Suppliers($conn);
$userId    = (int)$_SESSION['user_id'];
$role      = strtolower((string)($_SESSION['role'] ?? ''));
$isAdminLike = in_array($role, ['admin', 'super_admin', 'controller', 'branch_manager'], true)
    || $auth->isSuperAdmin($userId)
    || $auth->isController($userId);
$error   = '';
$success = '';

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = $_POST['action'] ?? '';

        if ($action === 'create_supplier') {
            $newId   = $suppliers->createSupplier($_POST, $userId);
            $success = 'Supplier created successfully.';

        } elseif ($action === 'update_supplier') {
            $suppliers->updateSupplier((int)$_POST['supplier_id'], $_POST);
            $success = 'Supplier updated.';

        } elseif ($action === 'record_invoice') {
            $suppliers->recordInvoice((int)$_POST['supplier_id'], $_POST, $userId);
            $success = 'Invoice recorded.';

        } elseif ($action === 'record_payment') {
            $suppliers->recordPayment((int)$_POST['supplier_id'], $_POST, $userId);
            $success = 'Payment voucher recorded.';
        }
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$search       = trim($_GET['search'] ?? '');
$filterStatus = $_GET['status'] ?? '';
$supplierList = $suppliers->getSuppliers($filterStatus ?: null, $search ?: null, 300);
$summary      = $suppliers->getSummary();

// Batch-fetch invoices and payments for all visible suppliers
$allInvoices  = [];
$allPayments  = [];
$unpaidMap    = [];  // supplierId → unpaid invoices (for payment modal dropdown)
$sIds = array_column($supplierList, 'supplier_id');
if (!empty($sIds)) {
    $in = implode(',', array_map('intval', $sIds));

    $invRows = $conn->query("
        SELECT si.*, u.username AS recorded_by_name
        FROM supplier_invoices si
        LEFT JOIN users u ON u.user_id = si.recorded_by
        WHERE si.supplier_id IN ($in)
        ORDER BY si.invoice_date DESC, si.invoice_id DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
    foreach ($invRows as $row) {
        $allInvoices[(int)$row['supplier_id']][] = $row;
        if ($row['status'] !== 'paid') {
            $unpaidMap[(int)$row['supplier_id']][] = $row;
        }
    }

    $payRows = $conn->query("
        SELECT sp.*, u.username AS recorded_by_name, si.invoice_number
        FROM supplier_payments sp
        LEFT JOIN users u ON u.user_id = sp.recorded_by
        LEFT JOIN supplier_invoices si ON si.invoice_id = sp.invoice_id
        WHERE sp.supplier_id IN ($in)
        ORDER BY sp.payment_date DESC, sp.payment_id DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
    foreach ($payRows as $row) {
        $allPayments[(int)$row['supplier_id']][] = $row;
    }
}

$invStatusBadge = ['unpaid' => 'bg-danger', 'partial' => 'bg-warning', 'paid' => 'bg-success'];
?>
<style>
    .supplier-detail-row td { background:#F8FAFC; padding:0!important; }
    .supplier-detail-inner { padding:14px 18px; border-top:3px solid #4F46E5; }
    .section-heading { font-size:1rem; font-weight:700; color:#1E293B; border-left:4px solid #4F46E5; padding-left:10px; }
    .supplier-code { font-size:.72rem; font-family:monospace; background:#EEF2FF; color:#4F46E5; padding:2px 6px; border-radius:4px; }
    .nav-tabs .nav-link { font-size:.82rem; }
    .balance-owed { color:#DC2626; font-weight:700; }
    .balance-clear { color:#16A34A; font-weight:700; }
    .search-highlight { background:#FEF08A; }
</style>

<div class="container-fluid px-4 mt-4">

    <div class="d-flex justify-content-between align-items-start mb-3">
        <div>
            <h1>Suppliers / Creditors</h1>
            <p class="text-muted mb-0">Manage suppliers, record purchase invoices and payment vouchers.</p>
        </div>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#supplierModal" id="addSupplierBtn">
            <i class="fas fa-plus me-1"></i> Add Supplier
        </button>
    </div>

    <?php if ($success): ?>
    <div class="alert alert-success alert-dismissible fade show">
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        <?php echo htmlspecialchars($success); ?>
    </div>
    <?php endif; ?>
    <?php if ($error): ?>
    <div class="alert alert-danger alert-dismissible fade show">
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        <?php echo htmlspecialchars($error); ?>
    </div>
    <?php endif; ?>

    <!-- Summary -->
    <div class="row mb-4">
        <div class="col-md-3"><div class="card"><div class="card-body py-3"><div class="text-muted small">Total Suppliers</div><h4 class="mb-0"><?php echo (int)$summary['total_suppliers']; ?> <small class="text-muted" style="font-size:.7rem;">(<?php echo (int)$summary['active_suppliers']; ?> active)</small></h4></div></div></div>
        <div class="col-md-3"><div class="card"><div class="card-body py-3"><div class="text-muted small">Total Invoiced</div><h4 class="mb-0">MWK <?php echo number_format((float)$summary['total_invoiced'], 2); ?></h4></div></div></div>
        <div class="col-md-3"><div class="card"><div class="card-body py-3"><div class="text-muted small">Total Paid</div><h4 class="mb-0">MWK <?php echo number_format((float)$summary['total_paid'], 2); ?></h4></div></div></div>
        <div class="col-md-3"><div class="card border-danger"><div class="card-body py-3"><div class="text-muted small">Outstanding Balance</div><h4 class="mb-0 text-danger">MWK <?php echo number_format((float)$summary['total_balance'], 2); ?></h4></div></div></div>
    </div>

    <!-- Search & Filter -->
    <div class="card mb-3">
        <div class="card-body py-2">
            <form method="get" class="form-inline">
                <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>"
                       class="form-control form-control-sm me-2" placeholder="Search name, code, phone, contact..."
                       style="min-width:280px;">
                <select name="status" class="form-control form-control-sm me-2">
                    <option value="">All Statuses</option>
                    <option value="active"   <?php echo $filterStatus === 'active'   ? 'selected' : ''; ?>>Active</option>
                    <option value="inactive" <?php echo $filterStatus === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                </select>
                <button type="submit" class="btn btn-sm btn-primary me-2"><i class="fas fa-search me-1"></i> Search</button>
                <a href="index.php" class="btn btn-sm btn-outline-secondary">Clear</a>
            </form>
        </div>
    </div>

    <?php if ($search && empty($supplierList)): ?>
    <div class="alert alert-info">
        <i class="fas fa-info-circle me-1"></i>
        No supplier found for <strong><?php echo htmlspecialchars($search); ?></strong>.
        <button type="button" class="btn btn-sm btn-primary ms-3" data-bs-toggle="modal" data-bs-target="#supplierModal"
                data-prefill-name="<?php echo htmlspecialchars($search, ENT_QUOTES); ?>">
            <i class="fas fa-plus me-1"></i> Create "<?php echo htmlspecialchars($search); ?>" as New Supplier
        </button>
    </div>
    <?php endif; ?>

    <!-- Supplier Table -->
    <div class="card">
        <div class="card-header"><span class="section-heading">Supplier List</span></div>
        <div class="card-body pb-1">
            <div class="table-responsive">
                <table class="table table-bordered table-sm table-hover">
                    <thead class="table-dark">
                        <tr>
                            <th style="width:30px;"></th>
                            <th>Code</th>
                            <th>Supplier Name</th>
                            <th>Contact</th>
                            <th>Phone</th>
                            <th class="text-end">Total Invoiced</th>
                            <th class="text-end">Total Paid</th>
                            <th class="text-end">Balance</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if (!$supplierList): ?>
                        <tr><td colspan="10" class="text-center text-muted py-4">No suppliers found. Click <strong>Add Supplier</strong> to get started.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($supplierList as $s):
                        $sid      = (int)$s['supplier_id'];
                        $sInvs    = $allInvoices[$sid] ?? [];
                        $sPays    = $allPayments[$sid] ?? [];
                        $sUnpaid  = $unpaidMap[$sid] ?? [];
                        $invCount = count($sInvs);
                        $payCount = count($sPays);
                        $hasBalance = (float)$s['balance'] > 0;
                        $unpaidJson = htmlspecialchars(json_encode(array_map(fn($i) => [
                            'id'  => (int)$i['invoice_id'],
                            'num' => $i['invoice_number'],
                            'bal' => number_format((float)$i['balance'], 2),
                        ], $sUnpaid)), ENT_QUOTES);
                    ?>
                        <tr class="supplier-row" id="srow-<?php echo $sid; ?>">
                            <td class="text-center">
                                <button type="button" class="btn btn-xs btn-outline-primary toggle-supplier-btn p-0 px-1"
                                        data-target="#sdetail-<?php echo $sid; ?>">
                                    <i class="fas fa-chevron-right" style="font-size:.7rem;"></i>
                                </button>
                            </td>
                            <td>
                                <?php if (!empty($s['supplier_code'])): ?>
                                <span class="supplier-code"><?php echo htmlspecialchars($s['supplier_code']); ?></span>
                                <?php else: ?><span class="text-muted">—</span><?php endif; ?>
                            </td>
                            <td class="fw-bold"><?php echo htmlspecialchars($s['supplier_name']); ?></td>
                            <td><?php echo htmlspecialchars($s['contact_person'] ?? '—'); ?></td>
                            <td><?php echo htmlspecialchars($s['phone'] ?? '—'); ?></td>
                            <td class="text-end">MWK <?php echo number_format((float)$s['total_invoiced'], 2); ?></td>
                            <td class="text-end">MWK <?php echo number_format((float)$s['total_paid'], 2); ?></td>
                            <td class="text-end <?php echo $hasBalance ? 'balance-owed' : 'balance-clear'; ?>">
                                MWK <?php echo number_format((float)$s['balance'], 2); ?>
                            </td>
                            <td>
                                <span class="badge bg-<?php echo $s['status'] === 'active' ? 'success' : 'secondary'; ?>">
                                    <?php echo ucfirst($s['status']); ?>
                                </span>
                            </td>
                            <td style="white-space:nowrap;">
                                <!-- Record Invoice -->
                                <button type="button" class="btn btn-sm btn-outline-info record-invoice-btn me-1"
                                        data-supplier-id="<?php echo $sid; ?>"
                                        data-supplier-name="<?php echo htmlspecialchars($s['supplier_name'], ENT_QUOTES); ?>">
                                    <i class="fas fa-file-invoice me-1"></i>Invoice
                                </button>
                                <!-- Record Payment -->
                                <button type="button" class="btn btn-sm btn-outline-success record-payment-btn me-1"
                                        data-supplier-id="<?php echo $sid; ?>"
                                        data-supplier-name="<?php echo htmlspecialchars($s['supplier_name'], ENT_QUOTES); ?>"
                                        data-balance="<?php echo (float)$s['balance']; ?>"
                                        data-unpaid-invoices="<?php echo $unpaidJson; ?>"
                                        <?php echo !$hasBalance ? 'disabled title="No outstanding balance"' : ''; ?>>
                                    <i class="fas fa-money-check me-1"></i>Pay
                                </button>
                                <!-- Edit -->
                                <button type="button" class="btn btn-sm btn-outline-warning edit-supplier-btn"
                                        data-supplier-id="<?php echo $sid; ?>"
                                        data-supplier-name="<?php echo htmlspecialchars($s['supplier_name'], ENT_QUOTES); ?>"
                                        data-supplier-code="<?php echo htmlspecialchars($s['supplier_code'] ?? '', ENT_QUOTES); ?>"
                                        data-eis-supplier-id="<?php echo htmlspecialchars($s['eis_supplier_id'] ?? '', ENT_QUOTES); ?>"
                                        data-contact-person="<?php echo htmlspecialchars($s['contact_person'] ?? '', ENT_QUOTES); ?>"
                                        data-phone="<?php echo htmlspecialchars($s['phone'] ?? '', ENT_QUOTES); ?>"
                                        data-email="<?php echo htmlspecialchars($s['email'] ?? '', ENT_QUOTES); ?>"
                                        data-address="<?php echo htmlspecialchars($s['address'] ?? '', ENT_QUOTES); ?>"
                                        data-notes="<?php echo htmlspecialchars($s['notes'] ?? '', ENT_QUOTES); ?>"
                                        data-status="<?php echo htmlspecialchars($s['status'], ENT_QUOTES); ?>">
                                    <i class="fas fa-edit"></i>
                                </button>
                            </td>
                        </tr>

                        <!-- Expandable detail row -->
                        <tr class="supplier-detail-row d-none" id="sdetail-<?php echo $sid; ?>">
                            <td colspan="10">
                                <div class="supplier-detail-inner">
                                    <?php if (!empty($s['address']) || !empty($s['email']) || !empty($s['notes'])): ?>
                                    <div class="mb-2 text-muted small">
                                        <?php if (!empty($s['email'])): ?><i class="fas fa-envelope me-1"></i><?php echo htmlspecialchars($s['email']); ?>&nbsp;&nbsp;<?php endif; ?>
                                        <?php if (!empty($s['address'])): ?><i class="fas fa-map-marker-alt me-1"></i><?php echo htmlspecialchars($s['address']); ?>&nbsp;&nbsp;<?php endif; ?>
                                        <?php if (!empty($s['notes'])): ?><i class="fas fa-sticky-note me-1"></i><?php echo htmlspecialchars($s['notes']); ?><?php endif; ?>
                                    </div>
                                    <?php endif; ?>

                                    <!-- Mini tabs: Invoices | Payments -->
                                    <ul class="nav nav-tabs nav-tabs-sm mb-2" id="stabs-<?php echo $sid; ?>">
                                        <li class="nav-item">
                                            <a class="nav-link active" data-bs-toggle="tab" href="#sinv-<?php echo $sid; ?>">
                                                <i class="fas fa-file-invoice me-1"></i>Invoices
                                                <span class="badge bg-secondary ms-1"><?php echo $invCount; ?></span>
                                            </a>
                                        </li>
                                        <li class="nav-item">
                                            <a class="nav-link" data-bs-toggle="tab" href="#spay-<?php echo $sid; ?>">
                                                <i class="fas fa-money-check me-1"></i>Payment Vouchers
                                                <span class="badge bg-secondary ms-1"><?php echo $payCount; ?></span>
                                            </a>
                                        </li>
                                    </ul>

                                    <div class="tab-content">
                                        <!-- Invoices Tab -->
                                        <div class="tab-pane fade show active" id="sinv-<?php echo $sid; ?>">
                                            <?php if ($sInvs): ?>
                                            <div class="table-responsive">
                                                <table class="table table-sm table-bordered mb-0" style="font-size:.82rem;">
                                                    <thead><tr>
                                                        <th>Invoice No.</th>
                                                        <th>Date</th>
                                                        <th>Due Date</th>
                                                        <th>Description</th>
                                                        <th class="text-end">Amount</th>
                                                        <th class="text-end">Paid</th>
                                                        <th class="text-end">Balance</th>
                                                        <th>Status</th>
                                                        <th>Recorded By</th>
                                                    </tr></thead>
                                                    <tbody>
                                                    <?php foreach ($sInvs as $inv): ?>
                                                    <tr>
                                                        <td><code><?php echo htmlspecialchars($inv['invoice_number']); ?></code></td>
                                                        <td><?php echo date('d M Y', strtotime($inv['invoice_date'])); ?></td>
                                                        <td>
                                                            <?php if ($inv['due_date']): ?>
                                                            <?php
                                                            $isDue = strtotime($inv['due_date']) < time() && $inv['status'] !== 'paid';
                                                            echo '<span' . ($isDue ? ' class="text-danger fw-bold"' : '') . '>' . date('d M Y', strtotime($inv['due_date'])) . ($isDue ? ' <i class="fas fa-exclamation-triangle"></i>' : '') . '</span>';
                                                            ?>
                                                            <?php else: ?><span class="text-muted">—</span><?php endif; ?>
                                                        </td>
                                                        <td><?php echo htmlspecialchars($inv['description'] ?? '—'); ?></td>
                                                        <td class="text-end">MWK <?php echo number_format((float)$inv['amount'], 2); ?></td>
                                                        <td class="text-end">MWK <?php echo number_format((float)$inv['amount_paid'], 2); ?></td>
                                                        <td class="text-end <?php echo (float)$inv['balance'] > 0 ? 'text-danger' : 'text-success'; ?>">
                                                            MWK <?php echo number_format((float)$inv['balance'], 2); ?>
                                                        </td>
                                                        <td><span class="badge <?php echo $invStatusBadge[$inv['status']] ?? 'bg-secondary'; ?>"><?php echo ucfirst($inv['status']); ?></span></td>
                                                        <td><small class="text-muted"><?php echo htmlspecialchars($inv['recorded_by_name'] ?? '—'); ?></small></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                    </tbody>
                                                    <tfoot>
                                                        <tr class="table-light fw-bold">
                                                            <td colspan="4" class="text-end">Totals</td>
                                                            <td class="text-end">MWK <?php echo number_format(array_sum(array_column($sInvs, 'amount')), 2); ?></td>
                                                            <td class="text-end">MWK <?php echo number_format(array_sum(array_column($sInvs, 'amount_paid')), 2); ?></td>
                                                            <td class="text-end <?php echo (float)$s['balance'] > 0 ? 'text-danger' : 'text-success'; ?>">MWK <?php echo number_format((float)$s['balance'], 2); ?></td>
                                                            <td colspan="2"></td>
                                                        </tr>
                                                    </tfoot>
                                                </table>
                                            </div>
                                            <?php else: ?>
                                            <p class="text-muted mb-0"><i class="fas fa-inbox me-1"></i> No invoices recorded yet.</p>
                                            <?php endif; ?>
                                        </div>

                                        <!-- Payments Tab -->
                                        <div class="tab-pane fade" id="spay-<?php echo $sid; ?>">
                                            <?php if ($sPays): ?>
                                            <div class="table-responsive">
                                                <table class="table table-sm table-bordered mb-0" style="font-size:.82rem;">
                                                    <thead><tr>
                                                        <th>Voucher No.</th>
                                                        <th>Date</th>
                                                        <th>Against Invoice</th>
                                                        <th class="text-end">Amount</th>
                                                        <th>Method</th>
                                                        <th>Narration</th>
                                                        <th>Recorded By</th>
                                                    </tr></thead>
                                                    <tbody>
                                                    <?php foreach ($sPays as $pay): ?>
                                                    <tr>
                                                        <td><code><?php echo htmlspecialchars($pay['voucher_number'] ?? '—'); ?></code></td>
                                                        <td><?php echo date('d M Y', strtotime($pay['payment_date'])); ?></td>
                                                        <td><?php echo !empty($pay['invoice_number']) ? '<code>' . htmlspecialchars($pay['invoice_number']) . '</code>' : '<span class="text-muted">General</span>'; ?></td>
                                                        <td class="text-end fw-bold">MWK <?php echo number_format((float)$pay['amount'], 2); ?></td>
                                                        <td><?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $pay['payment_method']))); ?></td>
                                                        <td><?php echo htmlspecialchars($pay['narration'] ?? '—'); ?></td>
                                                        <td><small class="text-muted"><?php echo htmlspecialchars($pay['recorded_by_name'] ?? '—'); ?></small></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                    </tbody>
                                                    <tfoot>
                                                        <tr class="table-light fw-bold">
                                                            <td colspan="3" class="text-end">Total Paid</td>
                                                            <td class="text-end text-success">MWK <?php echo number_format(array_sum(array_column($sPays, 'amount')), 2); ?></td>
                                                            <td colspan="3"></td>
                                                        </tr>
                                                    </tfoot>
                                                </table>
                                            </div>
                                            <?php else: ?>
                                            <p class="text-muted mb-0"><i class="fas fa-inbox me-1"></i> No payments recorded yet.</p>
                                            <?php endif; ?>
                                        </div>
                                    </div><!-- /tab-content -->
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- ═══════════════════════════════════
     ADD / EDIT SUPPLIER MODAL
═══════════════════════════════════ -->
<div class="modal fade" id="supplierModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="supplierModalTitle"><i class="fas fa-truck me-1"></i> Add Supplier</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post" id="supplierForm">
                <div class="modal-body">
                    <input type="hidden" name="action" id="supplierAction" value="create_supplier">
                    <input type="hidden" name="supplier_id" id="supplierFormId">
                    <div class="form-row">
                        <div class="form-group col-md-8">
                            <label class="fw-bold">Supplier Name <span class="text-danger">*</span></label>
                            <input type="text" name="supplier_name" id="formSupplierName" class="form-control" required placeholder="e.g. Acme Trading Ltd">
                        </div>
                        <div class="form-group col-md-4">
                            <label class="fw-bold">Supplier Code</label>
                            <input type="text" name="supplier_code" id="formSupplierCode" class="form-control" placeholder="e.g. SUP-001">
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-4">
                            <label class="fw-bold">EIS Supplier ID</label>
                            <input type="number" min="1" name="eis_supplier_id" id="formEisSupplierId" class="form-control" placeholder="ID assigned by MRA EIS">
                            <small class="form-text text-muted">Used when submitting informal purchases (stock receipts) to MRA EIS for this supplier.</small>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label class="fw-bold">Contact Person</label>
                            <input type="text" name="contact_person" id="formContactPerson" class="form-control" placeholder="Name of primary contact">
                        </div>
                        <div class="form-group col-md-6">
                            <label class="fw-bold">Phone</label>
                            <input type="text" name="phone" id="formPhone" class="form-control" placeholder="Phone number">
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label class="fw-bold">Email</label>
                            <input type="email" name="email" id="formEmail" class="form-control" placeholder="supplier@example.com">
                        </div>
                        <div class="form-group col-md-6" id="statusGroup" style="display:none;">
                            <label class="fw-bold">Status</label>
                            <select name="status" id="formStatus" class="form-control">
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="fw-bold">Address</label>
                        <input type="text" name="address" id="formAddress" class="form-control" placeholder="Physical address">
                    </div>
                    <div class="form-group mb-0">
                        <label class="fw-bold">Notes</label>
                        <input type="text" name="notes" id="formNotes" class="form-control" placeholder="Any additional notes...">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary" id="supplierSubmitBtn">
                        <i class="fas fa-save me-1"></i> Save Supplier
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ═══════════════════════════════════
     RECORD INVOICE MODAL
═══════════════════════════════════ -->
<div class="modal fade" id="invoiceModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title"><i class="fas fa-file-invoice me-1"></i> Record Supplier Invoice</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <input type="hidden" name="action" value="record_invoice">
                    <input type="hidden" name="supplier_id" id="invSupplierId">
                    <div class="alert alert-light border mb-3 py-2">
                        <i class="fas fa-building me-1 text-info"></i>
                        Supplier: <strong id="invSupplierName">—</strong>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label class="fw-bold">Invoice Number</label>
                            <input type="text" name="invoice_number" class="form-control" placeholder="Leave blank to auto-generate">
                        </div>
                        <div class="form-group col-md-6">
                            <label class="fw-bold">Invoice Date <span class="text-danger">*</span></label>
                            <input type="date" name="invoice_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label class="fw-bold">Due Date</label>
                            <input type="date" name="due_date" class="form-control">
                        </div>
                        <div class="form-group col-md-6">
                            <label class="fw-bold">Amount (MWK) <span class="text-danger">*</span></label>
                            <input type="number" step="0.01" min="0.01" name="amount" class="form-control" placeholder="0.00" required>
                        </div>
                    </div>
                    <div class="form-group mb-0">
                        <label class="fw-bold">Description / Items</label>
                        <textarea name="description" class="form-control" rows="3" placeholder="e.g. Stock purchase — 20 bags cement, 10 iron sheets..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-info"><i class="fas fa-save me-1"></i> Record Invoice</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ═══════════════════════════════════
     RECORD PAYMENT MODAL
═══════════════════════════════════ -->
<div class="modal fade" id="paymentModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title"><i class="fas fa-money-check me-1"></i> Record Payment Voucher</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <input type="hidden" name="action" value="record_payment">
                    <input type="hidden" name="supplier_id" id="paySupplierId">
                    <div class="alert alert-light border mb-3 py-2">
                        <i class="fas fa-building me-1 text-success"></i>
                        Supplier: <strong id="paySupplierName">—</strong> &nbsp;|&nbsp;
                        Balance: <strong class="text-danger" id="payBalance">MWK 0.00</strong>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label class="fw-bold">Voucher / Reference No.</label>
                            <input type="text" name="voucher_number" class="form-control" placeholder="e.g. PV-001">
                        </div>
                        <div class="form-group col-md-6">
                            <label class="fw-bold">Payment Date <span class="text-danger">*</span></label>
                            <input type="date" name="payment_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="fw-bold">Against Invoice (optional)</label>
                        <select name="invoice_id" id="payInvoiceSelect" class="form-control">
                            <option value="">— General payment (not linked to specific invoice) —</option>
                        </select>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label class="fw-bold">Amount (MWK) <span class="text-danger">*</span></label>
                            <input type="number" step="0.01" min="0.01" name="amount" id="payAmount" class="form-control" placeholder="0.00" required>
                            <small class="text-muted" id="payMaxNote"></small>
                        </div>
                        <div class="form-group col-md-6">
                            <label class="fw-bold">Payment Method</label>
                            <select name="payment_method" class="form-control">
                                <?php echo paymentMethodSelectOptions('cash'); ?>
                            </select>
                        </div>
                    </div>
                    <div class="form-group mb-0">
                        <label class="fw-bold">Narration / Notes</label>
                        <textarea name="narration" class="form-control" rows="2" placeholder="Payment description..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success"><i class="fas fa-save me-1"></i> Record Payment</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Toggle expand row
$(document).on('click', '.toggle-supplier-btn', function () {
    var target = $($(this).data('target'));
    target.toggleClass('d-none');
    $(this).find('i').toggleClass('fa-chevron-right fa-chevron-down');
});

// Add Supplier button (with optional pre-fill from search)
$('#addSupplierBtn').on('click', function () {
    resetSupplierModal('create_supplier', 'Add Supplier');
});

// Pre-fill name from "create X as new supplier" button
$(document).on('click', '[data-prefill-name]', function () {
    resetSupplierModal('create_supplier', 'Add Supplier');
    $('#formSupplierName').val($(this).data('prefill-name'));
});

// Edit supplier button
$(document).on('click', '.edit-supplier-btn', function () {
    var btn = $(this);
    resetSupplierModal('update_supplier', 'Edit Supplier');
    $('#supplierFormId').val(btn.data('supplier-id'));
    $('#formSupplierName').val(btn.data('supplier-name'));
    $('#formSupplierCode').val(btn.data('supplier-code'));
    $('#formEisSupplierId').val(btn.data('eis-supplier-id'));
    $('#formContactPerson').val(btn.data('contact-person'));
    $('#formPhone').val(btn.data('phone'));
    $('#formEmail').val(btn.data('email'));
    $('#formAddress').val(btn.data('address'));
    $('#formNotes').val(btn.data('notes'));
    $('#formStatus').val(btn.data('status'));
    $('#statusGroup').show();
    bootstrap.Modal.getOrCreateInstance(document.getElementById('supplierModal')).show();
});

function resetSupplierModal(action, title) {
    $('#supplierAction').val(action);
    $('#supplierModalTitle').html('<i class="fas fa-truck me-1"></i> ' + title);
    $('#supplierForm')[0].reset();
    $('#supplierFormId').val('');
    $('#statusGroup').hide();
}

// Record Invoice button
$(document).on('click', '.record-invoice-btn', function () {
    var btn = $(this);
    $('#invSupplierId').val(btn.data('supplier-id'));
    $('#invSupplierName').text(btn.data('supplier-name'));
    bootstrap.Modal.getOrCreateInstance(document.getElementById('invoiceModal')).show();
});

// Record Payment button
$(document).on('click', '.record-payment-btn', function () {
    var btn = $(this);
    var balance = parseFloat(btn.data('balance')) || 0;
    var unpaid  = btn.data('unpaid-invoices') || [];
    if (typeof unpaid === 'string') { try { unpaid = JSON.parse(unpaid); } catch(e) { unpaid = []; } }

    $('#paySupplierId').val(btn.data('supplier-id'));
    $('#paySupplierName').text(btn.data('supplier-name'));
    $('#payBalance').text('MWK ' + balance.toLocaleString('en', {minimumFractionDigits:2}));
    $('#payAmount').attr('max', balance).val('');
    $('#payMaxNote').text('Max: MWK ' + balance.toLocaleString('en', {minimumFractionDigits:2}));

    // Populate invoice dropdown
    var sel = $('#payInvoiceSelect').empty();
    sel.append('<option value="">— General payment (not linked to specific invoice) —</option>');
    unpaid.forEach(function(inv) {
        sel.append('<option value="' + inv.id + '">' + inv.num + ' (Balance: MWK ' + inv.bal + ')</option>');
    });
    // When invoice is selected, cap amount to invoice balance
    sel.off('change').on('change', function() {
        var opt = $(this).find(':selected');
        if ($(this).val()) {
            var invBal = parseFloat(opt.text().match(/[\d,]+\.?\d*/g).pop().replace(/,/g,'')) || balance;
            var cap = Math.min(invBal, balance);
            $('#payAmount').attr('max', cap);
            $('#payMaxNote').text('Max: MWK ' + cap.toLocaleString('en', {minimumFractionDigits:2}));
        } else {
            $('#payAmount').attr('max', balance);
            $('#payMaxNote').text('Max: MWK ' + balance.toLocaleString('en', {minimumFractionDigits:2}));
        }
    });

    bootstrap.Modal.getOrCreateInstance(document.getElementById('paymentModal')).show();
});
</script>

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