<?php 
include 'db_connect.php'; 

// Initialize baseline defaults to prevent PHP notice pollution inside the DOM
$id = '';
$lastname = '';
$firstname = '';
$middlename = '';
$email = '';
$contact = '';
$date_in = date('Y-m-d');
$house_id = '';
$agreement_path = '';
$security_deposit = 0;
$parking_monthly = 0;

if(isset($_GET['id']) && is_numeric($_GET['id'])){
    $qry = $conn->query("SELECT * FROM tenants 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-tenant-form" enctype="multipart/form-data">
        <input type="hidden" name="id" value="<?php echo $id ?>">
        
        <div class="row form-group">
            <div class="col-md-4">
                <label class="control-label font-weight-bold text-dark">Last Name</label>
                <input type="text" class="form-control" name="lastname" value="<?php echo $lastname ?>" required>
            </div>
            <div class="col-md-4">
                <label class="control-label font-weight-bold text-dark">First Name</label>
                <input type="text" class="form-control" name="firstname" value="<?php echo $firstname ?>" required>
            </div>
            <div class="col-md-4">
                <label class="control-label font-weight-bold text-dark">Middle Name</label>
                <input type="text" class="form-control" name="middlename" value="<?php echo $middlename ?>">
            </div>
        </div>

        <div class="form-group row">
            <div class="col-md-4">
                <label class="control-label font-weight-bold text-dark">Email Address</label>
                <input type="email" class="form-control" name="email" value="<?php echo $email ?>" required>
            </div>
            <div class="col-md-4">
                <label class="control-label font-weight-bold text-dark">Contact Phone #</label>
                <input type="text" class="form-control" name="contact" value="<?php echo $contact ?>" required>
            </div>
            <div class="col-md-4">
                <label class="control-label font-weight-bold text-dark">Lease Commencement Date</label>
                <input type="date" class="form-control" name="date_in" value="<?php echo date("Y-m-d", strtotime($date_in)) ?>" required>
            </div>
        </div>

        <hr>
        <div class="row form-group">
            <div class="col-md-6">
                <label class="control-label font-weight-bold text-dark">Assigned House / Unit</label>
                <select name="house_id" id="house_id" class="custom-select select2" required>
                    <option value="" disabled <?php echo empty($house_id) ? 'selected' : '' ?>>Select vacant room...</option>
                    <?php 
                    // Pull only vacant houses, but preserve current selection when updating a current occupant
                    $house = $conn->query("SELECT h.*, c.name as cname FROM houses h inner join categories c on c.id = h.category_id where h.id not in (SELECT house_id from tenants where status = 1) " . (!empty($house_id) ? " or h.id = $house_id" : "") . " order by h.house_no desc");
                    while($row = $house->fetch_assoc()):
                    ?>
                    <option value="<?php echo $row['id'] ?>" data-price="<?php echo $row['price'] ?>" <?php echo $house_id == $row['id'] ? 'selected' : '' ?>>
                        <?php echo ucwords($row['building']) ?> — Floor <?php echo $row['floor'] ?> (Unit <?php echo $row['house_no'] ?>) — KES <?php echo number_format($row['price'], 2) ?>/Mo
                    </option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="col-md-6">
                <label class="control-label font-weight-bold text-dark">Tenancy Agreement <span class="text-muted standard font-weight-normal">(PDF or Image)</span></label>
                <input type="file" class="form-control-file border p-1 rounded" name="agreement_doc" accept=".pdf,image/*">
                <?php if(!empty($agreement_path)): ?>
                    <small class="text-info d-block mt-1"><i class="fa fa-paperclip"></i> Existing: <a href="assets/uploads/contracts/<?php echo $agreement_path ?>" target="_blank" class="font-weight-bold text-underline">View Uploaded Lease Agreement</a></small>
                <?php endif; ?>
            </div>
        </div>

        <div class="row form-group">
            <div class="col-md-4">
                <label class="control-label font-weight-bold text-dark">Security Deposit <span class="text-muted font-weight-normal">(1 Month)</span></label>
                <input type="number" step="any" min="0" class="form-control text-right font-weight-bold text-dark" name="security_deposit" id="security_deposit" value="<?php echo $security_deposit ?>" required>
            </div>
            <div class="col-md-4">
                <label class="control-label font-weight-bold text-secondary">Initial Rent Baseline <span class="text-muted font-weight-normal">(3 Months)</span></label>
                <input type="number" step="any" class="form-control text-right bg-light text-muted font-weight-bold" name="initial_rent" id="initial_rent" readonly value="0">
            </div>
            <div class="col-md-4">
                <label class="control-label font-weight-bold text-dark">Monthly Parking Fee</label>
                <input type="number" step="any" min="0" class="form-control text-right" name="parking_monthly" id="parking_monthly" value="<?php echo $parking_monthly ?>">
            </div>
        </div>

        <div class="row mt-4 pt-2 border-top">
            <div class="col-md-12 text-right">
                <h4 class="text-dark mb-0">Total Initial Invoice Due: <span class="text-primary font-weight-bold" id="total_initial">KES 0.00</span></h4>
                <small class="text-muted">Calculates: [3 Months Rent] + [1 Month Security Deposit]</small>
            </div>
        </div>
    </form>
</div>

<script>
    $(document).ready(function(){
        // Anchor structural select dropdowns safely inside modal elements to ensure keyboard search inputs function
        $('.select2').select2({
            placeholder: "Select house unit assignment...",
            width: "100%",
            dropdownParent: $('#uni_modal')
        });

        // Trigger balance calculations immediately if we are modifying an existing profile entry
        calculate_initial_liabilities();
    });

    // Automatically recalculate baseline numbers when modifying room configurations or manually fine-tuning values
    $('#house_id, #security_deposit, #parking_monthly').on('change input', function(){
        calculate_initial_liabilities();
    });

    function calculate_initial_liabilities(){
        var house_select = $('#house_id Harvey option:selected');
        var house_select = $('#house_id').find('option:selected');
        var unit_price = house_select.attr('data-price') ? parseFloat(house_select.attr('data-price')) : 0;
        
        var deposit = $('#security_deposit').val() ? parseFloat($('#security_deposit').val()) : 0;
        var parking = $('#parking_monthly').val() ? parseFloat($('#parking_monthly').val()) : 0;

        // Apply our "3-month initial base period" rule structure
        var initial_rent_total = unit_price * 3;
        $('#initial_rent').val(initial_rent_total.toFixed(2));

        // Aggregate overall baseline amount due at move-in
        var combined_total = initial_rent_total + deposit;
        
        $('#total_initial').text('KES ' + combined_total.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }));
    }

    $('#manage-tenant-form').submit(function(e){
        e.preventDefault();
        start_load();
        
        // Use FormData instead of standard serialization to properly ship contract document files across the runtime wire
        var formData = new FormData($(this)[0]);

        $.ajax({
            url: 'ajax.php?action=save_tenant',
            method: 'POST',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: function(resp){
                if(resp == 1){
                    alert_toast("Tenant profile and leasing configuration successfully logged.", 'success');
                    setTimeout(function(){
                        location.reload();
                    }, 1000);
                } else if(resp == 2){
                    alert_toast("Email address configuration already registered to another active profile.", 'danger');
                    end_load();
                } else {
                    alert_toast("An infrastructure response code rejected database execution.", 'danger');
                    end_load();
                }
            },
            error: function(err){
                console.error("Fatal exception during profile creation operation:", err);
                alert_toast("Network connectivity issue experienced.", 'danger');
                end_load();
            }
        });
    });
</script>