<?php include('db_connect.php');?>

<div class="container-fluid mt-3">
    <div class="col-lg-12">
        <div class="row">
            <div class="col-md-4 mb-4">
                <form action="" id="manage-house">
                    <div class="card shadow-sm border-0" style="border-radius: 12px; overflow: hidden;">
                        <div class="card-header bg-light border-bottom py-3">
                            <h6 class="mb-0 text-dark font-weight-bold" id="form-title">
                                <i class="fa fa-home text-primary mr-2"></i>Register New Unit
                            </h6>
                        </div>
                        <div class="card-body p-4">
                            <div class="form-group" id="msg"></div>
                            <input type="hidden" name="id" id="unit_id">
                            
                            <div class="form-group mb-3">
                                <label class="control-label font-weight-bold text-dark small text-uppercase" style="letter-spacing: 0.5px;">Building Block Name / ID</label>
                                <input type="text" class="form-control" name="building" placeholder="e.g. Block A, Wing B" required>
                            </div>
                            
                            <div class="row mb-3">
                                <div class="col-6">
                                    <div class="form-group mb-0">
                                        <label class="control-label font-weight-bold text-dark small text-uppercase" style="letter-spacing: 0.5px;">Floor Level</label>
                                        <input type="number" class="form-control" name="floor" min="0" placeholder="0 for Ground" required>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="form-group mb-0">
                                        <label class="control-label font-weight-bold text-dark small text-uppercase" style="letter-spacing: 0.5px;">House / Room #</label>
                                        <input type="text" class="form-control text-monospace" name="house_no" placeholder="e.g. 101, A5" required>
                                    </div>
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-12">
                                    <div class="form-group mb-0">
                                        <label class="control-label font-weight-bold text-dark small text-uppercase" style="letter-spacing: 0.5px;">Property Footprint (Sqm)</label>
                                        <div class="input-group">
                                            <input type="number" class="form-control text-monospace" name="sqm" step="any" min="0.01" placeholder="e.g. 39.26" required>
                                            <div class="input-group-append">
                                                <span class="input-group-text bg-light font-weight-bold text-muted small">M²</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group mb-3">
                                <label class="control-label font-weight-bold text-dark small text-uppercase" style="letter-spacing: 0.5px;">Unit Category Type</label>
                                <select name="category_id" class="custom-select" required>
                                    <option value="" disabled selected>-- Select Type --</option>
                                    <?php 
                                    $categories = $conn->query("SELECT * FROM categories order by name asc");
                                    if($categories->num_rows > 0):
                                        while($row = $categories->fetch_assoc()) :
                                    ?>
                                        <option value="<?php echo $row['id'] ?>"><?php echo ucwords($row['name']) ?></option>
                                    <?php 
                                        endwhile; 
                                    else: 
                                    ?>
                                        <option value="" disabled>No categories defined. Configure categories first.</option>
                                    <?php endif; ?>
                                </select>
                            </div>
                            
                            <div class="form-group mb-3">
                                <label class="control-label font-weight-bold text-dark small text-uppercase" style="letter-spacing: 0.5px;">Features & Dimensions Description</label>
                                <textarea name="description" cols="30" rows="3" class="form-control" placeholder="e.g. 2 Bedroom, Master En-suite, Balcony view" required></textarea>
                            </div>
                            
                            <div class="form-group mb-0">
                                <label class="control-label font-weight-bold text-dark small text-uppercase" style="letter-spacing: 0.5px;">Base Monthly Rent (KES)</label>
                                <div class="input-group">
                                    <input type="number" class="form-control text-right font-weight-bold text-success text-monospace" name="price" step="any" min="1" placeholder="0.00" required>
                                </div>
                            </div>
                        </div>
                        <div class="card-footer bg-light border-top-0 d-flex justify-content-end py-3 px-4">
                            <button type="submit" class="btn btn-sm btn-primary font-weight-bold px-4 mr-2" style="border-radius: 6px;">Save Asset</button>
                            <button type="button" class="btn btn-sm btn-secondary px-4" id="cancel-edit" style="border-radius: 6px;">Cancel</button>
                        </div>
                    </div>
                </form>
            </div>

            <div class="col-md-8">
                <div class="card shadow-sm border-0" style="border-radius: 12px; overflow: hidden;">
                    <div class="card-header bg-light border-bottom py-3">
                        <h6 class="mb-0 text-dark font-weight-bold"><b>Real Estate Housing Inventory</b></h6>
                    </div>
                    <div class="card-body p-4">
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped table-hover mb-0" id="units-data-table">
                                <thead class="bg-light">
                                    <tr>
                                        <th class="text-center text-uppercase text-muted small font-weight-bold" style="width: 5%; letter-spacing: 0.5px;">#</th>
                                        <th class="text-uppercase text-muted small font-weight-bold" style="width: 70%; letter-spacing: 0.5px;">Property Structural Invariant Profile</th>
                                        <th class="text-center text-uppercase text-muted small font-weight-bold" style="width: 25%; letter-spacing: 0.5px;">Management Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $i = 1;
                                    $house = $conn->query("SELECT h.*, c.name as cname FROM houses h inner join categories c on c.id = h.category_id order by h.building asc, h.floor asc, h.house_no asc");
                                    while($row = $house->fetch_assoc()):
                                    ?>
                                    <tr>
                                        <td class="text-center align-middle font-weight-bold text-muted"><?php echo $i++ ?></td>
                                        <td class="align-middle py-3">
                                            <p class="mb-1">Building Location: <b class="text-dark font-weight-bold"><?php echo ucwords($row['building']) ?></b></p>
                                            <p class="mb-1 text-muted">
                                                <small>
                                                    Floor Level: <b class="text-dark mr-2"><?php echo $row['floor'] ?></b> | 
                                                    Unit ID / No: <b class="text-primary text-monospace mr-2"><?php echo $row['house_no'] ?></b> |
                                                    Footprint: <b class="text-dark text-monospace"><?php echo !empty($row['sqm']) ? number_format($row['sqm'], 2) : '0.00' ?> M²</b>
                                                </small>
                                            </p>
                                            <p class="mb-1 text-muted"><small>Classification: <span class="badge badge-info px-2 py-1" style="border-radius: 4px; font-weight: 600;"><?php echo ucwords($row['cname']) ?></span></small></p>
                                            <p class="mb-1 text-muted"><small>Unit Specs: <i><?php echo $row['description'] ?></i></small></p>
                                            <p class="mb-0 mt-1"><small>Base Fee Rate: <b class="text-success text-monospace">KES <?php echo number_format($row['price'], 2) ?></b> / Month</small></p>
                                        </td>
                                        <td class="text-center align-middle">
                                            <div class="btn-group" role="group">
                                                <button class="btn btn-sm btn-outline-primary edit_house font-weight-bold px-3" type="button" 
                                                    data-id="<?php echo $row['id'] ?>"  
                                                    data-house_no="<?php echo htmlspecialchars($row['house_no'], ENT_QUOTES) ?>" 
                                                    data-building="<?php echo htmlspecialchars($row['building'], ENT_QUOTES) ?>" 
                                                    data-floor="<?php echo $row['floor'] ?>" 
                                                    data-sqm="<?php echo isset($row['sqm']) ? $row['sqm'] : '' ?>"
                                                    data-description="<?php echo htmlspecialchars($row['description'], ENT_QUOTES) ?>" 
                                                    data-category_id="<?php echo $row['category_id'] ?>" 
                                                    data-price="<?php echo $row['price'] ?>"
                                                    style="border-radius: 4px 0 0 4px;">
                                                    <i class="fa fa-edit mr-1"></i>Edit
                                                </button>
                                                <button class="btn btn-sm btn-outline-danger delete_house font-weight-bold px-3" type="button" data-id="<?php echo $row['id'] ?>" style="border-radius: 0 4px 4px 0;">
                                                    <i class="fa fa-trash-alt mr-1"></i>Delete
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>  
</div>

