<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Supplier Ledger';

if (!function_exists('h')) {
    function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('money_fmt')) {
    function money_fmt($amount): string { return number_format((float)$amount, 2); }
}
if (!function_exists('slg_flash')) {
    function slg_flash(string $type, string $message): void {
        $_SESSION['supplier_ledger_flash'][] = ['type' => $type, 'message' => $message];
    }
}
if (!function_exists('slg_get_flash')) {
    function slg_get_flash(): array {
        $items = $_SESSION['supplier_ledger_flash'] ?? [];
        unset($_SESSION['supplier_ledger_flash']);
        return $items;
    }
}
if (!function_exists('slg_column_exists')) {
    function slg_column_exists(PDO $pdo, string $tableName, string $columnName): bool {
        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.columns
            WHERE table_schema = DATABASE()
              AND table_name = :table_name
              AND column_name = :column_name
        ");
        $stmt->execute([':table_name' => $tableName, ':column_name' => $columnName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}

$errors = [];

try {
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS inventory_suppliers (
            id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            supplier_code VARCHAR(60) NULL,
            supplier_name VARCHAR(180) NOT NULL,
            contact_person VARCHAR(150) NULL,
            phone VARCHAR(80) NULL,
            email VARCHAR(150) NULL,
            address TEXT NULL,
            payment_terms VARCHAR(120) NULL,
            tax_number VARCHAR(120) NULL,
            notes TEXT NULL,
            is_active TINYINT(1) NOT NULL DEFAULT 1,
            created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY uq_inventory_supplier_name (supplier_name)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");

    $colCheck = $pdo->prepare("
        SELECT COUNT(*)
        FROM information_schema.columns
        WHERE table_schema = DATABASE()
          AND table_name = 'inventory_suppliers'
          AND column_name = :col
    ");
    foreach ([
        'supplier_code' => "ALTER TABLE inventory_suppliers ADD COLUMN supplier_code VARCHAR(60) NULL AFTER id",
        'contact_person' => "ALTER TABLE inventory_suppliers ADD COLUMN contact_person VARCHAR(150) NULL AFTER supplier_name",
        'payment_terms' => "ALTER TABLE inventory_suppliers ADD COLUMN payment_terms VARCHAR(120) NULL AFTER address",
        'tax_number' => "ALTER TABLE inventory_suppliers ADD COLUMN tax_number VARCHAR(120) NULL AFTER payment_terms",
        'notes' => "ALTER TABLE inventory_suppliers ADD COLUMN notes TEXT NULL AFTER tax_number"
    ] as $col => $sql) {
        $colCheck->execute([':col' => $col]);
        if ((int)$colCheck->fetchColumn() === 0) $pdo->exec($sql);
    }

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS store_locations (
            id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            location_code VARCHAR(50) NULL,
            location_name VARCHAR(150) NOT NULL,
            location_type ENUM('main_store','bar','restaurant','curio','kitchen','housekeeping','maintenance','other') NOT NULL DEFAULT 'main_store',
            is_pos_location TINYINT(1) NOT NULL DEFAULT 0,
            allow_room_charge TINYINT(1) NOT NULL DEFAULT 1,
            is_active TINYINT(1) NOT NULL DEFAULT 1,
            notes TEXT NULL,
            created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY uq_store_location_code (location_code)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS inventory_grns (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            grn_no VARCHAR(60) NOT NULL,
            supplier_id INT UNSIGNED NULL,
            supplier_name VARCHAR(180) NULL,
            store_id INT UNSIGNED NOT NULL,
            po_id BIGINT UNSIGNED NULL,
            invoice_no VARCHAR(100) NULL,
            grn_date DATE NOT NULL,
            subtotal DECIMAL(14,2) NOT NULL DEFAULT 0.00,
            tax_amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
            total_amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
            status ENUM('posted','void') NOT NULL DEFAULT 'posted',
            notes TEXT NULL,
            created_by INT UNSIGNED NULL,
            void_reason TEXT NULL,
            voided_at DATETIME NULL,
            created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY uq_grn_no (grn_no),
            INDEX idx_grn_supplier (supplier_id),
            INDEX idx_grn_store (store_id),
            INDEX idx_grn_date (grn_date)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");

    $colCheck = $pdo->prepare("
        SELECT COUNT(*)
        FROM information_schema.columns
        WHERE table_schema = DATABASE()
          AND table_name = 'inventory_grns'
          AND column_name = :col
    ");
    $colCheck->execute([':col' => 'po_id']);
    if ((int)$colCheck->fetchColumn() === 0) {
        $pdo->exec("ALTER TABLE inventory_grns ADD COLUMN po_id BIGINT UNSIGNED NULL AFTER store_id");
    }

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS inventory_supplier_payments (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            payment_no VARCHAR(60) NOT NULL,
            supplier_id INT UNSIGNED NOT NULL,
            payment_date DATE NOT NULL,
            payment_method VARCHAR(50) NULL,
            reference_no VARCHAR(120) NULL,
            amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
            notes TEXT NULL,
            status ENUM('posted','void') NOT NULL DEFAULT 'posted',
            created_by INT UNSIGNED NULL,
            void_reason TEXT NULL,
            voided_at DATETIME NULL,
            created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY uq_supplier_payment_no (payment_no),
            INDEX idx_supplier_payment_supplier (supplier_id),
            INDEX idx_supplier_payment_date (payment_date)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS inventory_supplier_payment_allocations (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            payment_id BIGINT UNSIGNED NOT NULL,
            grn_id BIGINT UNSIGNED NULL,
            amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
            created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_supplier_payment_alloc_payment (payment_id),
            INDEX idx_supplier_payment_alloc_grn (grn_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
} catch (Throwable $e) {
    $errors[] = 'Could not prepare supplier ledger tables: ' . $e->getMessage();
}

$suppliers = [];
try {
    $suppliers = $pdo->query("
        SELECT *
        FROM inventory_suppliers
        ORDER BY is_active DESC, supplier_name ASC
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $errors[] = 'Could not load suppliers: ' . $e->getMessage();
}

$dateFrom = trim((string)($_GET['date_from'] ?? date('Y-m-01')));
$dateTo = trim((string)($_GET['date_to'] ?? date('Y-m-d')));
$supplierId = (int)($_GET['supplier_id'] ?? 0);
$status = trim((string)($_GET['status'] ?? 'posted'));
$search = trim((string)($_GET['q'] ?? ''));

if (strtotime($dateFrom) === false) $dateFrom = date('Y-m-01');
if (strtotime($dateTo) === false) $dateTo = date('Y-m-d');
if (strtotime($dateFrom) > strtotime($dateTo)) {
    $tmp = $dateFrom; $dateFrom = $dateTo; $dateTo = $tmp;
}

$where = "g.grn_date BETWEEN :date_from AND :date_to";
$params = [':date_from' => $dateFrom, ':date_to' => $dateTo];

if ($supplierId > 0) {
    $where .= " AND g.supplier_id = :supplier_id";
    $params[':supplier_id'] = $supplierId;
}
if ($status !== '') {
    $where .= " AND g.status = :status";
    $params[':status'] = $status;
}
if ($search !== '') {
    $where .= " AND (g.grn_no LIKE :q OR g.invoice_no LIKE :q OR g.supplier_name LIKE :q OR s.supplier_name LIKE :q)";
    $params[':q'] = '%' . $search . '%';
}

$ledgerRows = [];
$summary = [
    'grns' => 0,
    'purchases' => 0,
    'payments' => 0,
    'balance' => 0,
    'voided' => 0,
];

try {
    $stmt = $pdo->prepare("
        SELECT
            g.*,
            COALESCE(s.supplier_name, g.supplier_name, 'Manual Supplier') AS resolved_supplier_name,
            s.supplier_code,
            s.payment_terms,
            sl.location_name,
            COALESCE(pa.paid_amount,0) AS paid_amount,
            (CASE WHEN g.status = 'posted' THEN g.total_amount ELSE 0 END) - COALESCE(pa.paid_amount,0) AS balance_amount,
            DATEDIFF(CURDATE(), g.grn_date) AS age_days
        FROM inventory_grns g
        LEFT JOIN inventory_suppliers s ON s.id = g.supplier_id
        LEFT JOIN store_locations sl ON sl.id = g.store_id
        LEFT JOIN (
            SELECT
                a.grn_id,
                SUM(CASE WHEN p.status = 'posted' THEN a.amount ELSE 0 END) AS paid_amount
            FROM inventory_supplier_payment_allocations a
            INNER JOIN inventory_supplier_payments p ON p.id = a.payment_id
            GROUP BY a.grn_id
        ) pa ON pa.grn_id = g.id
        WHERE $where
        ORDER BY g.grn_date DESC, g.id DESC
        LIMIT 700
    ");
    $stmt->execute($params);
    $ledgerRows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($ledgerRows as $row) {
        $summary['grns']++;
        if ($row['status'] === 'posted') {
            $summary['purchases'] += (float)$row['total_amount'];
            $summary['payments'] += (float)$row['paid_amount'];
            $summary['balance'] += (float)$row['balance_amount'];
        } else {
            $summary['voided'] += (float)$row['total_amount'];
        }
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load supplier ledger: ' . $e->getMessage();
}

$supplierBalances = [];
try {
    $supplierWhere = "1=1";
    $supplierParams = [];

    if ($supplierId > 0) {
        $supplierWhere .= " AND s.id = :supplier_id";
        $supplierParams[':supplier_id'] = $supplierId;
    }

    $stmt = $pdo->prepare("
        SELECT
            s.id,
            s.supplier_code,
            s.supplier_name,
            s.phone,
            s.email,
            s.payment_terms,
            s.is_active,
            COALESCE(g.grn_count,0) AS grn_count,
            COALESCE(g.purchase_total,0) AS purchase_total,
            COALESCE(p.payment_total,0) AS payment_total,
            COALESCE(g.purchase_total,0) - COALESCE(p.payment_total,0) AS balance,
            g.last_grn_date,
            COALESCE(g.age_0_30,0) - COALESCE(p.payment_total,0) AS age_0_30,
            COALESCE(g.age_31_60,0) AS age_31_60,
            COALESCE(g.age_61_90,0) AS age_61_90,
            COALESCE(g.age_90_plus,0) AS age_90_plus
        FROM inventory_suppliers s
        LEFT JOIN (
            SELECT
                supplier_id,
                COUNT(*) AS grn_count,
                SUM(total_amount) AS purchase_total,
                MAX(grn_date) AS last_grn_date,
                SUM(CASE WHEN DATEDIFF(CURDATE(), grn_date) BETWEEN 0 AND 30 THEN total_amount ELSE 0 END) AS age_0_30,
                SUM(CASE WHEN DATEDIFF(CURDATE(), grn_date) BETWEEN 31 AND 60 THEN total_amount ELSE 0 END) AS age_31_60,
                SUM(CASE WHEN DATEDIFF(CURDATE(), grn_date) BETWEEN 61 AND 90 THEN total_amount ELSE 0 END) AS age_61_90,
                SUM(CASE WHEN DATEDIFF(CURDATE(), grn_date) > 90 THEN total_amount ELSE 0 END) AS age_90_plus
            FROM inventory_grns
            WHERE status = 'posted'
              AND supplier_id IS NOT NULL
            GROUP BY supplier_id
        ) g ON g.supplier_id = s.id
        LEFT JOIN (
            SELECT
                supplier_id,
                SUM(amount) AS payment_total
            FROM inventory_supplier_payments
            WHERE status = 'posted'
            GROUP BY supplier_id
        ) p ON p.supplier_id = s.id
        WHERE $supplierWhere
        ORDER BY balance DESC, s.supplier_name ASC
        LIMIT 300
    ");
    $stmt->execute($supplierParams);
    $supplierBalances = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $errors[] = 'Could not load supplier balances: ' . $e->getMessage();
}

$viewSupplierId = (int)($_GET['view_supplier_id'] ?? 0);
$viewSupplier = null;
$viewPayments = [];
$viewGrns = [];

if ($viewSupplierId > 0) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM inventory_suppliers WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $viewSupplierId]);
        $viewSupplier = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;

        if ($viewSupplier) {
            $stmt = $pdo->prepare("
                SELECT
                    g.*,
                    sl.location_name,
                    COALESCE(pa.paid_amount,0) AS paid_amount,
                    g.total_amount - COALESCE(pa.paid_amount,0) AS balance_amount
                FROM inventory_grns g
                LEFT JOIN store_locations sl ON sl.id = g.store_id
                LEFT JOIN (
                    SELECT
                        a.grn_id,
                        SUM(CASE WHEN p.status = 'posted' THEN a.amount ELSE 0 END) AS paid_amount
                    FROM inventory_supplier_payment_allocations a
                    INNER JOIN inventory_supplier_payments p ON p.id = a.payment_id
                    GROUP BY a.grn_id
                ) pa ON pa.grn_id = g.id
                WHERE g.supplier_id = :supplier_id
                ORDER BY g.grn_date DESC, g.id DESC
                LIMIT 100
            ");
            $stmt->execute([':supplier_id' => $viewSupplierId]);
            $viewGrns = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $stmt = $pdo->prepare("
                SELECT *
                FROM inventory_supplier_payments
                WHERE supplier_id = :supplier_id
                ORDER BY payment_date DESC, id DESC
                LIMIT 100
            ");
            $stmt->execute([':supplier_id' => $viewSupplierId]);
            $viewPayments = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
    } catch (Throwable $e) {
        $errors[] = 'Could not load supplier drill-down: ' . $e->getMessage();
    }
}

$flashes = slg_get_flash();

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-journal-text"></i> Stores &amp; POS Inventory</div>
            <div class="hero-title mt-2">Supplier Ledger</div>
            <div class="hero-subtitle mt-2">
                Track supplier purchases from GRNs, payment allocations and outstanding balances.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="suppliers.php" class="btn btn-light me-2">
                <i class="bi bi-people me-2"></i>Suppliers
            </a>
            <a href="grn.php" class="btn btn-outline-light">
                <i class="bi bi-truck me-2"></i>GRN / Purchases
            </a>
        </div>
    </div>
</div>

<?php foreach ($flashes as $flash): ?>
    <div class="alert alert-<?php echo h($flash['type']); ?>"><?php echo h($flash['message']); ?></div>
<?php endforeach; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0"><?php foreach ($errors as $err): ?><li><?php echo h($err); ?></li><?php endforeach; ?></ul>
    </div>
<?php endif; ?>

<div class="row g-4 mb-4">
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-receipt"></i></div>
            <div><div class="metric-label">GRNs</div><div class="metric-value"><?php echo (int)$summary['grns']; ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-cash-stack"></i></div>
            <div><div class="metric-label">Purchases</div><div class="metric-value small-value"><?php echo money_fmt($summary['purchases']); ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-success-subtle text-success"><i class="bi bi-check-circle"></i></div>
            <div><div class="metric-label">Payments</div><div class="metric-value small-value"><?php echo money_fmt($summary['payments']); ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-danger-subtle text-danger"><i class="bi bi-exclamation-triangle"></i></div>
            <div><div class="metric-label">Balance</div><div class="metric-value small-value"><?php echo money_fmt($summary['balance']); ?></div></div>
        </div>
    </div>
</div>

<?php if ($viewSupplier): ?>
<div class="card panel-card mb-4 supplier-view">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><?php echo h($viewSupplier['supplier_name']); ?> Ledger Detail</h5>
        <a href="supplier_ledger.php" class="btn btn-sm btn-outline-secondary">Close</a>
    </div>
    <div class="card-body">
        <div class="row g-3 mb-4">
            <div class="col-md-3"><strong>Code:</strong><br><?php echo h($viewSupplier['supplier_code'] ?: '—'); ?></div>
            <div class="col-md-3"><strong>Contact:</strong><br><?php echo h($viewSupplier['contact_person'] ?: '—'); ?></div>
            <div class="col-md-3"><strong>Phone:</strong><br><?php echo h($viewSupplier['phone'] ?: '—'); ?></div>
            <div class="col-md-3"><strong>Terms:</strong><br><?php echo h($viewSupplier['payment_terms'] ?: '—'); ?></div>
        </div>

        <h6 class="fw-bold">GRNs / Purchase Invoices</h6>
        <div class="table-responsive mb-4">
            <table class="table table-sm align-middle">
                <thead><tr><th>Date</th><th>GRN</th><th>Invoice</th><th>Store</th><th>Status</th><th class="text-end">Total</th><th class="text-end">Paid</th><th class="text-end">Balance</th><th></th></tr></thead>
                <tbody>
                <?php if (!$viewGrns): ?>
                    <tr><td colspan="9" class="text-center text-muted py-3">No GRNs for this supplier.</td></tr>
                <?php else: ?>
                    <?php foreach ($viewGrns as $g): ?>
                        <tr class="<?php echo $g['status'] === 'void' ? 'table-danger' : ''; ?>">
                            <td><?php echo h($g['grn_date']); ?></td>
                            <td><strong><?php echo h($g['grn_no']); ?></strong></td>
                            <td><?php echo h($g['invoice_no'] ?: '—'); ?></td>
                            <td><?php echo h($g['location_name'] ?: 'Store'); ?></td>
                            <td><span class="badge <?php echo $g['status'] === 'posted' ? 'text-bg-success' : 'text-bg-danger'; ?>"><?php echo h(ucwords($g['status'])); ?></span></td>
                            <td class="text-end"><?php echo money_fmt($g['total_amount']); ?></td>
                            <td class="text-end"><?php echo money_fmt($g['paid_amount']); ?></td>
                            <td class="text-end fw-bold"><?php echo money_fmt($g['balance_amount']); ?></td>
                            <td class="text-end"><a href="grn.php?view_id=<?php echo (int)$g['id']; ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-eye"></i></a></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <h6 class="fw-bold">Payments</h6>
        <div class="table-responsive">
            <table class="table table-sm align-middle mb-0">
                <thead><tr><th>Date</th><th>Payment No</th><th>Method</th><th>Reference</th><th>Status</th><th class="text-end">Amount</th></tr></thead>
                <tbody>
                <?php if (!$viewPayments): ?>
                    <tr><td colspan="6" class="text-center text-muted py-3">No payments captured yet.</td></tr>
                <?php else: ?>
                    <?php foreach ($viewPayments as $p): ?>
                        <tr class="<?php echo $p['status'] === 'void' ? 'table-danger' : ''; ?>">
                            <td><?php echo h($p['payment_date']); ?></td>
                            <td><strong><?php echo h($p['payment_no']); ?></strong></td>
                            <td><?php echo h($p['payment_method'] ?: '—'); ?></td>
                            <td><?php echo h($p['reference_no'] ?: '—'); ?></td>
                            <td><span class="badge <?php echo $p['status'] === 'posted' ? 'text-bg-success' : 'text-bg-danger'; ?>"><?php echo h(ucwords($p['status'])); ?></span></td>
                            <td class="text-end fw-bold"><?php echo money_fmt($p['amount']); ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="card panel-card mb-4">
    <div class="card-body">
        <form method="get" class="row g-3 align-items-end">
            <div class="col-md-2">
                <label class="form-label">From</label>
                <input type="date" name="date_from" class="form-control" value="<?php echo h($dateFrom); ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">To</label>
                <input type="date" name="date_to" class="form-control" value="<?php echo h($dateTo); ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label">Supplier</label>
                <select name="supplier_id" class="form-select">
                    <option value="0">All suppliers</option>
                    <?php foreach ($suppliers as $s): ?>
                        <option value="<?php echo (int)$s['id']; ?>" <?php echo $supplierId === (int)$s['id'] ? 'selected' : ''; ?>>
                            <?php echo h($s['supplier_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">GRN Status</label>
                <select name="status" class="form-select">
                    <option value="">All</option>
                    <option value="posted" <?php echo $status === 'posted' ? 'selected' : ''; ?>>Posted</option>
                    <option value="void" <?php echo $status === 'void' ? 'selected' : ''; ?>>Void</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Search</label>
                <input type="text" name="q" class="form-control" value="<?php echo h($search); ?>" placeholder="GRN / invoice / supplier">
            </div>
            <div class="col-md-1 d-grid">
                <button class="btn btn-primary"><i class="bi bi-funnel"></i></button>
            </div>
        </form>
    </div>
</div>

<div class="row g-4">
    <div class="col-xl-5">
        <div class="card panel-card h-100">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Supplier Balances</h5>
                <span class="text-muted small"><?php echo count($supplierBalances); ?> supplier(s)</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                        <tr>
                            <th>Supplier</th>
                            <th class="text-end">Purchases</th>
                            <th class="text-end">Payments</th>
                            <th class="text-end">Balance</th>
                            <th></th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$supplierBalances): ?>
                            <tr><td colspan="5" class="text-center text-muted py-4">No supplier balances found.</td></tr>
                        <?php else: ?>
                            <?php foreach ($supplierBalances as $row): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo h($row['supplier_name']); ?></strong>
                                        <div class="small text-muted">
                                            <?php echo h($row['supplier_code'] ?: ''); ?>
                                            <?php if (!empty($row['payment_terms'])): ?> • <?php echo h($row['payment_terms']); ?><?php endif; ?>
                                        </div>
                                    </td>
                                    <td class="text-end"><?php echo money_fmt($row['purchase_total']); ?></td>
                                    <td class="text-end"><?php echo money_fmt($row['payment_total']); ?></td>
                                    <td class="text-end fw-bold <?php echo (float)$row['balance'] > 0 ? 'text-danger' : 'text-success'; ?>">
                                        <?php echo money_fmt($row['balance']); ?>
                                    </td>
                                    <td class="text-end">
                                        <a href="supplier_ledger.php?view_supplier_id=<?php echo (int)$row['id']; ?>" class="btn btn-sm btn-outline-primary">
                                            <i class="bi bi-eye"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="card-footer small text-muted">
                Ageing is purchase-based. Once supplier payments are added, allocations reduce balances.
            </div>
        </div>
    </div>

    <div class="col-xl-7">
        <div class="card panel-card h-100">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">GRN Ledger</h5>
                <span class="text-muted small">Showing latest 700 matching GRNs</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                        <tr>
                            <th>Date</th>
                            <th>Supplier</th>
                            <th>GRN / Invoice</th>
                            <th>Store</th>
                            <th class="text-end">Age</th>
                            <th class="text-end">Total</th>
                            <th class="text-end">Paid</th>
                            <th class="text-end">Balance</th>
                            <th></th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$ledgerRows): ?>
                            <tr><td colspan="9" class="text-center text-muted py-4">No ledger rows found.</td></tr>
                        <?php else: ?>
                            <?php foreach ($ledgerRows as $row): ?>
                                <tr class="<?php echo $row['status'] === 'void' ? 'table-danger' : ''; ?>">
                                    <td><?php echo h($row['grn_date']); ?></td>
                                    <td>
                                        <strong><?php echo h($row['resolved_supplier_name']); ?></strong>
                                        <div class="small text-muted"><?php echo h($row['payment_terms'] ?: ''); ?></div>
                                    </td>
                                    <td>
                                        <strong><?php echo h($row['grn_no']); ?></strong>
                                        <div class="small text-muted">Invoice: <?php echo h($row['invoice_no'] ?: '—'); ?></div>
                                    </td>
                                    <td><?php echo h($row['location_name'] ?: 'Store'); ?></td>
                                    <td class="text-end"><?php echo (int)$row['age_days']; ?>d</td>
                                    <td class="text-end"><?php echo money_fmt($row['total_amount']); ?></td>
                                    <td class="text-end"><?php echo money_fmt($row['paid_amount']); ?></td>
                                    <td class="text-end fw-bold <?php echo (float)$row['balance_amount'] > 0 ? 'text-danger' : 'text-success'; ?>">
                                        <?php echo money_fmt($row['balance_amount']); ?>
                                    </td>
                                    <td class="text-end">
                                        <a href="grn.php?view_id=<?php echo (int)$row['id']; ?>" class="btn btn-sm btn-outline-primary">
                                            <i class="bi bi-eye"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="alert alert-info mt-4">
    <strong>Next step:</strong> build <code>supplier_payments.php</code> so payments can be captured and allocated against GRNs.
</div>

<style>
.small-value{font-size:1rem!important;letter-spacing:0!important}
.supplier-view{border:2px solid rgba(37,99,235,.18)}
</style>

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