<?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>
                        <!-- brokerage details  -->
                        <div class="col-md-12">
                            <div class="alert alert-info" style="">
                                <span class="no-margin font-medium-xs bold"
                                    style="display: flex;justify-content: center;font-weight:800;">
                                    <?php echo empty($brokerage_data) ? 'Add ' : 'Update '; ?>Brokerage Details
                                </span>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <?php if (empty($brokerage_data)) { ?>
                                <?php echo form_open((admin_url('cases/add_brokerage')), ['id' => 'myForm']); ?>
                                <div class='form-group' app-field-wrapper='doc_type'>
                                    <label for='name' class='control-label'><span style="color:red;font-weight:700;">*</span> Enter Brokerage Name</label>
                                    <input type="text" class="form-control" id="name" name="name">
                                    <b>
                                        <div class="invalid-feedback" style="color:red;margin-top:4px;"></div>
                                    </b>
                                </div>
                                <div class="form-group">
                                    <label for='email' class='control-label'>Enter Brokerage Email</label>
                                    <input type="text" class="form-control" id="email" name="email">
                                </div>
                                <div class="form-group">
                                    <label for='address' class='control-label'>Enter Brokerage Address</label>
                                    <input type="text" class="form-control" id="address" name="address">
                                </div>
                                <div class="form-group">
                                    <label for='phone' class='control-label'>Enter Brokerage Phone No</label>
                                    <input type="text" class="form-control" id="phone" name="phone">
                                </div>
                                <div class="form-group">
                                    <label for='color' class='control-label'>Enter Color</label>
                                    <input type="color" class="form-control" id="color" name="color">
                                </div>
                                <div class="" style="display:flex;align-items:center;">
                                    <label for='color' class='control-label'>Mandatory Brokerage</label>
                                    <input type="checkbox" class="" id="mandatory" name="mandatory" style="margin-left:5px;">
                                </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/brokerage');?>" class="btn btn-primary" style="margin-bottom:15px;"><i class="fa fa-plus" aria-hidden="true"></i> Add Brokerage</a>
                                <?php echo form_open((admin_url('cases/add_brokerage')), ['id' => 'edit_myForm']); ?>
                                <div class='form-group' app-field-wrapper='doc_type'>
                                    <label for='name' class='control-label'>Enter Brokerage name</label>
                                    <input type="text" class="form-control" id="name" name="name"
                                        value="<?php echo $brokerage_data->name; ?>">
                                    <b>
                                        <div class="invalid-feedback" style="color:red;margin-top:4px;"></div>
                                    </b>
                                    <input type="hidden" id="brokerage_id" name="brokerage_id"
                                        value="<?php echo $brokerage_data->id; ?>">
                                </div>
                                <div class="form-group">
                                    <label for='email' class='control-label'>Enter Brokerage Email</label>
                                    <input type="text" class="form-control" id="email" name="email" value="<?php echo $brokerage_data->email; ?>">
                                </div>
                                <div class="form-group">
                                    <label for='address' class='control-label'>Enter Brokerage Address</label>
                                    <input type="text" class="form-control" id="address" name="address" value="<?php echo $brokerage_data->address; ?>">
                                </div>
                                <div class="form-group">
                                    <label for='phone' class='control-label'>Enter Brokerage Phone No</label>
                                    <input type="text" class="form-control" id="phone" name="phone" value="<?php echo $brokerage_data->phone; ?>">
                                </div>
                                <div class="form-group">
                                    <label for='color' class='control-label'>Enter Color</label>
                                    <input type="color" class="form-control" id="color" name="color" value="<?php echo $brokerage_data->color; ?>">
                                </div>
                                <div class="" style="display:flex;align-items:center;">
                                    <label for='color' class='control-label'>Mandatory Brokerage</label>
                                    <input type="checkbox" class="" id="mandatory" name="mandatory" style="margin-left:5px;" <?php echo ($brokerage_data->mandatory == 1)? 'checked' : ''; ?>>
                                </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-8">
                            <div style="overflow-x: auto;">
                                <table class="table table-leads customizable-table number-index-2 dataTable no-footer" style="width: 100%;">
                                    <thead>
                                        <tr>
                                            <th style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">Name</th>
                                            <th style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">Email</th>
                                            <th style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">Address</th>
                                            <th style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">Phone No</th>
                                            <th style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">Color</th>
                                            <th style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">Mandatory</th>
                                            <th style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">Created at</th>
                                            <th style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem; text-align: center;">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody id="brokerageList"></tbody>
                                </table>
                            </div>
                        </div>
                        <div class="clearfix"></div>
                        <hr class="-tw-mx-4 tw-border-neutral-200" />
                        <?php if (empty($brokerage_data)) {?>
                        <!-- Staff table content show -->
                        <div class="col-md-12">
                            <div class="alert alert-info" style="margin-top:40px;">
                                <span class="no-margin font-medium-xs bold"
                                    style="display: flex;justify-content: center;font-weight:800;">
                                    Broker Details
                                </span>
                            </div>
                        </div>
                        <div class="clearfix"></div>
                        <hr class="-tw-mx-4 tw-border-neutral-200" />
                        <!-- add broker button -->
                        <div class="col-md-12">
                            <button class="btn btn-primary" id="add_broker_btn">
                                Add Broker
                            </button>
                        </div>
                        <div class="clearfix"></div>
                        <hr class="-tw-mx-4 tw-border-neutral-200" />
                        <div class="col-md-12">
                            <?php if (!empty($staff_data)) : ?>
                                <table class="table table-leads customizable-table number-index-2 dataTable no-footer" style="width: 100%;">
                                    <thead>
                                        <tr>
                                            <th style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">First Name</th>
                                            <th style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">Last Name</th>
                                            <th style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">Brokerage Name</th>
                                            <th style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">Email</th>
                                            <th style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">Phone</th>
                                            <th style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">Address</th>
                                            <th style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($staff_data as $staff) : ?>
                                            <tr>
                                                <td style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;"><?php echo htmlspecialchars($staff->firstname); ?></td>
                                                <td style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;"><?php echo htmlspecialchars($staff->lastname); ?></td>
                                                <td style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;"><?php echo htmlspecialchars($staff->brokerage_name); ?></td>
                                                <td style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;"><?php echo htmlspecialchars($staff->email); ?></td>
                                                <td style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;"><?php echo htmlspecialchars($staff->phone); ?></td>
                                                <td style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;"><?php echo htmlspecialchars($staff->address); ?></td>
                                                <td style="display: flex; justify-content: center; white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">
                                                    <a href="<?php echo base_url('/admin/staff/member/' . $staff->staff_id ) ?>" class="btn btn-primary edit-record" style="font-size: 0.8rem; padding: 0.3rem 0.5rem;">Edit</a>
                                                    <!-- <button onclick="deleteStaffMember(<?php echo $staff->staff_id; ?>);" class="btn btn-danger delete-btn" style="font-size: 0.8rem; padding: 0.3rem 0.5rem; margin-left: 5px;">Delete</button> -->
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                                <?php else : ?>
                                    <p>No staff data found.</p>
                            <?php endif; ?>
                        </div>
                        <?php } ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="add_broker_modal" tabindex="-1" role="dialog"
    aria-labelledby="statusChangeModalLabel" aria-hidden="true"
    style="width: 100%; background-color: #3831317a; overflow:hidden;">
    <div class="modal-dialog" role="document"
        style="display: flex; justify-content: center; align-items: center; height: 100%;">
        <div class="modal-content" style="max-height: 90vh; overflow: hidden;">
            <div class="modal-header">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <h4>Add Broker Details</h4>
                    <a type="button" class="close" id="add_broker_close_modal_btn" data-dismiss="modal"
                        aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </a>
                </div>
            </div>
            <div class="modal-body" style="overflow-y: auto; max-height: calc(100vh - 150px); padding: 15px;">
                <!-- Broker add form -->
                <div class="col-md-12">
                <?php echo form_open('admin/staff/member', ['class' => 'mtop15 mbot15', 'id' => 'add_broker_details', 'style' => 'width:500px;']); ?>
                    <!-- <div class="form-group">
                        <label for="profile_image" class="profile-image"><?php echo _l('staff_edit_profile_image'); ?></label>
                        <input type="file" name="profile_image" class="form-control" id="profile_image">
                    </div> -->
                    <div class="">
                        <?php echo render_input('firstname', '<span style="color:red;">*</span> First Name', '', 'text', ); ?>
                        <span class="error-message" id="error-firstname" style="color: red; display: none;">First name is required</span>
                    </div>
                    <div class="form-group">
                        <?php echo render_input('lastname', 'staff_add_edit_lastname', '', 'text'); ?>
                    </div>
                    <div class="form-group">
                        <?php echo render_input('phonenumber', 'staff_add_edit_phonenumber', ''); ?>
                    </div>
                    <div class="">
                        <?php echo render_input('email', '<span style="color:red;">*</span> Email', '', 'email', ['autocomplete' => 'off']); ?>
                        <span class="error-message" id="error-email" style="color: red; display: none;">Email is required</span>
                    </div>
                    <div class="form-group">
                        <?php echo render_textarea('email_signature', 'settings_email_signature', '', ['data-entities-encode' => 'true']); ?>
                    </div>
                    <div class="form-group select-placeholder" id="brokerage_select">
                        <span style="color:red;">*</span> <label for="brokerage_id"><?php echo _l('Select Brokerage'); ?></label>
                        <select class="selectpicker" data-none-selected-text="<?php echo _l('Select Broker Agent'); ?>" data-width="100%" name="brokerage_ids" id="brokerage_id" required>
                            <option value="" >Nothing Selected</option>
                            <?php 
                            if (!empty($all_brokerage_data)) {
                                foreach ($all_brokerage_data as $brokerage) { 
                                    $id = htmlspecialchars($brokerage['id']);
                                    $name = htmlspecialchars($brokerage['name']);
                                ?>
                                <option value="<?php echo $id; ?>">
                                    <?php echo $name; ?>
                                </option>
                                <?php 
                                }
                            } else { ?>
                                <option disabled><?php echo _l('No Brokerage Available'); ?></option>
                            <?php } ?>
                        </select>
                        <span class="select_brokerage" id="laywer_firm_select" style="color: red; display: none;">Please select a brokerage</span>
                    </div>
                    <div class="form-group">
                        <?php
                            foreach ($roles as $role) {
                                if ($role['roleid'] == 2) {
                                    $selected = $role['roleid'];
                                }
                            }
                        ?>
                        <?php echo render_select('role', $roles, ['roleid', 'name'], 'staff_add_edit_role', $selected); ?>
                    </div>
                    <div class="form-group checkbox checkbox-primary">
                        <input type="checkbox" name="send_welcome_email" id="send_welcome_email" checked>
                        <label for="send_welcome_email"><?php echo _l('staff_send_welcome_email'); ?></label>
                    </div>
                    <div class="form-group">
                        <span style="color:red;">*</span> <label for="password" class="control-label"><?php echo _l('staff_add_edit_password'); ?></label>
                        <div class="input-group">
                            <input type="password" class="form-control password" name="password" id="password" autocomplete="off">
                            <span class="input-group-addon tw-border-l-0">
                                <a href="#password" class="show_password" onclick="showPassword('password'); return false;">
                                    <i class="fa fa-eye"></i>
                                </a>
                            </span>
                            <span class="input-group-addon">
                                <a href="#" class="generate_password" onclick="generatePassword(this);return false;">
                                    <i class="fa fa-refresh"></i>
                                </a>
                            </span>
                        </div>
                        <span class="error-message" style="color: red; display: none;">Password is required</span>
                    </div>
                    <hr />
                    <h4 class="font-medium mbot15 bold"><?php echo _l('staff_add_edit_permissions'); ?></h4>
                    <?php $this->load->view('admin/staff/permissions', $permissionsData); ?>

                    <input type="submit" class="btn btn-primary" value="Submit" style="float:right;margin-top:15px;margin-bottom:15px;">

                <?php echo form_close(); ?>
                </div>
            </div>
        </div>
    </div>
</div>
<?php init_tail(); ?>
<script>
    $(document).ready(function () {
        // add broker js code
        $(document).on('click', '#add_broker_btn', function(){
            $('#add_broker_modal').modal('show'); 
        });
        $('#add_broker_close_modal_btn').click(function () {
                $('#add_broker_modal').modal('hide');
        });
        $('#add_broker_details').on('submit', function (e) {
            e.preventDefault();

            $('.error-message').hide();

            let form = $(this);
            let formData = new FormData(this); 
            let emailValue = form.find('input[name="email"]').val().trim();
            let firstnameValue = form.find('input[name="firstname"]').val().trim();
            let passwordValue = form.find('input[name="password"]').val().trim();
            let BrokerageValue = $('#brokerage_id').val();
            let isValid = true;

            if (firstnameValue === '') {
                $('#error-firstname').css({
                    'display': 'flex',
                    'margin-top': '-9px',
                    'color': 'red'
                }).show();
                isValid = false;
            }

            if (emailValue === '') {
                $('#error-email').css({
                    'display': 'flex',
                    'margin-top': '-9px',
                    'color': 'red'
                }).text('Email is required').show();
                isValid = false;
            }
            if (passwordValue === '') {
                $('input[name="password"]').closest('.form-group').find('.error-message').text('Password is required').show();
                isValid = false;
            }

            if (BrokerageValue === '') {
                $('#laywer_firm_select .error-message').text('Please select a lawyer firm').show();
                isValid = false;
            }
            if (isValid) {
                $.ajax({
                    url: '<?php echo admin_url('misc/staff_email_exists') ?>',
                    type: 'POST',
                    data: { email: emailValue },
                    success: function (response) {
                        if (response == 'false') {
                            $('#error-email').css({
                                'display': 'flex',
                                'margin-top': '-9px',
                                'color': 'red'
                            }).text('This email is already in use for a different role,Please choose a different email.').show();
                        } else {
                            $('#error-email').hide();

                            $.ajax({
                                url: form.attr('action'), 
                                type: 'POST',
                                data: formData,
                                contentType: false, 
                                processData: false, 
                                success: function (response) {
                                    alert_float('success', 'Form submitted successfully');
                                    form[0].reset();
                                    location.reload(true);
                                },
                                error: function (xhr, status, error) {
                                    alert_float('danger', 'An error occurred while submitting the form');
                                    console.error('Form submission error:', xhr.responseText);
                                }
                            });
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('Error checking email:', xhr.responseText);
                    }
                });
            }
        });
        document.getElementById('phonenumber').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) {
                $("#phonenumber_error").show();
                $(".lead-save-btn").attr('disabled', true);
            } else {
                $("#phonenumber_error").hide();
            }
        });
    function deleteStaffMember(staffId) {
        if (confirm('Are you sure you want to delete this staff member?')) {
            $.ajax({
                url: '<?php echo base_url("admin/staff/delete_by_current_staff"); ?>',
                type: 'POST',
                data: { id: staffId },
                success: function(response) {   
                    if (response.success) {
                        // Remove the row from the table
                        $('#staff-row-' + staffId).remove();
                        alert_float('success','Staff member deleted successfully.');
                    } else {
                        alert_float('danger','Failed to delete staff member: ' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error deleting staff member:', xhr.responseText);
                }
            });
        }
    }
    
    // Brokerage js code
    document.getElementById('phone').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) {
            $("#phone").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_brokerage'); ?>',
                data: formData,
                dataType: 'json',
                success: function (response) {
                    if (response.status === 'error') {
                        $('.invalid-feedback').text(response.message);
                    } else {
                        $('#myForm')[0].reset();
                        loadStates();
                        alert_float('success', 'brokerage 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_brokerage'); ?>',
                data: formData,
                dataType: 'json',
                success: function (response) {
                    if (response.status === 'error') {
                        $('.invalid-feedback').text(response.message);
                    } else {
                        loadStates();
                        alert_float('success', 'brokerage 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_brokerage'); ?>',
                dataType: 'json',
                success: function (response) {
                    $('#brokerageList').empty();
                    $.each(response, function (index, state) {
                        var mandatory_status = '';
                        if (state.mandatory == 1) {
                            mandatory_status = '<span style="color: green;">Yes</span>';
                        } else {
                            mandatory_status = '<span style="color: red;">No</span>';
                        }
                        if(state.mandatory == 1){
                            
                        }
                        var newRow = $('<tr>');
                        newRow.append('<td style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">' + state.name + '</td>');
                        newRow.append('<td style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">' + state.email + '</td>');
                        newRow.append('<td style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">' + state.address + '</td>');
                        newRow.append('<td style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">' + state.phone + '</td>');
                        newRow.append('<td style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">' + state.color + '</td>');
                        newRow.append('<td style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">' + mandatory_status + '</td>');
                        newRow.append('<td style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">' + state.created_at + '</td>');

                        var actionColumn = $('<td style="display: flex; justify-content: center; white-space: nowrap; font-size: 0.9rem; padding: 0.5rem;">');
                        actionColumn.append('<a href="<?php echo base_url('/admin/cases/brokerage/') ?>' + state.id + '" class="btn btn-primary edit-record" style="font-size: 0.8rem; padding: 0.3rem 0.5rem;">Edit</a>');
                        // actionColumn.append('<button data-id="' + state.id + '" class="btn btn-danger delete-btn" style="font-size: 0.8rem; padding: 0.3rem 0.5rem; margin-left: 5px;">Delete</button>');

                        newRow.append(actionColumn);
                        $('#brokerageList').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_brokerage'); ?>',
                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 if(response.status == 'fail'){
                        alert_float('danger', 'This record cannot be deleted because it is referenced in multiple locations.');
                    } else {
                        alert_float('danger', 'Failed to delete record!');
                    }
                },
                error: function (xhr, status, error) {
                    console.error(xhr.responseText);
                }
            });
        }
    });
</script>
</body>

</html>