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

$pageTitle = 'Supplier Payments';

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('sp_flash')) {
    function sp_flash(string $type, string $message): void {
        $_SESSION['supplier_payments_flash'][] = ['type' => $type, 'message' => $message];
    }
}
if (!function_exists('sp_get_flash')) {
    function sp_get_flash(): array {
        $items = $_SESSION['supplier_payments_flash'] ?? [];
        unset($_SESSION['supplier_payments_flash']);
        return $items;
    }
}
if (!function_exists('sp_column_exists')) {
    function sp_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;
    }
}
if (!function_exists('supplier_payment_no')) {
    function supplier_payment_no(PDO $pdo): string {
        $prefix = 'SP-' . date('ymd') . '-';
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM inventory_supplier_payments WHERE payment_no LIKE :p");
        $stmt->execute([':p' => $prefix . '%']);
        return $prefix . str_pad((string)((int)$stmt->fetchColumn() + 1), 4, '0', STR_PAD_LEFT);
    }
}

$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
    ");

    $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 payment tables: ' . $e->getMessage();
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (function_exists('verify_csrf')) verify_csrf();

        $action = (string)($_POST['action'] ?? '');

        if ($action === 'post_payment') {
            $supplierId = (int)($_POST['supplier_id'] ?? 0);
            $paymentDate = trim((string)($_POST['payment_date'] ?? date('Y-m-d')));
            $paymentMethod = trim((string)($_POST['payment_method'] ?? 'cash'));
            $referenceNo = trim((string)($_POST['reference_no'] ?? ''));
            $amount = (float)($_POST['amount'] ?? 0);
            $notes = trim((string)($_POST['notes'] ?? ''));
            $allocations = $_POST['allocations'] ?? [];

            if ($supplierId <= 0) throw new RuntimeException('Please select supplier.');
            if ($amount <= 0) throw new RuntimeException('Payment amount must be greater than zero.');
            if (strtotime($paymentDate) === false) $paymentDate = date('Y-m-d');

            $stmt = $pdo->prepare("SELECT * FROM inventory_suppliers WHERE id = :id LIMIT 1");
            $stmt->execute([':id' => $supplierId]);
            $supplier = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$supplier) throw new RuntimeException('Supplier not found.');

            $totalAllocated = 0.0;
            $cleanAllocations = [];

            foreach ($allocations as $grnId => $allocAmount) {
                $grnId = (int)$grnId;
                $allocAmount = (float)$allocAmount;
                if ($grnId <= 0 || $allocAmount <= 0) continue;

                $stmt = $pdo->prepare("
                    SELECT
                        g.*,
                        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 (
                        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.id = :grn_id
                      AND g.supplier_id = :supplier_id
                      AND g.status = 'posted'
                    LIMIT 1
                ");
                $stmt->execute([':grn_id' => $grnId, ':supplier_id' => $supplierId]);
                $grn = $stmt->fetch(PDO::FETCH_ASSOC);

                if (!$grn) {
                    throw new RuntimeException('Invalid GRN allocation selected.');
                }

                $balance = (float)$grn['balance_amount'];
                if ($allocAmount > $balance + 0.01) {
                    throw new RuntimeException('Allocation for ' . $grn['grn_no'] . ' exceeds outstanding balance.');
                }

                $totalAllocated += $allocAmount;
                $cleanAllocations[] = [
                    'grn_id' => $grnId,
                    'amount' => round($allocAmount, 2),
                ];
            }

            if ($totalAllocated > $amount + 0.01) {
                throw new RuntimeException('Total allocations cannot exceed payment amount.');
            }

            /*
             * If user captures amount but leaves allocations empty:
             * save as unallocated payment. Ledger supplier total will still reduce supplier balance,
             * and allocations can be added later if required.
             */
            $pdo->beginTransaction();

            $paymentNo = supplier_payment_no($pdo);
            $stmt = $pdo->prepare("
                INSERT INTO inventory_supplier_payments
                (payment_no, supplier_id, payment_date, payment_method, reference_no, amount, notes, status, created_by)
                VALUES
                (:payment_no, :supplier_id, :payment_date, :payment_method, :reference_no, :amount, :notes, 'posted', :created_by)
            ");
            $stmt->execute([
                ':payment_no' => $paymentNo,
                ':supplier_id' => $supplierId,
                ':payment_date' => date('Y-m-d', strtotime($paymentDate)),
                ':payment_method' => $paymentMethod ?: null,
                ':reference_no' => $referenceNo ?: null,
                ':amount' => round($amount, 2),
                ':notes' => $notes ?: null,
                ':created_by' => $_SESSION['user_id'] ?? null,
            ]);
            $paymentId = (int)$pdo->lastInsertId();

            if ($cleanAllocations) {
                $stmt = $pdo->prepare("
                    INSERT INTO inventory_supplier_payment_allocations
                    (payment_id, grn_id, amount)
                    VALUES
                    (:payment_id, :grn_id, :amount)
                ");
                foreach ($cleanAllocations as $a) {
                    $stmt->execute([
                        ':payment_id' => $paymentId,
                        ':grn_id' => $a['grn_id'],
                        ':amount' => $a['amount'],
                    ]);
                }
            }

            $pdo->commit();

            sp_flash('success', 'Supplier payment posted: ' . $paymentNo);
            header('Location: supplier_payments.php?view_id=' . $paymentId);
            exit;
        }

        if ($action === 'void_payment') {
            $paymentId = (int)($_POST['payment_id'] ?? 0);
            $reason = trim((string)($_POST['void_reason'] ?? ''));

            if ($paymentId <= 0) throw new RuntimeException('Invalid supplier payment selected.');
            if ($reason === '') throw new RuntimeException('Void reason is required.');

            $stmt = $pdo->prepare("SELECT * FROM inventory_supplier_payments WHERE id = :id LIMIT 1");
            $stmt->execute([':id' => $paymentId]);
            $payment = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$payment) throw new RuntimeException('Payment not found.');
            if ($payment['status'] === 'void') throw new RuntimeException('Payment is already voided.');

            $stmt = $pdo->prepare("
                UPDATE inventory_supplier_payments
                SET status = 'void',
                    void_reason = :reason,
                    voided_at = NOW()
                WHERE id = :id
            ");
            $stmt->execute([':reason' => $reason, ':id' => $paymentId]);

            sp_flash('success', 'Supplier payment voided. Allocations are ignored by ledger because payment is void.');
            header('Location: supplier_payments.php?view_id=' . $paymentId);
            exit;
        }

        if ($action === 'auto_allocate') {
            $supplierId = (int)($_POST['supplier_id'] ?? 0);
            $paymentAmount = (float)($_POST['amount'] ?? 0);

            if ($supplierId <= 0) throw new RuntimeException('Please select supplier first.');
            if ($paymentAmount <= 0) throw new RuntimeException('Enter payment amount first.');

            header('Location: supplier_payments.php?supplier_id=' . $supplierId . '&amount=' . $paymentAmount . '&auto=1');
            exit;
        }

    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        sp_flash('danger', $e->getMessage());
        header('Location: supplier_payments.php');
        exit;
    }
}

$suppliers = [];
try {
    $suppliers = $pdo->query("
        SELECT
            s.*,
            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
        FROM inventory_suppliers s
        LEFT JOIN (
            SELECT supplier_id, SUM(total_amount) AS purchase_total
            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 s.is_active = 1
        ORDER BY s.supplier_name ASC
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $errors[] = 'Could not load suppliers: ' . $e->getMessage();
}

$selectedSupplierId = (int)($_GET['supplier_id'] ?? $_POST['supplier_id'] ?? 0);
$prefillAmount = (float)($_GET['amount'] ?? 0);
$autoAllocate = (int)($_GET['auto'] ?? 0) === 1;

$outstandingGrns = [];
if ($selectedSupplierId > 0) {
    try {
        $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,
                DATEDIFF(CURDATE(), g.grn_date) AS age_days
            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
              AND g.status = 'posted'
              AND (g.total_amount - COALESCE(pa.paid_amount,0)) > 0.009
            ORDER BY g.grn_date ASC, g.id ASC
            LIMIT 200
        ");
        $stmt->execute([':supplier_id' => $selectedSupplierId]);
        $outstandingGrns = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if ($autoAllocate && $prefillAmount > 0) {
            $remaining = $prefillAmount;
            foreach ($outstandingGrns as &$g) {
                $bal = (float)$g['balance_amount'];
                $alloc = min($remaining, $bal);
                $g['auto_alloc'] = $alloc > 0 ? $alloc : 0;
                $remaining -= $alloc;
                if ($remaining <= 0) break;
            }
            unset($g);
        }
    } catch (Throwable $e) {
        $errors[] = 'Could not load outstanding GRNs: ' . $e->getMessage();
    }
}

$dateFrom = trim((string)($_GET['date_from'] ?? date('Y-m-01')));
$dateTo = trim((string)($_GET['date_to'] ?? date('Y-m-d')));
$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 = "p.payment_date BETWEEN :date_from AND :date_to";
$params = [':date_from' => $dateFrom, ':date_to' => $dateTo];

if ($selectedSupplierId > 0) {
    $where .= " AND p.supplier_id = :supplier_id";
    $params[':supplier_id'] = $selectedSupplierId;
}
if ($status !== '') {
    $where .= " AND p.status = :status";
    $params[':status'] = $status;
}
if ($search !== '') {
    $where .= " AND (p.payment_no LIKE :q OR p.reference_no LIKE :q OR s.supplier_name LIKE :q OR p.payment_method LIKE :q)";
    $params[':q'] = '%' . $search . '%';
}

$payments = [];
$summary = ['count' => 0, 'posted' => 0, 'voided' => 0, 'allocated' => 0, 'unallocated' => 0];

try {
    $stmt = $pdo->prepare("
        SELECT
            p.*,
            s.supplier_name,
            s.supplier_code,
            COALESCE(a.allocated_amount,0) AS allocated_amount,
            p.amount - COALESCE(a.allocated_amount,0) AS unallocated_amount
        FROM inventory_supplier_payments p
        INNER JOIN inventory_suppliers s ON s.id = p.supplier_id
        LEFT JOIN (
            SELECT payment_id, SUM(amount) AS allocated_amount
            FROM inventory_supplier_payment_allocations
            GROUP BY payment_id
        ) a ON a.payment_id = p.id
        WHERE $where
        ORDER BY p.payment_date DESC, p.id DESC
        LIMIT 500
    ");
    $stmt->execute($params);
    $payments = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($payments as $p) {
        $summary['count']++;
        if ($p['status'] === 'posted') {
            $summary['posted'] += (float)$p['amount'];
            $summary['allocated'] += (float)$p['allocated_amount'];
            $summary['unallocated'] += (float)$p['unallocated_amount'];
        } else {
            $summary['voided'] += (float)$p['amount'];
        }
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load supplier payments: ' . $e->getMessage();
}

$viewId = (int)($_GET['view_id'] ?? 0);
$viewPayment = null;
$viewAllocations = [];

if ($viewId > 0) {
    try {
        $stmt = $pdo->prepare("
            SELECT p.*, s.supplier_name, s.supplier_code, s.phone, s.email
            FROM inventory_supplier_payments p
            INNER JOIN inventory_suppliers s ON s.id = p.supplier_id
            WHERE p.id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $viewId]);
        $viewPayment = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;

        if ($viewPayment) {
            $stmt = $pdo->prepare("
                SELECT
                    a.*,
                    g.grn_no,
                    g.invoice_no,
                    g.grn_date,
                    g.total_amount
                FROM inventory_supplier_payment_allocations a
                LEFT JOIN inventory_grns g ON g.id = a.grn_id
                WHERE a.payment_id = :payment_id
                ORDER BY a.id ASC
            ");
            $stmt->execute([':payment_id' => $viewId]);
            $viewAllocations = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
    } catch (Throwable $e) {
        $errors[] = 'Could not load payment detail: ' . $e->getMessage();
    }
}

$flashes = sp_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-wallet2"></i> Stores &amp; POS Inventory</div>
            <div class="hero-title mt-2">Supplier Payments</div>
            <div class="hero-subtitle mt-2">
                Capture supplier payments and allocate them to outstanding GRNs.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="supplier_ledger.php" class="btn btn-light me-2">
                <i class="bi bi-journal-text me-2"></i>Supplier Ledger
            </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">Payments</div><div class="metric-value"><?php echo (int)$summary['count']; ?></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-cash-stack"></i></div>
            <div><div class="metric-label">Posted</div><div class="metric-value small-value"><?php echo money_fmt($summary['posted']); ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-info-subtle text-info"><i class="bi bi-check2-circle"></i></div>
            <div><div class="metric-label">Allocated</div><div class="metric-value small-value"><?php echo money_fmt($summary['allocated']); ?></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-exclamation-triangle"></i></div>
            <div><div class="metric-label">Unallocated</div><div class="metric-value small-value"><?php echo money_fmt($summary['unallocated']); ?></div></div>
        </div>
    </div>
</div>

<?php if ($viewPayment): ?>
<div class="card panel-card mb-4 payment-view" id="paymentView">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Payment <?php echo h($viewPayment['payment_no']); ?></h5>
        <div class="d-flex gap-2">
            <button type="button" class="btn btn-sm btn-outline-primary" onclick="window.print()"><i class="bi bi-printer me-1"></i>Print</button>
            <a href="supplier_payments.php" class="btn btn-sm btn-outline-secondary">Close</a>
        </div>
    </div>
    <div class="card-body">
        <div class="row g-3 mb-3">
            <div class="col-md-3"><strong>Supplier:</strong><br><?php echo h($viewPayment['supplier_name']); ?></div>
            <div class="col-md-2"><strong>Date:</strong><br><?php echo h($viewPayment['payment_date']); ?></div>
            <div class="col-md-2"><strong>Method:</strong><br><?php echo h($viewPayment['payment_method'] ?: '—'); ?></div>
            <div class="col-md-2"><strong>Reference:</strong><br><?php echo h($viewPayment['reference_no'] ?: '—'); ?></div>
            <div class="col-md-3 text-md-end"><strong>Amount:</strong><br><span class="fs-5 fw-bold"><?php echo money_fmt($viewPayment['amount']); ?></span></div>
            <div class="col-md-3"><strong>Status:</strong><br><span class="badge <?php echo $viewPayment['status'] === 'posted' ? 'text-bg-success' : 'text-bg-danger'; ?>"><?php echo h(ucwords($viewPayment['status'])); ?></span></div>
        </div>

        <?php if (!empty($viewPayment['notes'])): ?>
            <div class="alert alert-info"><?php echo h($viewPayment['notes']); ?></div>
        <?php endif; ?>

        <h6 class="fw-bold">Allocations</h6>
        <div class="table-responsive">
            <table class="table table-sm align-middle">
                <thead><tr><th>GRN Date</th><th>GRN</th><th>Invoice</th><th class="text-end">GRN Total</th><th class="text-end">Allocated</th><th></th></tr></thead>
                <tbody>
                <?php if (!$viewAllocations): ?>
                    <tr><td colspan="6" class="text-center text-muted py-3">This payment is not allocated to specific GRNs.</td></tr>
                <?php else: ?>
                    <?php foreach ($viewAllocations as $a): ?>
                        <tr>
                            <td><?php echo h($a['grn_date'] ?: '—'); ?></td>
                            <td><strong><?php echo h($a['grn_no'] ?: 'Unallocated'); ?></strong></td>
                            <td><?php echo h($a['invoice_no'] ?: '—'); ?></td>
                            <td class="text-end"><?php echo money_fmt($a['total_amount']); ?></td>
                            <td class="text-end fw-bold"><?php echo money_fmt($a['amount']); ?></td>
                            <td class="text-end">
                                <?php if (!empty($a['grn_id'])): ?>
                                    <a href="grn.php?view_id=<?php echo (int)$a['grn_id']; ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-eye"></i></a>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if ($viewPayment['status'] === 'posted'): ?>
            <div class="void-box mt-4">
                <form method="post" onsubmit="return confirm('Void this payment? Ledger will ignore its allocations.');">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="void_payment">
                    <input type="hidden" name="payment_id" value="<?php echo (int)$viewPayment['id']; ?>">
                    <label class="form-label">Void Reason</label>
                    <div class="input-group">
                        <input type="text" name="void_reason" class="form-control" placeholder="Reason required">
                        <button class="btn btn-outline-danger"><i class="bi bi-x-octagon me-1"></i>Void Payment</button>
                    </div>
                </form>
            </div>
        <?php else: ?>
            <div class="alert alert-danger mt-3">
                <strong>Voided:</strong> <?php echo h($viewPayment['void_reason'] ?: 'No reason captured'); ?>
                <?php if (!empty($viewPayment['voided_at'])): ?> on <?php echo h($viewPayment['voided_at']); ?><?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<div class="row g-4">
    <div class="col-xl-4">
        <div class="card panel-card mb-4">
            <div class="card-header"><h5 class="mb-0">Capture Payment</h5></div>
            <div class="card-body">
                <form method="get" class="mb-3">
                    <label class="form-label">Select Supplier</label>
                    <div class="input-group">
                        <select name="supplier_id" class="form-select" onchange="this.form.submit()">
                            <option value="0">Choose supplier</option>
                            <?php foreach ($suppliers as $supplier): ?>
                                <option value="<?php echo (int)$supplier['id']; ?>" <?php echo $selectedSupplierId === (int)$supplier['id'] ? 'selected' : ''; ?>>
                                    <?php echo h($supplier['supplier_name']); ?> — Bal: <?php echo money_fmt($supplier['balance']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </form>

                <form method="post" id="paymentForm">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="post_payment">

                    <div class="mb-3">
                        <label class="form-label">Supplier</label>
                        <select name="supplier_id" class="form-select" required>
                            <option value="">Select supplier</option>
                            <?php foreach ($suppliers as $supplier): ?>
                                <option value="<?php echo (int)$supplier['id']; ?>" <?php echo $selectedSupplierId === (int)$supplier['id'] ? 'selected' : ''; ?>>
                                    <?php echo h($supplier['supplier_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Payment Date</label>
                            <input type="date" name="payment_date" class="form-control" value="<?php echo h(date('Y-m-d')); ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Method</label>
                            <select name="payment_method" class="form-select">
                                <option value="cash">Cash</option>
                                <option value="card">Card</option>
                                <option value="bank_transfer">Bank Transfer</option>
                                <option value="ecocash">EcoCash</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                    </div>

                    <div class="row g-3 mt-0">
                        <div class="col-md-6">
                            <label class="form-label">Reference No</label>
                            <input type="text" name="reference_no" class="form-control" placeholder="Bank ref / voucher no">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Amount</label>
                            <input type="number" step="0.01" min="0.01" name="amount" id="paymentAmount" class="form-control" value="<?php echo $prefillAmount > 0 ? h($prefillAmount) : ''; ?>" required>
                        </div>
                    </div>

                    <div class="mt-3">
                        <label class="form-label">Notes</label>
                        <textarea name="notes" class="form-control" rows="2"></textarea>
                    </div>

                    <?php if ($selectedSupplierId > 0): ?>
                        <div class="mt-3 d-flex gap-2">
                            <button type="submit" name="action" value="post_payment" class="btn btn-primary flex-fill">
                                <i class="bi bi-check-circle me-2"></i>Post Payment
                            </button>
                        </div>
                    <?php else: ?>
                        <button type="button" class="btn btn-secondary w-100 mt-3" disabled>Select supplier first</button>
                    <?php endif; ?>

                    <div class="alert alert-info small mt-3 mb-0">
                        Payment may be allocated to GRNs below. If not allocated, it still reduces the supplier balance total.
                    </div>

                    <?php if ($outstandingGrns): ?>
                        <hr>
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <h6 class="fw-bold mb-0">Allocate to GRNs</h6>
                            <button type="button" class="btn btn-sm btn-outline-primary" id="autoAllocateBtn">Auto</button>
                        </div>

                        <div class="allocation-list" id="allocationList">
                            <?php foreach ($outstandingGrns as $g): ?>
                                <div class="allocation-row">
                                    <div>
                                        <strong><?php echo h($g['grn_no']); ?></strong>
                                        <div class="small text-muted">
                                            <?php echo h($g['grn_date']); ?> • <?php echo h($g['invoice_no'] ?: 'No invoice'); ?> • <?php echo (int)$g['age_days']; ?>d
                                        </div>
                                        <div class="small">Balance: <strong><?php echo money_fmt($g['balance_amount']); ?></strong></div>
                                    </div>
                                    <div style="width:130px">
                                        <input type="number"
                                               step="0.01"
                                               min="0"
                                               max="<?php echo h($g['balance_amount']); ?>"
                                               name="allocations[<?php echo (int)$g['id']; ?>]"
                                               class="form-control form-control-sm text-end alloc-input"
                                               data-balance="<?php echo h($g['balance_amount']); ?>"
                                               value="<?php echo isset($g['auto_alloc']) && $g['auto_alloc'] > 0 ? h(number_format((float)$g['auto_alloc'], 2, '.', '')) : ''; ?>">
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <div class="allocation-summary mt-3">
                            <div class="d-flex justify-content-between">
                                <span>Allocated</span>
                                <strong id="allocatedLabel">0.00</strong>
                            </div>
                            <div class="d-flex justify-content-between">
                                <span>Unallocated</span>
                                <strong id="unallocatedLabel">0.00</strong>
                            </div>
                        </div>
                    <?php elseif ($selectedSupplierId > 0): ?>
                        <div class="alert alert-success mt-3 mb-0">No outstanding GRNs for this supplier.</div>
                    <?php endif; ?>
                </form>
            </div>
        </div>
    </div>

    <div class="col-xl-8">
        <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 $selectedSupplierId === (int)$s['id'] ? 'selected' : ''; ?>>
                                    <?php echo h($s['supplier_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">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="payment/ref/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="card panel-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Payment History</h5>
                <span class="text-muted small">Showing latest 500 matching payments</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>Payment</th>
                            <th>Supplier</th>
                            <th>Method</th>
                            <th>Reference</th>
                            <th>Status</th>
                            <th class="text-end">Amount</th>
                            <th class="text-end">Allocated</th>
                            <th class="text-end">Unallocated</th>
                            <th class="text-end">Action</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$payments): ?>
                            <tr><td colspan="10" class="text-center text-muted py-4">No supplier payments found.</td></tr>
                        <?php else: ?>
                            <?php foreach ($payments 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['supplier_name']); ?>
                                        <div class="small text-muted"><?php echo h($p['supplier_code'] ?: ''); ?></div>
                                    </td>
                                    <td><?php echo h(ucwords(str_replace('_',' ', $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>
                                    <td class="text-end"><?php echo money_fmt($p['allocated_amount']); ?></td>
                                    <td class="text-end"><?php echo money_fmt($p['unallocated_amount']); ?></td>
                                    <td class="text-end">
                                        <div class="btn-group btn-group-sm">
                                            <a href="supplier_payments.php?view_id=<?php echo (int)$p['id']; ?>" class="btn btn-outline-primary">
                                                <i class="bi bi-eye"></i>
                                            </a>
                                            <a href="supplier_ledger.php?view_supplier_id=<?php echo (int)$p['supplier_id']; ?>" class="btn btn-outline-info">
                                                <i class="bi bi-journal-text"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                                <?php if (!empty($p['notes'])): ?>
                                    <tr class="notes-row">
                                        <td colspan="10" class="small text-muted pt-0">
                                            <i class="bi bi-info-circle me-1"></i><?php echo h($p['notes']); ?>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="alert alert-info mt-4">
            <strong>Accounting note:</strong> This creates the supplier payment sub-ledger. Later we can post these payments into your GL cash/bank accounts automatically.
        </div>
    </div>
</div>

<style>
.small-value{font-size:1rem!important;letter-spacing:0!important}
.payment-view{border:2px solid rgba(37,99,235,.18)}
.void-box{background:#fff7ed;border:1px solid #fed7aa;border-radius:16px;padding:14px}
.allocation-list{display:flex;flex-direction:column;gap:8px;max-height:420px;overflow:auto}
.allocation-row{display:flex;justify-content:space-between;gap:10px;border:1px solid rgba(15,23,42,.10);background:#f8fafc;border-radius:14px;padding:10px}
.allocation-summary{background:#0f172a;color:#fff;border-radius:14px;padding:12px}
.notes-row td{border-top:0!important;background:#fafafa}
@media print{
    body *{visibility:hidden!important}
    #paymentView,#paymentView *{visibility:visible!important}
    #paymentView{position:absolute;left:0;top:0;width:100%;box-shadow:none!important;border:0!important}
    .void-box,.hero-band,.panel-card:not(#paymentView){display:none!important}
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function(){
    const amountInput = document.getElementById('paymentAmount');
    const allocInputs = Array.from(document.querySelectorAll('.alloc-input'));
    const allocatedLabel = document.getElementById('allocatedLabel');
    const unallocatedLabel = document.getElementById('unallocatedLabel');
    const autoBtn = document.getElementById('autoAllocateBtn');

    function money(n){ return Number(n || 0).toFixed(2); }

    function recalc(){
        const amount = parseFloat(amountInput ? amountInput.value || '0' : '0');
        let allocated = 0;

        allocInputs.forEach(input => {
            let val = parseFloat(input.value || '0');
            const max = parseFloat(input.dataset.balance || '0');

            if (val > max) {
                val = max;
                input.value = money(max);
            }
            if (val < 0) {
                val = 0;
                input.value = '';
            }

            allocated += val;
        });

        if (allocatedLabel) allocatedLabel.textContent = money(allocated);
        if (unallocatedLabel) unallocatedLabel.textContent = money(amount - allocated);
    }

    if (amountInput) amountInput.addEventListener('input', recalc);
    allocInputs.forEach(input => input.addEventListener('input', recalc));

    if (autoBtn) {
        autoBtn.addEventListener('click', function(){
            let remaining = parseFloat(amountInput ? amountInput.value || '0' : '0');
            if (remaining <= 0) {
                alert('Enter payment amount first.');
                return;
            }

            allocInputs.forEach(input => {
                const bal = parseFloat(input.dataset.balance || '0');
                const alloc = Math.min(remaining, bal);
                input.value = alloc > 0 ? money(alloc) : '';
                remaining -= alloc;
            });

            recalc();
        });
    }

    const form = document.getElementById('paymentForm');
    if (form) {
        form.addEventListener('submit', function(e){
            const amount = parseFloat(amountInput ? amountInput.value || '0' : '0');
            let allocated = 0;
            allocInputs.forEach(input => allocated += parseFloat(input.value || '0'));

            if (allocated > amount + 0.01) {
                e.preventDefault();
                alert('Allocated amount cannot exceed payment amount.');
                return false;
            }
        });
    }

    recalc();
});
</script>

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