<?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();
}

$branch_id = (int)$record['branch_id'];
$laybuyTotal = (float)$record['amount'];
$totalPaid = (float)$record['total_paid'];
$balance = max(0, $laybuyTotal - $totalPaid);
$assignedValue = array_sum(array_map(static fn($row) => (float)($row['value'] ?? 0), $laybuy->getCodesDetails($record_id) ?? []));
$remainingCodeValue = max(0, $laybuyTotal - $assignedValue);
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $txn_date = trim($_POST['txn_date'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    $uniqueCodes = is_array($_POST['unique_code'] ?? null) ? $_POST['unique_code'] : [$_POST['unique_code'] ?? ''];
    $values = is_array($_POST['value'] ?? null) ? $_POST['value'] : [$_POST['value'] ?? ''];
    $codeRows = [];
    foreach ($uniqueCodes as $index => $uniqueCode) {
        $codeRows[] = ['unique_code' => trim((string)$uniqueCode), 'value' => trim((string)($values[$index] ?? ''))];
    }
    $submittedTotal = array_sum(array_map(static fn($row) => is_numeric($row['value']) ? (float)$row['value'] : 0, $codeRows));

    if ($txn_date === '' || $notes === '' || !$codeRows || $submittedTotal <= 0 || $submittedTotal > $remainingCodeValue + 0.009) {
        $message = '<div class="alert alert-danger">Please provide a valid date, unique code, positive numeric value, and notes.</div>';
    } else {
        $result = $laybuy->assignMultipleCodes($record_id, $txn_date, $codeRows, $notes, $branch_id);
        if (!empty($result['success'])) {
            header('Location: assign_codes.php?record_id=' . $record_id . '&branch_id=' . $branch_id);
            exit();
        }
        $message = '<div class="alert alert-danger">' . htmlspecialchars($result['message'] ?? 'Failed to assign code.') . '</div>';
    }
}
?>
<?php include __DIR__ . '/../../includes/header.php'; ?>
    <div class="container mt-5">
        <h1 class="mb-4">Add New Code to Laybuy</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">
            <div class="form-group">
                <label for="txn_date">Date added</label>
                <input type="date" class="form-control" id="txn_date" name="txn_date" value="<?php echo date('Y-m-d'); ?>" required>
            </div>
            <label>Unique Codes and Values</label>
            <div id="codeRows">
                <div class="form-row code-row mb-2">
                    <div class="col-md-7"><input type="text" class="form-control" name="unique_code[]" placeholder="Unique code" required></div>
                    <div class="col-md-4"><input type="number" step="0.01" min="0.01" class="form-control code-value" name="value[]" placeholder="Value" required></div>
                    <div class="col-md-1"><button type="button" class="btn btn-outline-danger remove-code" disabled>&times;</button></div>
                </div>
            </div>
            <button type="button" class="btn btn-outline-primary btn-sm mb-3" id="addCodeRow">+ Add another code</button>
            <small class="form-text text-muted d-block mb-3">Remaining value available: MWK <span id="remainingValue"><?php echo number_format($remainingCodeValue, 2); ?></span>. Enter one row per inventory item.</small>
            <div class="form-group">
                <label for="notes">Notes</label>
                <input type="text" class="form-control" id="notes" name="notes" value="<?php echo htmlspecialchars($_POST['notes'] ?? ''); ?>" required>
            </div>

            <button type="submit" class="btn btn-primary">Add Code</button>
            <a href="assign_codes.php?record_id=<?php echo $record_id . '&branch_id=' . $branch_id; ?>" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
    <script>
        const codeRows = document.getElementById('codeRows');
        document.getElementById('addCodeRow').addEventListener('click', function () {
            const row = codeRows.querySelector('.code-row').cloneNode(true);
            row.querySelectorAll('input').forEach(input => input.value = '');
            row.querySelector('.remove-code').disabled = false;
            codeRows.appendChild(row);
        });
        codeRows.addEventListener('click', function (event) {
            if (event.target.classList.contains('remove-code') && codeRows.children.length > 1) {
                event.target.closest('.code-row').remove();
            }
        });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
