<?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">
                        <?php if(($laywer_firm_data->type == '' || $laywer_firm_data->type == 'laywer-firm') && $laywer_firm_data->type != 'update-laywer'){?>
                            <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($laywer_firm_data) ? 'Add ' : 'Update '; ?>Law Firm Details
                                    </span>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <?php if (empty($laywer_firm_data)) { ?>
                                    <?php echo form_open((admin_url('cases/add_laywer_firm')), ['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 Law Firm 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 Law Firm Email</label>
                                        <input type="text" class="form-control" id="email" name="email">
                                    </div>
                                    <div class="form-group">
                                        <label for='address' class='control-label'>Enter Law Firm Address</label>
                                        <input type="text" class="form-control" id="address" name="address">
                                    </div>
                                    <div class="form-group">
                                        <label for='phone' class='control-label'>Enter Law Firm 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>
                                    <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/laywer');?>" class="btn btn-primary" style="margin-bottom:15px;"><i class="fa fa-plus" aria-hidden="true"></i> Add Law Firm</a>
                                    <?php echo form_open((admin_url('cases/add_laywer_firm')), ['id' => 'edit_myForm']); ?>
                                    <div class='form-group' app-field-wrapper='doc_type'>
                                        <label for='name' class='control-label'>Enter Law Firm name</label>
                                        <input type="text" class="form-control" id="name" name="name"
                                            value="<?php echo $laywer_firm_data->name; ?>">
                                        <b>
                                            <div class="invalid-feedback" style="color:red;margin-top:4px;"></div>
                                        </b>
                                        <input type="hidden" id="laywer_firm_id" name="laywer_firm_id"
                                            value="<?php echo $laywer_firm_data->id; ?>">
                                    </div>
                                    <div class="form-group">
                                        <label for='email' class='control-label'>Enter Law Firm Email</label>
                                        <input type="text" class="form-control" id="email" name="email" value="<?php echo $laywer_firm_data->email; ?>">
                                    </div>
                                    <div class="form-group">
                                        <label for='address' class='control-label'>Enter Law Firm Address</label>
                                        <input type="text" class="form-control" id="address" name="address" value="<?php echo $laywer_firm_data->address; ?>">
                                    </div>
                                    <div class="form-group">
                                        <label for='phone' class='control-label'>Enter Law Firm Phone No</label>
                                        <input type="text" class="form-control" id="phone" name="phone" value="<?php echo $laywer_firm_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 $laywer_firm_data->color; ?>">
                                    </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;">Created at</th>
                                                <th style="white-space: nowrap; font-size: 0.9rem; padding: 0.5rem; text-align: center;">Action</th>
                                            </tr>
                                        </thead>
                                        <tbody id="LaywerFirmList"></tbody>
                                    </table>
                                </div>
                            </div>
                        <?php } ?>
                        <!-- add laywer code -->
                        <?php if($laywer_firm_data->type == ''){?>
                            <div class="clearfix"></div>
                            <hr class="-tw-mx-4 tw-border-neutral-200" />
                            <?php if (empty($laywer_firm_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;">
                                        Law 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 Law
                                </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;">Law Firm 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->laywer_firm_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/cases/laywer/update-laywer/' . $staff->laywer_id ) ?>" class="btn btn-primary edit-record" style="font-size: 0.8rem; padding: 0.3rem 0.5rem;">Edit</a>
                                                        <button 
                                                            class="btn btn-danger btn-delete-lawyer" 
                                                            data-laywer-id="<?php echo $staff->laywer_id; ?>" 
                                                            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 } ?>
                        <?php } ?>
                        <!-- Updated the laywer firm code -->
                        <?php if($laywer_firm_data->type == 'update-laywer'){?>
                            <!-- Staff table content show -->
                            <div class="col-md-12">
                                <a href="<?php echo base_url('admin/Cases/laywer')?>" class="btn btn-primary">
                                    Back to Add Law Page
                                </a>
                            </div>
                            <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;">
                                        Update Law Details
                                    </span>
                                </div>
                            </div>
                            <!-- update laywer form details -->
                            <div class="col-md-4">
                                <?php 
                                echo form_open((admin_url('Cases/add_lawyer')), [
                                    'class' => 'mtop15 mbot15', 
                                    'id' => 'update_laywer_details', 
                                    'style' => 'width:500px;'
                                ]); 
                                ?>
                                <input type="hidden" name="laywer_id" value="<?php echo $laywer_firm_data->id;?>">
                                <!-- First Name -->
                                <div class="">
                                    <?php 
                                    echo render_input(
                                        'firstname', 
                                        '<span style="color:red;">*</span> First Name', 
                                        isset($laywer_firm_data->firstname) ? $laywer_firm_data->firstname : '', 
                                        'text'
                                    ); 
                                    ?>
                                    <span class="error-message" id="error-firstname" style="color: red; display: none;">First name is required</span>
                                </div>

                                <!-- Last Name -->
                                <div class="form-group">
                                    <?php 
                                    echo render_input(
                                        'lastname', 
                                        'Last Name', 
                                        isset($laywer_firm_data->lastname) ? $laywer_firm_data->lastname : '', 
                                        'text'
                                    ); 
                                    ?>
                                </div>

                                <!-- Phone Number -->
                                <div class="form-group">
                                    <?php 
                                    echo render_input(
                                        'phonenumber', 
                                        'Phone Number', 
                                        isset($laywer_firm_data->phone) ? $laywer_firm_data->phone : '', 
                                        'text'
                                    ); 
                                    ?>
                                </div>

                                 <?php echo render_input('address', 'Address', $laywer_firm_data->address, 'text'); ?>
                                <div class="">
                                    <?php 
                                    echo render_input(
                                        'email', 
                                        '<span style="color:red;">*</span> Email', 
                                        isset($laywer_firm_data->email) ? $laywer_firm_data->email : '', 
                                        'email', 
                                        ['autocomplete' => 'off']
                                    ); 
                                    ?>
                                    <span class="error-message" id="error-email" style="color: red; display: none;">Email is required</span>
                                </div>

                                <!-- Lawyer Firm Dropdown -->
                                <div class="form-group select-placeholder" id="lawyer_firm_select">
                                    <span style="color:red;">*</span> 
                                    <label for="lawyer_firm_id"><?php echo _l('Select Lawyer Firm'); ?></label>
                                    <select 
                                        class="selectpicker" 
                                        data-none-selected-text="<?php echo _l('Select Lawyer Firm'); ?>" 
                                        data-width="100%" 
                                        name="lawyer_firm_ids" 
                                        id="lawyer_firm_id"
                                    >
                                        <option value="">Nothing Selected</option>
                                        <?php 
                                        if (!empty($laywer_firm_data->laywer_firm_data)) {
                                            foreach ($laywer_firm_data->laywer_firm_data as $firm) { 
                                                $id = htmlspecialchars($firm['id']);
                                                $name = htmlspecialchars($firm['name']);
                                                $selected = (isset($laywer_firm_data->laywer_firm_id) && $laywer_firm_data->laywer_firm_id == $id) ? 'selected' : '';
                                        ?>
                                            <option value="<?php echo $id; ?>" <?php echo $selected; ?>>
                                                <?php echo $name; ?>
                                            </option>
                                        <?php 
                                            }
                                        } else { 
                                        ?>
                                            <option disabled><?php echo _l('No Lawyer Firm Available'); ?></option>
                                        <?php 
                                        } 
                                        ?>
                                    </select>
                                    <span class="error-message" style="color: red; display: none;">Please select a lawyer firm</span>
                                </div>

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

                                <?php echo form_close(); ?>
                            </div>
                            <div class="col-md-8">
                                <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;">Law Firm 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 ($laywer_firm_data->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->laywer_firm_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->laywer_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/cases/laywer/update-laywer/' . $staff->laywer_id ) ?>" class="btn btn-primary edit-record" style="font-size: 0.8rem; padding: 0.3rem 0.5rem;">Edit</a>
                                                    <button 
                                                        class="btn btn-danger btn-delete-lawyer" 
                                                        data-laywer-id="<?php echo $staff->laywer_id; ?>" 
                                                        style="font-size: 0.8rem; padding: 0.3rem 0.5rem; margin-left: 5px;">
                                                        Delete
                                                    </button>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php } ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="add_laywer_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 Law Frim Details</h4>
                    <a type="button" class="close" id="add_laywer_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_url('Cases/add_laywer')), ['class' => 'mtop15 mbot15', 'id' => 'add_laywer_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>
                        <?php echo render_input('address', 'Address', '', 'text'); ?>
                        <div class="form-group select-placeholder" id="laywer_firm_select">
                            <span style="color:red;">*</span> <label for="laywer_firm_id"><?php echo _l('Select Law Firm'); ?></label>
                            <select class="selectpicker" data-none-selected-text="<?php echo _l('Select Law Firm Agent'); ?>" data-width="100%" name="laywer_firm_ids" id="laywer_firm_id">
                                <option value="" >Nothing Selected</option>
                                <?php 
                                if (!empty($all_laywer_data)) {
                                    foreach ($all_laywer_data as $laywer_firm) { 
                                        $id = htmlspecialchars($laywer_firm['id']);
                                        $name = htmlspecialchars($laywer_firm['name']);
                                    ?>
                                    <option value="<?php echo $id; ?>">
                                        <?php echo $name; ?>
                                    </option>
                                    <?php 
                                    }
                                } else { ?>
                                    <option disabled><?php echo _l('No Law Firm Available'); ?></option>
                                <?php } ?>
                            </select>
                            <span class="error-message" style="color: red; display: none;">Please select a laywer</span>
                        </div>
                        <input type="submit" class="btn btn-primary" value="Submit" style="float:right;margin-top:15px;margin-bottom:30px;">

                    <?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_laywer_modal').modal('show'); 
        });
        $('#add_laywer_close_modal_btn').click(function () {
                $('#add_laywer_modal').modal('hide');
        });
        $('#add_laywer_details').on('submit', function (e) {
            e.preventDefault();

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

            let form = $(this);

            let emailInput = form.find('input[name="email"]');
            let firstnameInput = form.find('input[name="firstname"]');
            let lastnameInput = form.find('input[name="lastname"]');
            let addressInput = form.find('input[name="address"]');
            let phoneInput = form.find('input[name="phonenumber"]');
            let laywerFirmSelect = $('#laywer_firm_id');

            let emailValue = emailInput.val()?.trim() ?? '';
            let firstnameValue = firstnameInput.val()?.trim() ?? '';
            let lastnameValue = lastnameInput.val()?.trim() ?? '';
            let addressValue = addressInput.val()?.trim() ?? '';
            let phoneValue = phoneInput.val()?.trim() ?? '';
            let laywerFirmValue = laywerFirmSelect.val() ?? '';

            let isValid = true;

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

            if (!emailValue) {
                $('#error-email').css({
                    'display': 'flex',
                    'margin-top': '-9px',
                    'color': 'red'
                }).text('Email is required').show();
                isValid = false;
            }

            if (!laywerFirmValue) {
                $('#laywer_firm_select .error-message').css('color', 'red')
                    .text('Please select a lawyer firm').show();
                isValid = false;
            }

            if (isValid) {
                $.ajax({
                    url: '<?php echo admin_url("Cases/laywer_email_exists") ?>',
                    type: 'POST',
                    data: { email: emailValue },
                    dataType: 'json',
                    success: function (response) {
                        if (!response.success) {
                            $('#error-email').css({
                                'display': 'flex',
                                'margin-top': '-9px',
                                'color': 'red'
                            }).text('Email already exists').show();
                        } else {
                            $('#error-email').hide();

                            $.ajax({
                                url: form.attr('action'),
                                type: 'POST',
                                data: {
                                    firstname: firstnameValue,
                                    lastname: lastnameValue,
                                    email: emailValue,
                                    phone: phoneValue,
                                    address: addressValue,
                                    laywer_firm_id: laywerFirmValue
                                },
                                dataType: 'json',
                                success: function (response) {
                                    if (response.success) {
                                        alert_float('success', 'Form submitted successfully');
                                        form[0].reset();
                                        location.reload(true);
                                    } else {
                                        alert_float('danger', 'An error occurred while submitting the form');
                                    }
                                },
                                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);
                    }
                });
            }
        });
        // update the laywer details
        $('#update_laywer_details').on('submit', function (e) {
            e.preventDefault();

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

            var formData = $(this).serialize();

            $.ajax({
                url: '<?php echo admin_url("Cases/update_lawyer"); ?>',
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function (response) {
                    if (response.success) {
                        alert_float('success', 'Record Updated successfully.');
                        location.reload(); 
                    } else if (response.errors) {
                        if (response.errors.firstname) {
                            $('#error-firstname').text(response.errors.firstname).show();
                        }
                        if (response.errors.email) {
                            $('#error-email').text(response.errors.email).show();
                        }
                        if (response.errors.lawyer_firm_ids) {
                            $('#lawyer_firm_select .error-message')
                                .text(response.errors.lawyer_firm_ids)
                                .show();
                        }
                    } else {
                        alert_float('danger', 'Failed to update the lawyer. Please try again.');
                    }
                },
                error: function () {
                    alert_float('danger', 'Failed to update the lawyer. Please try again.');
                },
            });
        });
        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);
                }
            });
        }
    }
    $(document).on('click', '.btn-delete-lawyer', function () {
        const staffId = $(this).data('laywer-id');
        delete_laywer_record(staffId);
    });

    function delete_laywer_record(staffId) {
    if (confirm('Are you sure you want to delete the record?')) {
        $.ajax({
            url: '<?php echo admin_url("Cases/delete_laywer"); ?>',
            type: 'POST',
            data: { laywer_id: staffId },
            dataType: 'json', // Ensure response is parsed as JSON
            success: function (response) {
                if (response.success) {
                    alert_float('success', response.message);
                    location.reload(); // Reload the page to reflect changes
                } else {
                    alert_float('danger', response.message);
                }
            },
            error: function (xhr, status, error) {
                console.error('Error deleting lawyer:', xhr.responseText);
                alert_float('danger', 'An error occurred while deleting the lawyer. Please try again.');
            }
        });
    }
}


    
    // 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_laywer_firm'); ?>',
                data: formData,
                dataType: 'json',
                success: function (response) {
                    if (response.status === 'error') {
                        $('.invalid-feedback').text(response.message);
                    } else {
                        $('#myForm')[0].reset();
                        loadStates();
                        alert_float('success', 'Law Firm 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_laywer_firm'); ?>',
                data: formData,
                dataType: 'json',
                success: function (response) {
                    if (response.status === 'error') {
                        $('.invalid-feedback').text(response.message);
                    } else {
                        loadStates();
                        alert_float('success', 'Law Firm 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_laywer_firm'); ?>',
                dataType: 'json',
                success: function (response) {
                    $('#LaywerFirmList').empty();
                    $.each(response, function (index, state) {
                        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;">' + 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/laywer/laywer-firm/') ?>' + 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);
                        $('#LaywerFirmList').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_laywer_firm'); ?>',
                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>