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

<div class="container-fluid">
    <div class="col-lg-12">
        <div class="row">
            <div class="col-md-4">
                <form action="" id="manage-utility">
                    <div class="card">
                        <div class="card-header" id="form-title">New Utility Bill Entry</div>
                        <div class="card-body">
                            <input type="hidden" name="id">
                            
                            <div class="form-group">
                                <label class="control-label">Tenant</label>
                                <select name="tenant_id" id="tenant_id" class="custom-select select2" required>
                                    <option value=""></option>
                                    <?php 
                                    $tenants = $conn->query("SELECT t.*, 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 ucwords($row['name']) ?> (<?php echo $row['building'] ?> - <?php echo $row['house_no'] ?>)</option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="form-group">
                                <label class="control-label">Bill Type</label>
                                <select name="type" id="type" class="custom-select" required>
                                    <option value="Water">Water</option>
                                    <option value="Electricity">Electricity</option>
                                    <option value="Other">Other</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label class="control-label">Reading (Units)</label>
                                <input type="number" step="any" name="reading" id="reading" class="form-control" placeholder="Optional">
                            </div>
                            <div class="form-group">
                                <label class="control-label">Amount Billed</label>
                                <input type="number" step="any" name="amount" id="amount" class="form-control" required>
                            </div>
                            <div class="form-group">
                                <label class="control-label">Billing Date</label>
                                <input type="date" name="billing_date" id="billing_date" class="form-control" value="<?php echo date('Y-m-d') ?>" required>
                            </div>
                        </div>
                        <div class="card-footer">
                            <button class="btn btn-primary btn-sm">Save Bill</button>
                            <button class="btn btn-default btn-sm" type="button" id="reset-form">Cancel</button>
                        </div>
                    </div>
                </form>
            </div>
            
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Recent Utility Charges</div>
                    <div class="card-body">
                        <table class="table table-condensed table-bordered table-hover">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Tenant</th>
                                    <th>Type</th>
                                    <th>Amount</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $bills = $conn->query("SELECT b.*, concat(t.lastname,', ',t.firstname) as name FROM utility_bills b inner join tenants t on t.id = b.tenant_id order by b.billing_date desc");
                                while($row=$bills->fetch_assoc()):
                                ?>
                                <tr>
                                    <td><?php echo date("M d, Y",strtotime($row['billing_date'])) ?></td>
                                    <td><b><?php echo ucwords($row['name']) ?></b></td>
                                    <td><span class="badge badge-info px-2 py-1"><?php echo $row['type'] ?></span></td>
                                    <td class="text-right font-weight-bold"><?php echo number_format($row['amount'],2) ?></td>
                                    <td class="text-center">
                                        <button class="btn btn-sm btn-primary edit_bill" type="button" 
                                                data-id="<?php echo $row['id'] ?>" 
                                                data-tenant_id="<?php echo $row['tenant_id'] ?>"
                                                data-type="<?php echo $row['type'] ?>"
                                                data-reading="<?php echo $row['reading'] ?>"
                                                data-amount="<?php echo $row['amount'] ?>"
                                                data-billing_date="<?php echo date('Y-m-d', strtotime($row['billing_date'])) ?>">Edit</button>
                                        <button class="btn btn-sm btn-danger delete_bill" type="button" data-id="<?php echo $row['id'] ?>">Delete</button>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function(){
        // Initialize interactive styling elements inside document tree
        if($('.select2').length > 0){
            $('.select2').select2({
                placeholder: "Search Tenant Name...",
                width: "100%"
            });
        }
    });

    // Populate data back into the form fields when clicking Edit
    $('.edit_bill').click(function(){
        start_load();
        var form = $('#manage-utility');
        form.find("[name='id']").val($(this).attr('data-id'));
        form.find("[name='tenant_id']").val($(this).attr('data-tenant_id')).trigger('change');
        form.find("[name='type']").val($(this).attr('data-type'));
        form.find("[name='reading']").val($(this).attr('data-reading'));
        form.find("[name='amount']").val($(this).attr('data-amount'));
        form.find("[name='billing_date']").val($(this).attr('data-billing_date'));
        
        $('#form-title').text("Modify Utility Bill Entry");
        end_load();
    });

    // Reset layout fields to zero state
    $('#reset-form').click(function(){
        var form = $('#manage-utility');
        form.get(0).reset();
        form.find("[name='id']").val('');
        form.find("[name='tenant_id']").val('').trigger('change');
        form.find("[name='billing_date']").val('<?php echo date('Y-m-d') ?>');
        $('#form-title').text("Utility Bill Entry");
    });

    $('#manage-utility').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 bill successfully saved.", 'success');
                    setTimeout(function(){ location.reload() },1000);
                } else {
                    alert_toast("An error occurred while executing the transaction.", 'danger');
                    end_load();
                }
            }
        });
    });

    $('.delete_bill').click(function(){
        _conf("Delete this utility record permanently? This will update the tenant balance immediately.","delete_utility",[$(this).attr('data-id')]);
    });

    function delete_utility($id){
        start_load();
        $.ajax({
            url:'ajax.php?action=delete_utility',
            method:'POST',
            data:{id:$id},
            success:function(resp){
                if(resp==1){
                    alert_toast("Record successfully deleted.", 'success');
                    setTimeout(function(){ location.reload() },1000);
                } else {
                    alert_toast("An error occurred while removing the data record.", 'danger');
                    end_load();
                }
            }
        });
    }
</script>