<?php 
include 'db_connect.php'; 

// Initialize defaults to prevent empty variable notice triggers during execution
$id = '';
$tenant_id = '';
$type = '';
$reading = '';
$amount = '';
$billing_date = date('Y-m-d');

if(isset($_GET['id']) && is_numeric($_GET['id'])){
    $qry = $conn->query("SELECT * FROM utility_bills 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="utility-form">
        <input type="hidden" name="id" value="<?php echo $id ?>">
        
        <div class="form-group">
            <label class="control-label font-weight-bold text-dark">Assigned Tenant</label>
            <select name="tenant_id" class="custom-select select2" required>
                <option value=""></option>
                <?php 
                $tenants = $conn->query("SELECT t.id, concat(t.lastname, ', ', t.firstname) 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">Utility Bill Type</label>
            <select name="type" class="custom-select text-dark" required>
                <option value="" disabled <?php echo empty($type) ? 'selected' : '' ?>>Select resource billing profile...</option>
                <option value="Water" <?php echo $type == 'Water' ? 'selected' : '' ?>>Water Consumption</option>
                <option value="Electricity" <?php echo $type == 'Electricity' ? 'selected' : '' ?>>Electricity Units</option>
                <option value="Parking" <?php echo $type == 'Parking' ? 'selected' : '' ?>>Parking Allocation (Extra Space)</option>
                <option value="Other" <?php echo $type == 'Other' ? 'selected' : '' ?>>Other / Surcharge Additions</option>
            </select>
        </div>
        
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label class="control-label font-weight-bold text-dark">Meter Reading <span class="text-muted font-weight-normal small">(Optional)</span></label>
                    <input type="number" step="any" min="0" name="reading" class="form-control" value="<?php echo $reading ?>">
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label class="control-label font-weight-bold text-dark">Bill Amount (KES)</label>
                    <input type="number" step="any" min="0" name="amount" class="form-control font-weight-bold text-dark" value="<?php echo $amount ?>" placeholder="0.00" required>
                </div>
            </div>
        </div>
        
        <div class="form-group">
            <label class="control-label font-weight-bold text-dark">Target Billing Date</label>
            <input type="date" name="billing_date" class="form-control" value="<?php echo date("Y-m-d", strtotime($billing_date)) ?>" required>
        </div>
    </form>
</div>

<script>
    // Ensure standard modal setup execution logic runs properly
    $(document).ready(function(){
        $('.select2').select2({
            placeholder: "Select or search matching occupant...",
            width: "100%",
            dropdownParent: $('#uni_modal') // Prevents search input focus locks inside Bootstrap Modals
        });
    });

    $('#utility-form').submit(function(e){
        e.preventDefault();
        start_load();
        
        $.ajax({
            url: 'ajax.php?action=save_utility',
            method: 'POST',
            data: $(this).serialize(),
            success: function(resp){
                if(resp == 1){
                    alert_toast("Utility billing entry logged into database.", 'success');
                    setTimeout(function(){
                        location.reload();
                    }, 1000);
                } else {
                    alert_toast("An infrastructure layout block stopped verification.", 'danger');
                    end_load();
                }
            },
            error: function(err){
                console.error("Utility transactional submission fault:", err);
                alert_toast("Fatal system error encountered while adjusting records.", 'danger');
                end_load();
            }
        });
    });
</script>