<?php 
include 'db_connect.php'; 

// Initialize baseline defaults to eliminate notice pollution inside the DOM framework
$id = '';
$tenant_id = '';
$amount = '';
$invoice = '';
$type = 'rent'; // Default fallback allocation

if(isset($_GET['id']) && is_numeric($_GET['id'])){
    $qry = $conn->query("SELECT * FROM payments where id = " . $_GET['id']);
    if($qry && $qry->num_rows > 0){
        foreach($qry->fetch_assoc() as $k => $val){
            $$k = $val;
        }
    }
}
?>
<div class="container-fluid">
    <form action="" id="manage-payment-form">
        <input type="hidden" name="id" value="<?php echo $id ?>">
        <div id="msg"></div>
        
        <div class="form-group">
            <label class="control-label font-weight-bold text-dark">Select Tenant</label>
            <select name="tenant_id" id="tenant_id" class="custom-select select2" required>
                <option value=""></option>
                <?php 
                $tenants = $conn->query("SELECT t.id, concat(t.lastname,', ',t.firstname,' ',t.middlename) as name, h.house_no, h.building 
                                       FROM tenants t 
                                       INNER JOIN houses h ON h.id = t.house_id 
                                       WHERE t.status = 1 
                                       ORDER BY name ASC");
                while($row = $tenants->fetch_assoc()):
                ?>
                <option value="<?php echo $row['id'] ?>" <?php echo $tenant_id == $row['id'] ? 'selected' : '' ?>>
                    <?php echo ucwords($row['name']) ?> (<?php echo ucwords($row['building']) ?> — Unit <?php echo $row['house_no'] ?>)
                </option>
                <?php endwhile; ?>
            </select>
        </div>
        
        <div class="form-group">
            <label class="control-label font-weight-bold text-dark">Payment Allocation Destination</label>
            <select name="type" id="type" class="custom-select" required>
                <option value="rent" <?php echo $type == 'rent' ? 'selected' : '' ?>>House Rent Allocation</option>
                <option value="parking" <?php echo $type == 'parking' ? 'selected' : '' ?>>Parking Space Registry Fee</option>
                <option value="utility" <?php echo $type == 'utility' ? 'selected' : '' ?>>Utilities & Garbage Maintenance Collection</option>
            </select>
        </div>

        <div class="form-group" id="details"></div>
        
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label class="control-label font-weight-bold text-secondary">Outstanding Ledger Balance</label>
                    <input type="text" class="form-control text-right bg-light font-weight-bold text-danger text-monospace" id="balance" readonly value="0.00">
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label class="control-label font-weight-bold text-dark">Amount Remitted (KES)</label>
                    <input type="number" step="any" min="1" name="amount" class="form-control text-right font-weight-bold text-success" value="<?php echo $amount ?>" placeholder="0.00" required>
                </div>
            </div>
        </div>
        
        <div class="form-group">
            <label class="control-label font-weight-bold text-dark">Invoice / Receipt Reference #</label>
            <input type="text" name="invoice" class="form-control text-monospace" placeholder="e.g. M-PESA Ref, Check #, Bank Slip ID" value="<?php echo $invoice ?>" required>
        </div>
    </form>
</div>

<script>
    $(document).ready(function(){
        // Anchor structural select dropdowns safely inside modal frames to allow search text inputs to focus
        $('#tenant_id').select2({
            placeholder: "Search occupant name or unit number...",
            width: "100%",
            dropdownParent: $('#uni_modal')
        });

        // Trigger balance calculation check smoothly if editing an existing receipt
        if('<?php echo !empty($id) ? 1 : 0 ?>' == 1) {
            $('#tenant_id').trigger('change');
        }
    });

    // Fire data-sync engine when selection parameters adjust
    $('#tenant_id').change(function(){
        var t_id = $(this).val();
        if(t_id == '' || t_id <= 0){
            $('#details').html('');
            $('#balance').val('0.00');
            return false;
        }
        
        start_load();
        $.ajax({
            url: 'ajax.php?action=get_tdetails',
            method: 'POST',
            data: { id: t_id, pid: '<?php echo $id ?>' },
            success: function(resp){
                if(resp){
                    try {
                        var data = JSON.parse(resp);
                        
                        // Dynamically append extracted house metrics if available inside JSON response payload
                        var pricingDetails = '';
                        if(data.rent_price !== undefined && data.parking_price !== undefined){
                            pricingDetails = '<hr class="my-1"><small class="d-block font-weight-bold text-dark">' + 
                                             'Expected Rent: KES ' + parseFloat(data.rent_price).toLocaleString('en-US', {minimumFractionDigits: 2}) + 
                                             ' | Parking Fee: KES ' + parseFloat(data.parking_price).toLocaleString('en-US', {minimumFractionDigits: 2}) + 
                                             '</small>';
                        }
                        
                        // Render layout container info blocks cleanly inside our DOM interface
                        $('#details').html('<div class="alert alert-info border-left-primary shadow-sm mb-3 py-2"><i class="fa fa-info-circle mr-1"></i> ' + data.details + pricingDetails + '</div>');
                        
                        var formattedBalance = parseFloat(data.outstanding);
                        $('#balance').val(isNaN(formattedBalance) ? '0.00' : formattedBalance.toFixed(2));
                    } catch(e) {
                        console.error("Failed to parse JSON balance metrics stream:", e);
                        alert_toast("Error parsing live ledger tracking numbers.", "danger");
                    }
                }
            },
            error: function(err){
                console.error("Ledger calculation sync error:", err);
            },
            complete: function(){
                end_load();
            }
        });
    });

    $('#manage-payment-form').submit(function(e){
        e.preventDefault();
        
        // Block empty submittals or text mismatches ahead of processing
        if(parseFloat($('input[name="amount"]').val()) <= 0){
            alert_toast("Invalid transaction amount structure specified.", "danger");
            return false;
        }

        start_load();
        $.ajax({
            url: 'ajax.php?action=save_payment',
            method: 'POST',
            data: $(this).serialize(),
            success: function(resp){
                if(resp == 1){
                    alert_toast("Cash receipt transaction recorded into financial accounts.", 'success');
                    setTimeout(function(){
                        location.reload();
                    }, 1000);
                } else {
                    alert_toast("Database layout exception rejected current input data state.", 'danger');
                    end_load();
                }
            },
            error: function(err){
                console.error("Payment transmission error:", err);
                alert_toast("A critical network fault crashed task transmission.", 'danger');
                end_load();
            }
        });
    });
</script>