<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Laybuy.php';
require_once __DIR__ . '/../../classes/LoanLaybuy.php';

$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);
$loanLaybuy = new LoanLaybuy($conn);
$laybuy = new Laybuy($conn);

if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}

$record_id = isset($_GET['record_id']) ? (int)$_GET['record_id'] : 0;
$record = $loanLaybuy->getLoanLaybuyById($record_id);
if (!$record || (int)$auth->getUserBranch($_SESSION['user_id']) !== (int)$record['branch_id']) {
    header('Location: laybuy_and_loans.php?error=' . urlencode('Laybuy not found or access denied.'));
    exit();
}

$laybuyTotal = (float)$record['amount'];
$totalPaid = (float)$record['total_paid'];
$balance = max(0, $laybuyTotal - $totalPaid);
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $bodyAmount = (float)($_POST['top_up_amount'] ?? 0);
    $paymentDate = trim($_POST['payment_date'] ?? '');
    $paymentMethod = trim($_POST['payment_method'] ?? 'cash');
    $notes = trim($_POST['notes'] ?? '');

    $codes = [];
    $uniqueCodes = $_POST['unique_code'] ?? [];
    $codeValues = $_POST['code_value'] ?? [];
    $codeNotes = $_POST['code_notes'] ?? [];
    foreach ($uniqueCodes as $idx => $uniqueCode) {
        $codes[] = [
            'unique_code' => $uniqueCode,
            'value' => $codeValues[$idx] ?? 0,
            'notes' => $codeNotes[$idx] ?? '',
        ];
    }

    $result = $laybuy->recordPayment(
        $record_id,
        $bodyAmount,
        $paymentDate,
        $notes,
        $record['branch_id'],
        $paymentMethod,
        $codes
    );

    if (!empty($result['success'])) {
        $params = ['record_id' => $record_id, 'success' => $result['message']];
        if (!empty($result['transaction_id'])) {
            $params['eis_transaction'] = $result['transaction_id'];
        }
        header('Location: pay_loan_or_laybuy.php?' . http_build_query($params));
        exit();
    }

    $message = '<div class="alert alert-danger">' . htmlspecialchars($result['message'] ?? 'Failed to record payment.') . '</div>';
}
?>
<?php include __DIR__ . '/../../includes/header.php'; ?>
    <div class="container mt-5">
        <h1 class="mb-4">Add Laybuy Payment</h1>
        <?php echo $message; ?>

        <div class="alert alert-info">
            <strong><?php echo htmlspecialchars($record['record_number']); ?></strong>
            <?php echo htmlspecialchars($record['customer_name']); ?> -
            Total: MWK <?php echo number_format($laybuyTotal, 2); ?>,
            Paid: MWK <?php echo number_format($totalPaid, 2); ?>,
            Balance: MWK <span id="balanceLabel"><?php echo number_format($balance, 2); ?></span>
        </div>

        <form method="POST" id="paymentForm">
            <div class="form-group">
                <label for="payment_date">Payment Date</label>
                <input type="date" class="form-control" id="payment_date" name="payment_date" value="<?php echo date('Y-m-d'); ?>" required>
            </div>
            <div class="form-group">
                <label for="payment_method">Payment Option</label>
                <select class="form-control" id="payment_method" name="payment_method" required>
                    <option value="cash">Cash</option>
                    <option value="card">Card</option>
                    <option value="mobile_money">Mobile Money</option>
                    <option value="bank_transfer">Bank Transfer</option>
                    <option value="cheque">Cheque</option>
                    <option value="other">Other</option>
                </select>
            </div>
            <div class="form-group">
                <label for="old_balance">Old Balance</label>
                <input type="text" class="form-control" id="old_balance" value="<?php echo number_format($balance, 2, '.', ''); ?>" disabled>
            </div>
            <div class="form-group">
                <label for="top_up_amount">Payment Amount</label>
                <input type="number" step="0.01" min="0.01" max="<?php echo htmlspecialchars(number_format($balance, 2, '.', '')); ?>" class="form-control" id="top_up_amount" name="top_up_amount" required>
            </div>
            <div class="form-group">
                <label for="new_balance">New Balance</label>
                <input type="text" class="form-control" id="new_balance" disabled>
            </div>
            <div class="form-group">
                <label for="notes">Notes</label>
                <input type="text" class="form-control" id="notes" name="notes" required>
            </div>

            <div id="finalPaymentSection" class="card mt-4 mb-4" style="display:none;">
                <div class="card-header">
                    Final Payment Item Codes
                </div>
                <div class="card-body">
                    <p class="text-muted mb-3">For final payment, assign the unique code or codes being sold. Their values must total MWK <?php echo number_format($laybuyTotal, 2); ?>.</p>
                    <div id="codeRows">
                        <div class="form-row code-row">
                            <div class="form-group col-md-4">
                                <label>Unique Code</label>
                                <input type="text" class="form-control final-field" name="unique_code[]">
                            </div>
                            <div class="form-group col-md-3">
                                <label>Value</label>
                                <input type="number" step="0.01" min="0.01" class="form-control final-field code-value" name="code_value[]">
                            </div>
                            <div class="form-group col-md-4">
                                <label>Code Notes</label>
                                <input type="text" class="form-control" name="code_notes[]">
                            </div>
                            <div class="form-group col-md-1 d-flex align-items-end">
                                <button type="button" class="btn btn-outline-danger remove-code-row">&times;</button>
                            </div>
                        </div>
                    </div>
                    <button type="button" class="btn btn-outline-primary btn-sm" id="addCodeRow">Add Another Code</button>
                    <div class="mt-3"><strong>Code Value Total:</strong> MWK <span id="codeValueTotal">0.00</span></div>
                </div>
            </div>

            <button type="submit" class="btn btn-primary">Add Payment</button>
            <a href="pay_loan_or_laybuy.php?record_id=<?php echo $record_id; ?>" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
    <script>
        const balance = <?php echo json_encode(round($balance, 2)); ?>;
        const laybuyTotal = <?php echo json_encode(round($laybuyTotal, 2)); ?>;
        const amountInput = document.getElementById('top_up_amount');
        const newBalanceInput = document.getElementById('new_balance');
        const finalSection = document.getElementById('finalPaymentSection');
        const codeRows = document.getElementById('codeRows');
        const codeValueTotal = document.getElementById('codeValueTotal');
        const addCodeRowBtn = document.getElementById('addCodeRow');

        function money(value) {
            return (Math.round(value * 100) / 100).toFixed(2);
        }

        function isFinalPayment() {
            const paid = parseFloat(amountInput.value || '0');
            return Math.abs(paid - balance) < 0.01;
        }

        function updateNewBal() {
            const paid = parseFloat(amountInput.value || '0');
            const newBalance = Math.max(0, balance - paid);
            newBalanceInput.value = money(newBalance);
            if (finalSection) {
                finalSection.style.display = isFinalPayment() ? 'block' : 'none';
                document.querySelectorAll('.final-field').forEach(function(field) {
                    field.required = isFinalPayment();
                });
                updateCodeTotal();
            }
        }

        function updateCodeTotal() {
            if (!codeValueTotal) return;
            let total = 0;
            document.querySelectorAll('.code-value').forEach(function(input) {
                total += parseFloat(input.value || '0');
            });
            codeValueTotal.textContent = money(total);
        }

        if (codeRows && addCodeRowBtn) {
            addCodeRowBtn.addEventListener('click', function() {
                const firstRow = codeRows.querySelector('.code-row');
                const row = firstRow.cloneNode(true);
                row.querySelectorAll('input').forEach(function(input) { input.value = ''; });
                codeRows.appendChild(row);
                updateNewBal();
            });

            codeRows.addEventListener('click', function(event) {
                if (!event.target.classList.contains('remove-code-row')) return;
                if (codeRows.querySelectorAll('.code-row').length === 1) return;
                event.target.closest('.code-row').remove();
                updateCodeTotal();
            });

            codeRows.addEventListener('input', updateCodeTotal);
        }

        amountInput.addEventListener('input', updateNewBal);
        document.getElementById('paymentForm').addEventListener('submit', function(event) {
            if (!isFinalPayment()) return;
            let total = 0;
            document.querySelectorAll('.code-value').forEach(function(input) {
                total += parseFloat(input.value || '0');
            });
            if (Math.abs(total - laybuyTotal) >= 0.01) {
                event.preventDefault();
                alert('Assigned code values must equal the full laybuy total: MWK ' + money(laybuyTotal));
            }
        });
        updateNewBal();
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