<style>
    td {
        vertical-align: middle !important;
    }
    .text-monospace {
        font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace !important;
    }
    .form-control:focus, .custom-select:focus {
        border-color: #3b82f6 !important;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15) !important;
    }
</style>

<script>
    $(document).ready(function(){
        if($('#units-data-table').length > 0) {
            $('#units-data-table').dataTable({
                "pageLength": 10,
                "bLengthChange": true
            });
        }
    });

    function reset_house_form() {
        var form = $('#manage-house');
        form.get(0).reset();
        $('#unit_id').val('');
        $('#form-title').html('<i class="fa fa-home text-primary mr-2"></i>Register New Unit');
        $('#msg').html('');
    }

    $('#cancel-edit, button[type="reset"]').click(function(){
        reset_house_form();
    });

    // Handle Edit Action Population safely
    $('.edit_house').click(function(e){
        e.preventDefault();
        start_load();
        
        var btn = $(this);
        var form = $('#manage-house');
        
        // Reset baseline state mapping values first
        $('#msg').html('');
        
        // Feed field strings explicitly directly into targets
        $('#unit_id').val(btn.attr('data-id'));
        form.find("[name='house_no']").val(btn.attr('data-house_no'));
        form.find("[name='building']").val(btn.attr('data-building'));
        form.find("[name='floor']").val(btn.attr('data-floor'));
        form.find("[name='sqm']").val(btn.attr('data-sqm'));
        form.find("[name='description']").val(btn.attr('data-description'));
        form.find("[name='price']").val(btn.attr('data-price'));
        form.find("[name='category_id']").val(btn.attr('data-category_id'));
        
        // Adjust control title frame
        $('#form-title').html('<i class="fa fa-edit text-warning mr-2"></i>Modify Unit #' + btn.attr('data-house_no'));
        
        // Scroll smoothly to form view on smaller viewports
        $('html, body').animate({
            scrollTop: form.offset().top - 20
        }, 300);
        
        end_load();
    });

    $('#manage-house').submit(function(e){
        e.preventDefault();
        start_load();
        $('#msg').html('');
        
        $.ajax({
            url: 'ajax.php?action=save_house',
            data: new FormData($(this)[0]),
            cache: false,
            contentType: false,
            processData: false,
            method: 'POST',
            type: 'POST',
            success: function(resp){
                if(resp == 1){
                    alert_toast("Property structure mapping parameters saved.", 'success');
                    setTimeout(function(){
                        location.reload();
                    }, 1000);
                } else if(resp == 2){
                    $('#msg').html('<div class="alert alert-danger font-weight-bold mb-3"><i class="fa fa-exclamation-circle mr-2"></i>Error: That House Number already exists within the chosen building block structure.</div>');
                    end_load();
                } else {
                    $('#msg').html('<div class="alert alert-danger font-weight-bold mb-3"><i class="fa fa-exclamation-circle mr-2"></i>An unexpected database fault blocked structural processing.</div>');
                    end_load();
                }
            },
            error: function(err){
                console.error("House data transaction fault:", err);
                alert_toast("Network link latency failure experienced.", 'danger');
                end_load();
            }
        });
    });

    $('.delete_house').click(function(){
        _conf("Are you absolutely sure you want to remove this unit from inventory records? This action cannot be reversed if active contracts exist.", "delete_house", [$(this).attr('data-id')]);
    });

    function delete_house($id){
        start_load();
        $.ajax({
            url: 'ajax.php?action=delete_house',
            method: 'POST',
            data: { id: $id },
            success: function(resp){
                if(resp == 1){
                    alert_toast("Property records updated: Unit removed.", 'success');
                    setTimeout(function(){
                        location.reload();
                    }, 1000);
                } else {
                    alert_toast("Server rejected property file deletion request.", 'danger');
                    end_load();
                }
            },
            error: function(err){
                console.error("Critical execution breakdown updating logs:", err);
                end_load();
            }
        });
    }
</script>