<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<?php init_head(); ?>
<div id="wrapper">
    <div class="content">
        <div class="row">
            <div class="col-md-12">
                <div class="panel_s panel-table-full">
                    <div class="panel-body">
                        <div class="clearfix"></div>
                        <div class="col-md-6">
                            <?php if (empty($lender_data)) { ?>
                                <?php echo form_open((admin_url('cases/add_lender')), ['id' => 'myForm']); ?>
                                <div class='form-group' app-field-wrapper='doc_type'>
                                    <label for='lender' class='control-label'><span style="color:red;font-weight:700;">*</span> Enter Lender</label>
                                    <input type="text" class="form-control" id="lender" name="lender">
                                    <b>
                                        <div class="invalid-feedback" style="color:red;margin-top:4px;"></div>
                                    </b>
                                </div>
                                <div class="form-group">
                                    <label for='lender' class='control-label'>Enter Lender Address</label>
                                    <input type="text" class="form-control" id="lender_address" name="lender_address">
                                </div>
                                <div class="form-group">
                                    <label for='lender' class='control-label'>Enter Lender Phone No</label>
                                    <input type="text" class="form-control" id="lender_phoneno" name="lender_phoneno">
                                </div>
                                <input type="submit" class="btn btn-primary" id="submitButton"
                                        style="margin-top: 10px; float:right;">
                                <?php echo form_close(); ?>
                            <?php
                            } else { ?>
                                <a href="<?php echo admin_url('/cases/lender');?>" class="btn btn-primary" style="margin-bottom:15px;"><i class="fa fa-plus" aria-hidden="true"></i> Add Lender</a>
                                <?php echo form_open((admin_url('cases/add_lender')), ['id' => 'edit_myForm']); ?>
                                <div class='form-group' app-field-wrapper='doc_type'>
                                    <label for='lender' class='control-label'>Enter Lender</label>
                                    <input type="text" class="form-control" id="lender" name="lender"
                                        value="<?php echo $lender_data->bank_name; ?>">
                                    <b>
                                        <div class="invalid-feedback" style="color:red;margin-top:4px;"></div>
                                    </b>
                                    <input type="hidden" id="lender_id" name="lender_id"
                                        value="<?php echo $lender_data->id; ?>">
                                </div>
                                <div class="form-group">
                                    <label for='lender' class='control-label'>Enter Lender Address</label>
                                    <input type="text" class="form-control" id="lender_address" name="lender_address" value="<?php echo $lender_data->lender_address; ?>">
                                </div>
                                <div class="form-group">
                                    <label for='lender' class='control-label'>Enter Lender Phone No</label>
                                    <input type="text" class="form-control" id="lender_phoneno" name="lender_phoneno" value="<?php echo $lender_data->lender_phoneno; ?>">
                                </div>
                                <button type="submit" class="btn btn-primary"
                                        style="margin-top: 10px; float:right;">Update</button>
                                <?php echo form_close(); ?>
                            <?php } ?>
                        </div>
                        <div class="col-md-6">
                            <table class="table table-leads customizable-table number-index-2 dataTable no-footer">
                                <thead>
                                    <th>Lender name</th>
                                    <th>Lender Address</th>
                                    <th>Lender PhoneNo</th>
                                    <th>Created at</th>
                                    <th style="display:flex;justify-content:center;">Action</th>
                                </thead>
                                <tbody id="lenderList">
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php init_tail(); ?>
<script>
    $(document).ready(function () {
        
    document.getElementById('lender_phoneno').addEventListener('input', function (e) {
        var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
        e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');

        $(".lead-save-btn").attr('disabled', false);
        if (e.target.value.length <= 13) {
            $("#lender_phoneno").show();
            // $(".lead-save-btn").attr('disabled', true);
        } else {
            // $("#lender_phoneno").hide();
        }
    });
        // Load states when the page loads
        loadStates();

        // Handle form submission
        $('#myForm').submit(function (event) {
            event.preventDefault();
            $('.invalid-feedback').empty();
            var formData = $(this).serialize();
            $.ajax({
                type: 'POST',
                url: '<?php echo base_url('admin/cases/add_lender'); ?>',
                data: formData,
                dataType: 'json',
                success: function (response) {
                    if (response.status === 'error') {
                        $('.invalid-feedback').text(response.message);
                    } else {
                        $('#myForm')[0].reset();
                        loadStates();
                        alert_float('success', 'State added successfully.');
                    }
                },
                error: function (xhr, status, error) {
                    console.log('Error fetching data');
                }
            });
        });
        // edit form valitdtion
        $('#edit_myForm').submit(function (event) {
            event.preventDefault();
            $('.invalid-feedback').empty();
            var formData = $(this).serialize();
            $.ajax({
                type: 'POST',
                url: '<?php echo base_url('admin/cases/add_lender'); ?>',
                data: formData,
                dataType: 'json',
                success: function (response) {
                    if (response.status === 'error') {
                        $('.invalid-feedback').text(response.message);
                    } else {
                        loadStates();
                        alert_float('success', 'State updated successfully.');
                    }
                },
                error: function (xhr, status, error) {
                    console.log('Error fetching data');
                }
            });
        });

        // Function to load states using AJAX
        function loadStates() {
            $.ajax({
                type: 'GET',
                url: '<?php echo base_url('admin/cases/show_all_lender'); ?>',
                dataType: 'json',
                success: function (response) {
                    $('#lenderList').empty();
                    $.each(response, function (index, state) {
                        var newRow = $('<tr>');
                        newRow.append('<td>' + state.bank_name + '</td>');
                        newRow.append('<td>' + state.lender_address + '</td>');
                        newRow.append('<td>' + state.lender_phoneno + '</td>');
                        newRow.append('<td>' + state.created_at + '</td>');
                        var actionColumn = $('<td style="display:flex;">');
                        actionColumn.append('<a href="<?php echo base_url('/admin/cases/lender/') ?>' + state.id + '" class="btn btn-primary edit-record">Edit</a>');
                        actionColumn.append('<button data-id="' + state.id + '" class="btn btn-danger delete-btn" style="margin-left:5px;">Delete</button>');
                        newRow.append(actionColumn);
                        $('#lenderList').append(newRow);
                    });
                },
                error: function (xhr, status, error) {
                    console.log('Error fetching data');
                }
            });

        }
    });
    // delete the state data
    $(document).on('click', '.delete-btn', function () {
        var stateId = $(this).data('id');
        var row = $(this).closest('tr');
        if (confirm("Are you sure you want to delete this record?")) {
            $.ajax({
                type: 'POST',
                url: '<?php echo base_url('admin/cases/delete_lender'); ?>',
                data: { id: stateId },
                dataType: 'json',
                success: function (response) {
                    if (response.status == 'success') {
                        row.fadeOut(400, function () {
                            $(this).remove();
                        });
                        alert_float('success', 'Record deleted successfully.');
                    } else {
                        alert_float('error', 'Failed to delete record!');
                    }
                },
                error: function (xhr, status, error) {
                    console.error(xhr.responseText);
                }
            });
        }
    });
</script>
</body>

</html>