<?php echo $__env->make('admin.layouts.header', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
<?php echo $__env->make('admin.layouts.sidebar', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
<?php
$account_type_list = ["Auto Loan","Housing Loan","Property Loan","LOAN AGAINST SHARES/SECURITIES","Personal Loan","Consumer Loan","Gold Loan","EDUCATIONAL LOAN","LOAN TO PROFESSIONAL","Credit Card","LEASING","OVERDRAFT","TWO-WHEELER LOAN","NON-FUNDED CREDIT FACILITY","LOAN AGAINST BANK DEPOSITS","FLEET CARD","Commercial Vehicle Loan","Telco – Wireless","Telco – Broadband","Telco – Landline","GECL Secured","GECL Unsecured","Secured Credit Card","Used Car Loan","Construction Equipment Loan","Tractor Loan","Corporate Credit Card","Kisan Credit Card","Loan on Credit Card","Prime Minister Jaan Dhan Yojana - Overdraft","Mudra Loans – Shishu / Kishor / Tarun","Microfinance – Business Loan","Microfinance – Personal Loan","Microfinance – Housing Loan","Microfinance – Others","Pradhan Mantri Awas Yojana - Credit Link Subsidy Scheme MAY CLSS","P2P Personal Loan","P2P Auto Loan","P2P Education Loan","BUSINESS LOAN – GENERAL","BUSINESS LOAN –PRIORITY SECTOR – SMALL BUSINESS","BUSINESS LOAN –PRIORITY SECTOR – AGRICULTURE","BUSINESS LOAN –PRIORITY SECTOR – OTHERS","BUSINESS NON-FUNDED CREDIT FACILITY – GENERAL","BUSINESS NON-FUNDED CREDIT FACILITY – PRIORITY SECTOR – SMALL BUSINESS","BUSINESS NON-FUNDED CREDIT FACILITY – PRIORITY SECTOR – AGRICULTURE","BUSINESS NON-FUNDED CREDIT FACILITY – PRIORITY SECTOR – OTHERS","BUSINESS LOANS AGAINST BANK DEPOSITS","Staff Loan","Business Loan - Unsecured","Others","Business Loan - Secured","Short Term Personal Loan [Unsecured]","Priority Sector Gold Loan [Secured]","Temporary Overdraft [Unsecured]"];
?>
<style>
    .panel-heading {
        background-color: #f1f1f1;
        border: 1px solid #e0dfe0;
        padding-left: 10px;
        padding-top: 6px;
        cursor: pointer;
    }
    .panel-default{
        padding-bottom: 4px;
    }
    .panel-collapse{
        background-color: #ffffff;
        padding: 10px;
        border: 1px solid #dedada;
    }
    .hidden-rule-row {
        display: none !important; /* Use !important to override inline styles if necessary */
    }
    /* Stacked modal fix: ensure PAC sub-modal appears above surrogate modal */
    #personalAccountCountModal {
        z-index: 1060;
    }
    #personalAccountCountModal + .modal-backdrop,
    .modal-backdrop.pac-backdrop {
        z-index: 1055;
    }
</style>

<div class="m-grid__item m-grid__item--fluid m-wrapper">
    <!-- BEGIN: Subheader -->
    <div class="m-subheader ">
        <div class="d-flex align-items-center">
            <div class="mr-auto">
                <h3 class="m-subheader__title m-subheader__title--separator">
                    Grade
                </h3>
                <?php if(\Illuminate\Support\Facades\Session::has('Document_List_Create|13-2-0')): ?>
                    <span class="btn btn-primary"><a href="/admin/auto-documentation/add" style="text-decoration: none;color: white;">Add Document List</a></span>
                <?php endif; ?>
            </div>

        </div>
    </div>
    <!-- END: Subheader -->
    <div class="m-content">
        <?php if(Session::has('success')): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close"></button>
                <?php echo e(Session::get('success')); ?>

            </div>
        <?php endif; ?>
        <?php if(Session::has('error')): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close"></button>
                <?php echo e(Session::get('error')); ?>

            </div>
        <?php endif; ?>

        <div class="m-portlet m-portlet--mobile">
            <div class="m-portlet__head">
                <div class="m-portlet__head-caption">
                    <div class="m-portlet__head-title">
                        <span class="m-portlet__head-icon">
                            <i class="fa fa-object-ungroup"></i>
                        </span>
                        <h3 class="m-portlet__head-text">
                            <?php echo isset($_GET['clone']) ? 'Duplicate ' : ''; ?>Grade
                        </h3>
                    </div>
                </div>
            </div>

            <div class="m-portlet__body">
                <div class="m-section">
                    <div class="m-section__content">
                        
                        <div class="form-group m-form__group row">
                            <label class="col-lg-3 col-form-label">
                                Grade Alias: <span style="color: red;">*</span>
                            </label>
                            <div class="col-lg-6">
                                <input type="text" class="form-control m-input" name="grade_alias" data-id="<?php echo isset($grade->id) ? $grade->id : ''; ?>" value="<?php echo isset($grade->grade_alias) ? $grade->grade_alias : ''; ?>" placeholder="Enter Grade Alias" required="">
                                <span class="field-hint" style="color: red; display: none; font-size: smaller;">Grade alias is mandatory.</span>
                            </div>
                        </div>

                        
                        <div class="panel-group">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <h4 class="panel-title">
                                        <a data-toggle="collapse" href="#collapse_approval_rule" style="font-size: 13px;color: #777171;">Approval Rule</a>
                                    </h4>
                                </div>

                                <div id="collapse_approval_rule" class="panel-collapse collapse">
                                    
                                    <div class="panel-body">
                                    <?php if(isset($grade)): ?>
                                        <?php $__currentLoopData = $grade->updateFields; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $label => $field): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <div class="panel-group">
                                                <div class="panel panel-default">
                                                    <div class="panel-heading collapsed" style="width: 100%; padding-bottom: 5px;" data-toggle="collapse" href="#collapse_<?php echo strtolower($label); ?>" aria-expanded="false">
                                                        <h4 class="panel-title" style="display: inline-block; margin-top: 5px;">
                                                            <a style="display: inline-block; color: #6d6666;font-size: 14px;"><?php echo isset($label) ? $label : ''; ?> <?php if($field['status'] == 0): ?> <span style="color: sandybrown;">[Inactive]</span> <?php endif; ?></a>
                                                        </h4>
                                                    </div>
                                                    <div id="collapse_<?php echo strtolower($label); ?>" class="panel-collapse collapse">
                                                        <div class="panel-body">
                                                            <form id="update_approval_grade_<?php echo isset($label) ? $label : ''; ?>" class="m-form m-form--fit m-form--label-align-right" method="POST" enctype="multipart/form-data">
                                                                <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>" />
                                                                <input type="hidden" name="original_rule_name" value="<?php echo $label; ?>" class="changed" />
                                                                <?php $counter = 1; $module_counter = 1;?>
                                                                <?php $status = isset($field['status']) ? $field['status'] : (is_array($field) ? 1 : $field); ?>
                                                                <?php if(isset($label) && $label != 'status'): ?>
                                                                    <?php $__currentLoopData = $field; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                                        <?php if(isset($value['label'])): ?>
                                                                            <?php if($value['type'] != 'module'): ?>
                                                                                <?php if($counter % 2 !== 0): ?>
                                                                                    <div class="form-group m-form__group row">
                                                                                <?php endif; ?>
                                                                                <label class="col-lg-3 col-form-label">
                                                                                    <?php echo isset($value['label']) ? $value['label'] : ''; ?>

                                                                                    <?php if(isset($value['title']) && $value['title'] != ''): ?>
                                                                                        <i class="fa fa-info-circle" data-toggle="tooltip" title="<?php echo isset($value['title']) ? $value['title'] : ''; ?>"></i>
                                                                                    <?php endif; ?>
                                                                                </label>
                                                                            <?php endif; ?>

                                                                            <?php if($value['type'] == 'select'): ?>
                                                                                <?php if($value['key'] == 'employee_status'): ?>
                                                                                    <?php $listEmployee = isset($value['value']) ? explode(',',$value['value']) : [];?>
                                                                                    <div class="col-lg-3" style="align-self: center;">
                                                                                        <select class="form-control m-input selectpicker" name="employee_status[]" id="employee_status" multiple data-selected-text-format="count > 3">
                                                                                            <option value=""> Select Employee Status </option>
                                                                                            <option value="UNEMPLOYED" <?php if(in_array('UNEMPLOYED', $listEmployee)): ?> selected="" <?php endif; ?>>UNEMPLOYED</option>
                                                                                            <option value="SALARIED" <?php if(in_array('SALARIED', $listEmployee)): ?> selected="" <?php endif; ?>>SALARIED</option>
                                                                                            <option value="BUSINESS" <?php if(in_array('BUSINESS', $listEmployee)): ?> selected="" <?php endif; ?>>BUSINESS</option>
                                                                                            <option value="Self Employed - Business" <?php if(in_array('Self Employed - Business', $listEmployee)): ?> selected="" <?php endif; ?>>Self Employed - Business</option>
                                                                                            <option value="Self Employed - Professional" <?php if(in_array('Self Employed - Professional', $listEmployee)): ?> selected="" <?php endif; ?>>Self Employed - Professional</option>
                                                                                            <option value="PENSIONER" <?php if(in_array('PENSIONER', $listEmployee)): ?> selected="" <?php endif; ?>>PENSIONER</option>
                                                                                            <option value="HOUSEWIFE" <?php if(in_array('HOUSEWIFE', $listEmployee)): ?> selected="" <?php endif; ?>>HOUSEWIFE</option>
                                                                                        </select>
                                                                                    </div>
                                                                                <?php elseif($value['key'] == 'solar_financing_for'): ?>
                                                                                    <?php $listSolarFinancingFor = isset($value['value']) ? explode(',',$value['value']) : [];?>
                                                                                    <div class="col-lg-3" style="align-self: center;">
                                                                                        <select class="form-control m-input selectpicker" name="solar_financing_for[]" id="solar_financing_for" multiple data-selected-text-format="count > 3">
                                                                                            <option value=""> Select Solar Financing For </option>
                                                                                            <option value="1" <?php if(in_array('1', $listSolarFinancingFor)): ?> selected="" <?php endif; ?>>Residential</option>
                                                                                            <option value="2" <?php if(in_array('2', $listSolarFinancingFor)): ?> selected="" <?php endif; ?>>Bharat MSME</option>
                                                                                            <option value="3" <?php if(in_array('3', $listSolarFinancingFor)): ?> selected="" <?php endif; ?>>Urban C&I (MSME)</option>
                                                                                            <option value="4" <?php if(in_array('4', $listSolarFinancingFor)): ?> selected="" <?php endif; ?>>Housing Society</option>
                                                                                        </select>
                                                                                    </div>
                                                                                <?php elseif($value['key'] == 'solar_power_type'): ?>
                                                                                    <?php $listSolarPowerType = isset($value['value']) ? explode(',',$value['value']) : [];?>
                                                                                    <div class="col-lg-3" style="align-self: center;">
                                                                                        <select class="form-control m-input selectpicker" name="solar_power_type[]" id="solar_power_type" multiple data-selected-text-format="count > 3">
                                                                                            <option value=""> Select Solar Power Type </option>
                                                                                            <option value="1" <?php if(in_array('1', $listSolarPowerType)): ?> selected="" <?php endif; ?>>On-Grid</option>
                                                                                            <option value="2" <?php if(in_array('2', $listSolarPowerType)): ?> selected="" <?php endif; ?>>Off-Grid</option>
                                                                                            <option value="3" <?php if(in_array('3', $listSolarPowerType)): ?> selected="" <?php endif; ?>>Hybrid</option>
                                                                                        </select>
                                                                                    </div>
                                                                                <?php endif; ?>
                                                                            <?php elseif($value['type'] == 'checkbox'): ?>
                                                                                <div class="col-lg-3" style="align-self: center;">
                                                                                    <input type="<?php echo $value['type']; ?>" class="form-control m-input <?php if(isset($value['value']) && $value['value'] != ''): ?> changed <?php endif; ?>" name="<?php echo isset($value['key']) ? $value['key'] : ''; ?>" <?php if(isset($value['value']) && $value['value'] != ''): ?> checked <?php endif; ?> value="on">
                                                                                </div>
                                                                            <?php elseif($value['type'] == 'popup'): ?>
                                                                                <?php if($value['label'] == 'Surrogate'): ?>
                                                                                    <div class="col-lg-3" style="align-self: center; display: flex; align-items: center; gap: 10px;">
                                                                                        <input type="checkbox" class="form-control m-input surrogate-checkbox_<?php echo isset($label) ? $label : ''; ?>" id="surrogate_checkbox_<?php echo isset($label) ? $label : ''; ?>" name="<?php echo isset($value['key']) ? $value['key'] : ''; ?>" <?php if(isset($value['value']) && isset($value['value']->status) && $value['value']->status == 1): ?> checked <?php endif; ?> value="on" style="width: auto; margin: 0;">
                                                                                        <input type="hidden" class="surrogate-data-input <?php if($value['value'] != ''): ?> changed <?php endif; ?>" id="surrogate_data_<?php echo isset($label) ? $label : ''; ?>" name="<?php echo isset($value['key']) ? $value['key'] : ''; ?>" value="<?php if(isset($value['value'])): ?> <?php echo htmlspecialchars(json_encode($value['value']), ENT_QUOTES, 'UTF-8'); ?> <?php else: ?> {"values":[],"status":0} <?php endif; ?>">
                                                                                        <button type="button" class="btn btn-primary surrogate-modal-btn" id="surrogate_btn_<?php echo isset($label) ? $label : ''; ?>" data-label="<?php echo $label; ?>" data-modal-type="surrogate" data-json-data='<?php if(isset($value['value'])): ?> <?php echo htmlspecialchars(json_encode($value['value']), ENT_QUOTES, 'UTF-8'); ?> <?php else: ?> {"values":[],"status":0} <?php endif; ?>' onclick="openModalFromButton(this)" <?php if(!isset($value['value']) || $value['value'] == '' || !isset($value['value']->status) || $value['value']->status == 0): ?> disabled <?php endif; ?>>
                                                                                            Open Surrogate Policy
                                                                                        </button>
                                                                                    </div>
                                                                                <?php elseif($value['label'] == 'Track Record'): ?>
                                                                                    <div class="col-lg-3" style="align-self: center; display: flex; align-items: center; gap: 10px;">
                                                                                        <input type="checkbox" class="form-control m-input track-record-checkbox_<?php echo isset($label) ? $label : ''; ?>" id="track_record_checkbox_<?php echo isset($label) ? $label : ''; ?>" name="<?php echo isset($value['key']) ? $value['key'] : ''; ?>" <?php if(isset($value['value']) && isset($value['value']->status) && $value['value']->status == 1): ?> checked <?php endif; ?> value="on" style="width: auto; margin: 0;">
                                                                                        <input type="hidden" class="track-record-data-input <?php if($value['value'] != ''): ?> changed <?php endif; ?>" id="track_record_data_<?php echo isset($label) ? $label : ''; ?>" name="<?php echo isset($value['key']) ? $value['key'] : ''; ?>" value="<?php if(isset($value['value'])): ?> <?php echo htmlspecialchars(json_encode($value['value']), ENT_QUOTES, 'UTF-8'); ?> <?php else: ?> {"ownership":"","years":0,"months":0,"percentage":0,"amount":0,"status":0} <?php endif; ?>">
                                                                                        <button type="button" class="btn btn-primary track-record-modal-btn" id="track_record_btn_<?php echo isset($label) ? $label : ''; ?>" data-label="<?php echo $label; ?>" data-modal-type="track-record" data-json-data='<?php if(isset($value['value'])): ?> <?php echo htmlspecialchars(json_encode($value['value']), ENT_QUOTES, 'UTF-8'); ?> <?php else: ?> {"ownership":"","years":0,"months":0,"percentage":0,"amount":0} <?php endif; ?>' onclick="openModalFromButton(this)" <?php if(!isset($value['value']) || $value['value'] == '' || !isset($value['value']->status) || $value['value']->status == 0): ?> disabled <?php endif; ?>>
                                                                                            Track Record
                                                                                        </button>
                                                                                    </div>
                                                                                <?php endif; ?>
                                                                            <?php elseif($value['type'] == 'range'): ?>
                                                                                <div class="col-lg-3" style="display: flex; align-items: center; gap: 10px;">
                                                                                    <input type="text" class="form-control m-input <?php if(isset($value['value'][0]) && $value['value'][0] != ''): ?> changed <?php endif; ?>" name="<?php echo isset($value['key']) ? $value['key'] : ''; ?>[0]" value="<?php echo isset($value['value'][0]) ? $value['value'][0] : ''; ?>" style="flex: 1;">
                                                                                    <span style="padding: 0 5px;">To</span>
                                                                                    <input type="text" class="form-control m-input <?php if(isset($value['value'][1]) && $value['value'][1] != ''): ?> changed <?php endif; ?>" name="<?php echo isset($value['key']) ? $value['key'] : ''; ?>[1]" value="<?php echo isset($value['value'][1]) ? $value['value'][1] : ''; ?>" style="flex: 1;">
                                                                                </div>
                                                                            <?php elseif($value['type'] == 'double_input'): ?>
                                                                                <div class="col-lg-3" >
                                                                                    
                                                                                    <div style="display: flex; align-items: center; margin-bottom: 6px;">
                                                                                        <span style="white-space: nowrap; margin-right: 10px; font-size: 13px; color: #1f2022ff;">
                                                                                            Max Bounces:
                                                                                        </span>
                                                                                        <input type="text" 
                                                                                            class="form-control m-input <?php if(isset($value['value']['max_emi_bounces'])): ?> changed <?php endif; ?>" 
                                                                                            name="<?php echo $value['key']; ?>[max_emi_bounces]" 
                                                                                            value="<?php echo $value['value']['max_emi_bounces'] ?? ''; ?>" 
                                                                                            placeholder="Count">
                                                                                    </div>

                                                                                    
                                                                                    <div style="display: flex; align-items: center;">
                                                                                        <span style="white-space: nowrap; margin-right: 10px; font-size: 13px; color: #1f2022ff;">
                                                                                            Lookback (M):
                                                                                        </span>
                                                                                        <input type="text" 
                                                                                            class="form-control m-input <?php if(isset($value['value']['emi_bounce_lookback_months'])): ?> changed <?php endif; ?>" 
                                                                                            name="<?php echo $value['key']; ?>[emi_bounce_lookback_months]" 
                                                                                            value="<?php echo $value['value']['emi_bounce_lookback_months'] ?? ''; ?>" 
                                                                                            placeholder="Months">
                                                                                    </div>
                                                                                </div>
                                                                            <?php elseif($value['type'] == 'module'): ?>
                                                                                
                                                                                <?php if($counter % 2 === 0): ?>
                                                                                    </div> 
                                                                                    <?php $counter++; ?> 
                                                                                <?php endif; ?>
                                                                                <?php if($module_counter % 2 !== 0): ?>
                                                                                    <div class="form-group m-form__group row">
                                                                                <?php endif; ?>
                                                                                
                                                                                <?php if($value['key'] == 'dpd_rules'): ?>
                                                                                    <?php
                                                                                    $dpdData = null;
                                                                                    $dpdStatus = 0;
                                                                                    $dpdOwnership = [];
                                                                                    $dpdExcludeAccountTypes = [];
                                                                                    $dpdRules = [];
                                                                                    
                                                                                    if (isset($value['value']) && !empty($value['value'])) {
                                                                                        if (is_string($value['value'])) {
                                                                                            $dpdData = json_decode($value['value'], true);
                                                                                        } else {
                                                                                            $dpdData = $value['value'];
                                                                                        }
                                                                                        if ($dpdData) {
                                                                                            $dpdStatus    = isset($dpdData->status) ? (int)$dpdData->status : 0;
                                                                                            $dpdOwnership = isset($dpdData->ownership) ? (array)$dpdData->ownership : [];
                                                                                            $dpdExcludeAccountTypes = isset($dpdData->account_types) ? (array)$dpdData->account_types : [];
                                                                                            $dpdRules     = isset($dpdData->rules) ? (array)$dpdData->rules : [];
                                                                                        }
                                                                                    }
                                                                                    
                                                                                    // If no rules exist, create a default one
                                                                                    if (empty($dpdRules)) {
                                                                                        $dpdRules = [['value' => '', 'months' => '', 'operator' => '', 'tradelines' => '']];
                                                                                    }
                                                                                    ?>
                                                                                    
                                                                                    <div class="col-md-6 dpd-section-card mb-4" data-role="collapsible-card" data-data-key="dpd" data-static-rules="1" data-dpd-data='<?php if($dpdData): ?> <?php echo htmlspecialchars(json_encode([['ownership' => $dpdOwnership, 'rules' => $dpdRules, 'status' => $dpdStatus]]), ENT_QUOTES, 'UTF-8'); ?> <?php endif; ?>'>
                                                                                        
                                                                                        <div class="panel-heading">
                                                                                            <h4 class="panel-title d-flex align-items-center justify-content-between">
                                                                                                <div class="d-flex align-items-center">
                                                                                                    <label for="dpdEnabled" class="mb-0">
                                                                                                        <a data-toggle="collapse" href="#dpdCollapseContent" style="font-size: 13px; color: #777171; text-decoration: none;">DPD</a>
                                                                                                    </label>
                                                                                                    <span data-toggle="tooltip" title="If any individual tradeline has Dpds based on following rules, then the result is "pass". Otherwise, the result is "fail". If the rule is "pass",  the case will be auto-rejected. Accounts used: Open account, Closed account." style="margin-left: 5px;">
                                                                                                    <i class="fa fa-info-circle" style="color: #9e9e9e; cursor: pointer;"></i>
                                                                                                </div>
                                                                                                <div class="form-check form-switch">
                                                                                                    <input class="form-check-input" type="checkbox" id="dpdEnabled" name="dpd_status" value="1" data-role="card-checkbox" <?php if($dpdStatus == 1): ?> checked <?php endif; ?>>
                                                                                                    <label class="form-check-label" for="dpdEnabled"></label>
                                                                                                </div>
                                                                                            </h4>
                                                                                        </div>
                                                                                        
                                                                                        <div class="collapse show" id="dpdCollapseContent" data-role="collapse-content" aria-labelledby="dpdHeader">
                                                                                            <div class="panel-body p-3">
                                                                                                
                                                                                                <div class="row mb-3">
                                                                                                    <label for="dpd_ownership" class="col-sm-2 col-form-label">Ownership</label>
                                                                                                    <div class="col-sm-4">
                                                                                                        <select id="dpd_ownership" name="dpd_ownership[]" class="form-control m-input selectpicker" multiple>
                                                                                                            <option value="individual" <?php if(in_array('individual', $dpdOwnership)): ?> selected <?php endif; ?>>Individual</option>
                                                                                                            <option value="guarantor" <?php if(in_array('guarantor', $dpdOwnership)): ?> selected <?php endif; ?>>Guarantor</option>
                                                                                                            <option value="joint" <?php if(in_array('joint', $dpdOwnership)): ?> selected <?php endif; ?>>Joint</option>
                                                                                                            <option value="Authorized User" <?php if(in_array('Authorized User', $dpdOwnership)): ?> selected <?php endif; ?>>Authorized User</option>
                                                                                                        </select>
                                                                                                    </div>
                                                                                                    <label for="dpd_ownership" class="col-sm-2 col-form-label">Exclude Account Types</label>
                                                                                                    <div class="col-sm-4">
                                                                                                        <select id="dpd_exclude_account_types" name="dpd_exclude_account_types[]" class="form-control m-input selectpicker" multiple>
                                                                                                            <?php $__currentLoopData = $account_type_list; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $account_type): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                                                                                <option value="<?php echo $account_type; ?>" <?php if(in_array($account_type, $dpdExcludeAccountTypes)): ?> selected <?php endif; ?>><?php echo $account_type; ?></option>
                                                                                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                                                                        </select>
                                                                                                    </div>
                                                                                                </div>
                                                                                                
                                                                                                <div data-role="rules-container" class="dpd-rules-container"
                                                                                                    data-name-prefix="dpd_rules"
                                                                                                    data-template-id="approval-dpd-rule-template"
                                                                                                    data-initial-count="<?php echo e(count($dpdRules) ?: 1); ?>">
                                                                                                    <?php if(!empty($dpdRules)): ?>
                                                                                                        <?php $__currentLoopData = $dpdRules; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $ruleIndex => $rule): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                                                                        <div class="dpd-rule-row d-flex align-items-center mb-3" data-role="rule-row" <?php if($ruleIndex == 0): ?> id="dpd-default-rule" <?php endif; ?>>
                                                                                                                <input type="text" name="dpd_rules[<?php echo e($ruleIndex); ?>][value]" value="<?php echo e(is_array($rule) ? ($rule['value'] ?? '') : ($rule->value ?? '')); ?>" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Days">
                                                                                                                <span style="margin-right: 10px">+ days in the last</span>
                                                                                                                <input type="text" name="dpd_rules[<?php echo e($ruleIndex); ?>][months]" value="<?php echo e(is_array($rule) ? ($rule['months'] ?? '') : ($rule->months ?? '')); ?>" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Months">
                                                                                                                <span style="margin-right: 10px">months</span>
                                                                                                                <?php
                                                                                                                    $dpdOp = is_array($rule) ? ($rule['operator'] ?? '') : ($rule->operator ?? '');
                                                                                                                ?>
                                                                                                                <select name="dpd_rules[<?php echo e($ruleIndex); ?>][operator]" class="form-select" style="width: 80px; margin-right: 10px">
                                                                                                                    <option value="&gt;" <?php if($dpdOp == '>'): ?> selected <?php endif; ?>>&gt;</option>
                                                                                                                    <option value="=" <?php if($dpdOp == '='): ?> selected <?php endif; ?>>=</option>
                                                                                                                    <option value="&lt;" <?php if($dpdOp == '<'): ?> selected <?php endif; ?>>&lt;</option>
                                                                                                                    <option value="&gt;=" <?php if($dpdOp == '>='): ?> selected <?php endif; ?>>&gt;=</option>
                                                                                                                    <option value="&lt;=" <?php if($dpdOp == '<='): ?> selected <?php endif; ?>>&lt;=</option>
                                                                                                                </select>
                                                                                                                <input type="text" name="dpd_rules[<?php echo e($ruleIndex); ?>][tradelines]" value="<?php echo e(is_array($rule) ? ($rule['tradelines'] ?? '1') : ($rule->tradelines ?? '1')); ?>" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Count">
                                                                                                                <span>Tradeline</span>
                                                                                                                <?php if($ruleIndex > 0): ?>
                                                                                                                    <button type="button" class="btn btn-danger btn-sm delete-rule" data-role="delete-button" style="margin-left: 10px;">
                                                                                                                        <i class="fa fa-trash"></i>
                                                                                                                    </button>
                                                                                                                <?php endif; ?>
                                                                                                            </div>
                                                                                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                                                                    <?php else: ?>
                                                                                                        
                                                                                                        <div class="dpd-rule-row d-flex align-items-center mb-3" data-role="rule-row" id="approval-dpd-default-rule">
                                                                                                            <input type="text" name="dpd_rules[0][value]" value="30" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Days">
                                                                                                            <span style="margin-right: 10px">+ days in the last</span>
                                                                                                            <input type="text" name="dpd_rules[0][months]" value="6" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Months">
                                                                                                            <span style="margin-right: 10px">months</span>
                                                                                                            <select name="dpd_rules[0][operator]" class="form-select" style="width: 80px; margin-right: 10px">
                                                                                                                <option value="&gt;" selected>&gt;</option>
                                                                                                                <option value="=">=</option>
                                                                                                                <option value="&lt;">&lt;</option>
                                                                                                                <option value="&gt;=">&gt;=</option>
                                                                                                                <option value="&lt;=">&lt;=</option>
                                                                                                            </select>
                                                                                                            <input type="text" name="dpd_rules[0][tradelines]" value="1" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Count">
                                                                                                            <span>Tradeline</span>
                                                                                                        </div>
                                                                                                    <?php endif; ?>
                                                                                                    
                                                                                                    <div data-role="rule-row" class="align-items-center d-none gap-2 mb-3" id="approval-dpd-rule-template"> 
                                                                                                        <input type="text" name="__PREFIX__[__INDEX__][value]" value="" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Days" disabled>
                                                                                                        <span style="margin-right: 10px">+ days in the last</span>
                                                                                                        <input type="text" name="__PREFIX__[__INDEX__][months]" value="" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Months" disabled>
                                                                                                        <span style="margin-right: 10px">months</span>
                                                                                                        <select name="__PREFIX__[__INDEX__][operator]" class="form-select" style="width: 80px; margin-right: 10px" disabled>
                                                                                                            <option value="&gt;" selected>&gt;</option>
                                                                                                            <option value="=">=</option>
                                                                                                            <option value="&lt;">&lt;</option>
                                                                                                            <option value="&gt;=">&gt;=</option>
                                                                                                            <option value="&lt;=">&lt;=</option>
                                                                                                        </select>
                                                                                                        <input type="text" name="__PREFIX__[__INDEX__][tradelines]" value="1" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Count" disabled>
                                                                                                        <span>Tradeline</span>
                                                                                                        <button type="button" class="btn btn-danger btn-sm delete-rule" data-role="delete-button" disabled>
                                                                                                            <i class="fa fa-trash"></i>
                                                                                                        </button>
                                                                                                    </div>
                                                                                                </div>
                                                                                                
                                                                                                <div class="mt-2">
                                                                                                    <button type="button" class="btn btn-primary btn-sm" data-role="add-button">+Add</button>
                                                                                                </div>
                                                                                            </div> 
                                                                                            </div> 
                                                                                        </div> 
                                                                                <?php elseif($value['key'] == 'keyword_rules'): ?>
                                                                                    <?php
                                                                                    $keywordData = null;
                                                                                    $keywordStatus = 0;
                                                                                    $keywordOwnership = [];
                                                                                    $keywordRules = [];
                                                                                    $keywordExcludeAccountTypes = [];

                                                                                    if (isset($value['value']) && !empty($value['value'])) {
                                                                                        if (is_string($value['value'])) {
                                                                                            $keywordData = json_decode($value['value'], true);
                                                                                        } else {
                                                                                            $keywordData = $value['value'];
                                                                                        }
                                                                                        if ($keywordData) {
                                                                                            // handle both array and object style
                                                                                            $statusSource = is_array($keywordData) ? ($keywordData['status'] ?? 0) : ($keywordData->status ?? 0);
                                                                                            $ownershipSource = is_array($keywordData) ? ($keywordData['ownership'] ?? []) : ($keywordData->ownership ?? []);
                                                                                            $rulesSource = is_array($keywordData) ? ($keywordData['rules'] ?? []) : ($keywordData->rules ?? []);

                                                                                            $keywordStatus = (int)$statusSource;
                                                                                            $keywordOwnership = $ownershipSource;
                                                                                            $keywordRules = $rulesSource;
                                                                                            $keywordExcludeAccountTypes = isset($keywordData->account_types) ? (array)$keywordData->account_types : [];
                                                                                        }
                                                                                    }

                                                                                    if (empty($keywordRules)) {
                                                                                        $keywordRules = [['value' => '', 'months' => '', 'operator' => '', 'tradelines' => '']];
                                                                                    }
                                                                                    ?>
                                                                                    
                                                                                    <div class="col-md-6 keyword-section-card mb-4" data-role="collapsible-card" data-data-key="KEYWORD" data-static-rules="1">
                                                                                        <div class="panel-heading">
                                                                                            <h4 class="panel-title d-flex align-items-center justify-content-between">
                                                                                                <div class="d-flex align-items-center">
                                                                                                    <label for="keywordEnabled" class="mb-0">
                                                                                                        <a data-toggle="collapse" href="#keywordCollapseContent" style="font-size: 13px; color: #777171; text-decoration: none;">Keyword</a>
                                                                                                    </label>
                                                                                                    <span data-toggle="tooltip" title="If any of the selected keywords in the applicant bureau are present in the BRE account status within selected months then pass, else fail.  If the rule is “pass”, the case should be auto- rejected. Accounts used: Open account, Closed account." style="margin-left: 5px;">
                                                                                                    <i class="fa fa-info-circle" style="color: #9e9e9e; cursor: pointer;"></i>
                                                                                                </div>
                                                                                                <div class="form-check form-switch">
                                                                                                    <input class="form-check-input" type="checkbox" id="keywordEnabled" name="keyword_status" value="1" data-role="card-checkbox" <?php if($keywordStatus == 1): ?> checked <?php endif; ?>>
                                                                                                    <label class="form-check-label" for="keywordEnabled"></label>
                                                                                                </div>
                                                                                            </h4>
                                                                                        </div>
                                                                                        
                                                                                        <div class="collapse show" id="keywordCollapseContent" data-role="collapse-content" aria-labelledby="keywordHeader">
                                                                                            <div class="panel-body p-3">
                                                                                                
                                                                                                <div class="row mb-3">
                                                                                                    <label for="keyword_ownership" class="col-sm-2 col-form-label">Ownership</label>
                                                                                                    <div class="col-sm-4">
                                                                                                        <select id="keyword_ownership" name="keyword_ownership[]" class="form-control m-input selectpicker" multiple>
                                                                                                            <option value="individual" <?php if(in_array('individual', $keywordOwnership ?? [])): ?> selected <?php endif; ?>>Individual</option>
                                                                                                            <option value="guarantor" <?php if(in_array('guarantor', $keywordOwnership ?? [])): ?> selected <?php endif; ?>>Guarantor</option>
                                                                                                            <option value="joint" <?php if(in_array('joint', $keywordOwnership ?? [])): ?> selected <?php endif; ?>>Joint</option>
                                                                                                            <option value="Authorized User" <?php if(in_array('Authorized User', $keywordOwnership ?? [])): ?> selected <?php endif; ?>>Authorized User</option>
                                                                                                        </select>
                                                                                                    </div>
                                                                                                    <label for="keyword_exclude_account_types" class="col-sm-2 col-form-label">Exclude Account Types</label>
                                                                                                    <div class="col-sm-4">
                                                                                                        <select id="keyword_exclude_account_types" name="keyword_exclude_account_types[]" class="form-control m-input selectpicker" multiple>
                                                                                                            <?php $__currentLoopData = $account_type_list; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $account_type): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                                                                                <option value="<?php echo $account_type; ?>" <?php if(in_array($account_type, $keywordExcludeAccountTypes)): ?> selected <?php endif; ?>><?php echo $account_type; ?></option>
                                                                                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                                                                        </select>
                                                                                                    </div>
                                                                                                </div>

                                                                                                
                                                                                                <div data-role="rules-container" class="keyword-rules-container"
                                                                                                    data-name-prefix="keyword_rules"
                                                                                                    data-template-id="approval-keyword-rule-template"
                                                                                                    data-initial-count="<?php echo e(count($keywordRules) ?: 1); ?>">
                                                                                                    <?php if(!empty($keywordRules)): ?>
                                                                                                        <?php $__currentLoopData = $keywordRules; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $ruleIndex => $rule): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                                                                            <div class="keyword-rule-row d-flex align-items-center mb-3" data-role="rule-row" <?php if($ruleIndex == 0): ?> id="keyword-default-rule" <?php endif; ?>>
                                                                                                                <input type="text" name="keyword_rules[<?php echo e($ruleIndex); ?>][value]" value="<?php echo e(is_array($rule) ? ($rule['value'] ?? '') : ($rule->value ?? '')); ?>" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Keywords">
                                                                                                                <span style="margin-right: 10px">in the last</span>
                                                                                                                <input type="text" name="keyword_rules[<?php echo e($ruleIndex); ?>][months]" value="<?php echo e(is_array($rule) ? ($rule['months'] ?? '') : ($rule->months ?? '')); ?>" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Months">
                                                                                                                <span style="margin-right: 10px">months</span>
                                                                                                                <?php
                                                                                                                    $op = is_array($rule) ? ($rule['operator'] ?? '') : ($rule->operator ?? '');
                                                                                                                ?>
                                                                                                                <select name="keyword_rules[<?php echo e($ruleIndex); ?>][operator]" class="form-select" style="width: 80px; margin-right: 10px">
                                                                                                                    <option value="&gt;" <?php if($op == '>'): ?> selected <?php endif; ?>>&gt;</option>
                                                                                                                    <option value="=" <?php if($op == '='): ?> selected <?php endif; ?>>=</option>
                                                                                                                    <option value="&lt;" <?php if($op == '<'): ?> selected <?php endif; ?>>&lt;</option>
                                                                                                                    <option value="&gt;=" <?php if($op == '>='): ?> selected <?php endif; ?>>&gt;=</option>
                                                                                                                    <option value="&lt;=" <?php if($op == '<='): ?> selected <?php endif; ?>>&lt;=</option>
                                                                                                                </select>
                                                                                                                <input type="text" name="keyword_rules[<?php echo e($ruleIndex); ?>][tradelines]" value="<?php echo e(is_array($rule) ? ($rule['tradelines'] ?? '1') : ($rule->tradelines ?? '1')); ?>" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Count">
                                                                                                                <span>Tradeline</span>
                                                                                                                <?php if($ruleIndex > 0): ?>
                                                                                                                    <button type="button" class="btn btn-danger btn-sm delete-rule" data-role="delete-button" style="margin-left: 10px;">
                                                                                                                        <i class="fa fa-trash"></i>
                                                                                                                    </button>
                                                                                                                <?php endif; ?>
                                                                                                            </div>
                                                                                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                                                                    <?php else: ?>
                                                                                                        
                                                                                                        <div class="keyword-rule-row d-flex align-items-center mb-3" data-role="rule-row" id="approval-keyword-default-rule">
                                                                                                            <input type="text" name="keyword_rules[0][value]" value="SMA" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Keywords">
                                                                                                            <span style="margin-right: 10px">in the last</span>
                                                                                                            <input type="text" name="keyword_rules[0][months]" value="6" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Months">
                                                                                                            <span style="margin-right: 10px">months</span>
                                                                                                            <select name="keyword_rules[0][operator]" class="form-select" style="width: 80px; margin-right: 10px">
                                                                                                                <option value="&gt;" selected>&gt;</option>
                                                                                                                <option value="=">=</option>
                                                                                                                <option value="&lt;">&lt;</option>
                                                                                                                <option value="&gt;=">&gt;=</option>
                                                                                                                <option value="&lt;=">&lt;=</option>
                                                                                                            </select>
                                                                                                            <input type="text" name="keyword_rules[0][tradelines]" value="1" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Count">
                                                                                                            <span>Tradeline</span>
                                                                                                        </div>
                                                                                                    <?php endif; ?>
                                                                                                    
                                                                                                    <div data-role="rule-row" class="align-items-center d-none gap-2 mb-3" id="approval-keyword-rule-template">
                                                                                                        <input type="text" name="__PREFIX__[__INDEX__][value]" value="" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Keywords" disabled>
                                                                                                        <span style="margin-right: 10px">in the last</span>
                                                                                                        <input type="text" name="__PREFIX__[__INDEX__][months]" value="" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Months" disabled>
                                                                                                        <span style="margin-right: 10px">months</span>
                                                                                                        <select name="__PREFIX__[__INDEX__][operator]" class="form-select" style="width: 80px; margin-right: 10px" disabled>
                                                                                                            <option value="&gt;" selected>&gt;</option>
                                                                                                            <option value="=">=</option>
                                                                                                            <option value="&lt;">&lt;</option>
                                                                                                            <option value="&gt;=">&gt;=</option>
                                                                                                            <option value="&lt;=">&lt;=</option>
                                                                                                        </select>
                                                                                                        <input type="text" name="__PREFIX__[__INDEX__][tradelines]" value="1" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Count" disabled>
                                                                                                        <span>Tradeline</span>
                                                                                                        <button type="button" class="btn btn-danger btn-sm delete-rule" data-role="delete-button" disabled>
                                                                                                            <i class="fa fa-trash"></i>
                                                                                                        </button>
                                                                                                    </div>
                                                                                                </div>
                                                                                                
                                                                                                <div class="mt-2">
                                                                                                    <button type="button" class="btn btn-primary btn-sm" data-role="add-button">+Add</button>
                                                                                                </div>
                                                                                            </div> 
                                                                                        </div> 
                                                                                    </div> 
                                                                                <?php elseif($value['key'] == 'past_dues_rules'): ?>
                                                                                    <?php
                                                                                    $pastDuesData = null;
                                                                                    $pastDueStatus = 0;
                                                                                    $pastDueOwnership = [];
                                                                                    $pastDueRules = [];

                                                                                    if (isset($value['value']) && !empty($value['value'])) {
                                                                                        if (is_string($value['value'])) {
                                                                                            $pastDuesData = json_decode($value['value'], true);
                                                                                        } else {
                                                                                            $pastDuesData = $value['value'];
                                                                                        }
                                                                                        if ($pastDuesData) {
                                                                                            // handle both array and object style
                                                                                            $statusSource = is_array($pastDuesData) ? ($pastDuesData['status'] ?? 0) : ($pastDuesData->status ?? 0);
                                                                                            $ownershipSource = is_array($pastDuesData) ? ($pastDuesData['ownership'] ?? []) : ($pastDuesData->ownership ?? []);
                                                                                            $rulesSource = is_array($pastDuesData) ? ($pastDuesData['rules'] ?? []) : ($pastDuesData->rules ?? []);

                                                                                            $pastDueStatus = (int)$statusSource;
                                                                                            $pastDueOwnership = $ownershipSource;
                                                                                            $pastDueRules = $rulesSource;
                                                                                        }
                                                                                    }

                                                                                    if (empty($pastDueRules)) {
                                                                                        $pastDueRules = [['value' => '', 'months' => '', 'account_type' => '']];
                                                                                    }
                                                                                    ?>
                                                                                    
                                                                                    <div class="col-md-6 past-dues-section-card mb-4" data-role="collapsible-card" data-data-key="PAST_DUES" data-static-rules="1">
                                                                                        
                                                                                        <div class="panel-heading">
                                                                                            <h4 class="panel-title d-flex align-items-center justify-content-between">
                                                                                                <div class="d-flex align-items-center">
                                                                                                    <label for="pastDuesEnabled" class="mb-0">
                                                                                                        <a data-toggle="collapse" href="#pastDuesCollapseContent" style="font-size: 13px; color: #777171; text-decoration: none;">Total Past Dues</a>
                                                                                                    </label>
                                                                                                    <span data-toggle="tooltip" title="If the Total past dues in the bureau are greater than the value set by the credit team, then 'pass', else fail. If the rule is “pass”, the case should be auto-rejected. Accounts used: Open account | Duration check: Reporting date." style="margin-left: 5px;">
                                                                                                    <i class="fa fa-info-circle" style="color: #9e9e9e; cursor: pointer;"></i>
                                                                                                </div>
                                                                                                <div class="form-check form-switch">
                                                                                                    <input class="form-check-input" type="checkbox" id="pastDuesEnabled" data-role="card-checkbox" name="past_dues_status" value="1" <?php if($pastDueStatus == 1): ?> checked <?php endif; ?>>
                                                                                                    <label class="form-check-label" for="pastDuesEnabled"></label>
                                                                                                </div>
                                                                                            </h4>
                                                                                        </div>
                                                                                        
                                                                                        <div class="collapse show" id="pastDuesCollapseContent" data-role="collapse-content" aria-labelledby="pastDuesHeader">
                                                                                            <div class="panel-body p-3">
                                                                                                
                                                                                                <div class="row mb-3">
                                                                                                    <label for="past_dues_ownership" class="col-sm-2 col-form-label">Ownership</label>
                                                                                                    <div class="col-sm-4">
                                                                                                        <select id="past_dues_ownership" name="past_dues_ownership[]" class="form-control m-input selectpicker" multiple>
                                                                                                            <option value="individual" <?php if(in_array('individual', $pastDueOwnership ?? [])): ?> selected <?php endif; ?>>Individual</option>
                                                                                                            <option value="guarantor" <?php if(in_array('guarantor', $pastDueOwnership ?? [])): ?> selected <?php endif; ?>>Guarantor</option>
                                                                                                            <option value="joint" <?php if(in_array('joint', $pastDueOwnership ?? [])): ?> selected <?php endif; ?>>Joint</option>
                                                                                                            <option value="Authorized User" <?php if(in_array('Authorized User', $pastDueOwnership ?? [])): ?> selected <?php endif; ?>>Authorized User</option>
                                                                                                        </select>
                                                                                                    </div>
                                                                                                </div>
                                                                                                
                                                                                                <div data-role="rules-container" class="past-dues-rules-container"
                                                                                                    id="past-dues-rules-container" 
                                                                                                    data-name-prefix="past_dues_rules"
                                                                                                    data-template-id="approval-past-dues-rule-template"
                                                                                                    data-initial-count="<?php echo e(count($pastDueRules ?? []) ?: 1); ?>">
                                                                                                    <?php if(!empty($pastDueRules)): ?>
                                                                                                        <?php $__currentLoopData = $pastDueRules; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $ruleIndex => $rule): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                                                                            <div class="past-dues-rule-row d-flex align-items-center mb-3" data-role="rule-row" <?php if($ruleIndex == 0): ?> id="approval-past-dues-default-rule" <?php endif; ?>>
                                                                                                                <input type="text" name="past_dues_rules[<?php echo e($ruleIndex); ?>][value]" value="<?php echo e(is_array($rule) ? ($rule['value'] ?? '') : ($rule->value ?? '')); ?>" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Amount">
                                                                                                                <span style="margin-right: 10px"> for</span>
                                                                                                                <input type="text" name="past_dues_rules[<?php echo e($ruleIndex); ?>][account_type]" value="<?php echo e(is_array($rule) ? ($rule['account_type'] ?? '') : ($rule->account_type ?? '')); ?>" class="form-control" style="width: 120px; margin-right: 10px" placeholder="Account Type">
                                                                                                                <span style="margin-right: 10px"> in the last</span>
                                                                                                                <input type="text" name="past_dues_rules[<?php echo e($ruleIndex); ?>][months]" value="<?php echo e(is_array($rule) ? ($rule['months'] ?? '') : ($rule->months ?? '')); ?>" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Months">
                                                                                                                <span style="margin-right: 10px">months</span>
                                                                                                                <?php if($ruleIndex > 0): ?>
                                                                                                                    <button type="button" class="btn btn-danger btn-sm delete-rule" data-role="delete-button" style="margin-left: 10px;">
                                                                                                                        <i class="fa fa-trash"></i>
                                                                                                                    </button>
                                                                                                                <?php endif; ?>
                                                                                                            </div>
                                                                                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                                                                    <?php else: ?>
                                                                                                        
                                                                                                        <div class="past-dues-rule-row d-flex align-items-center mb-3" data-role="rule-row"
                                                                                                            id="approval-past-dues-default-rule">
                                                                                                            <input type="text" name="past_dues_rules[0][value]" value="300" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Amount">
                                                                                                            <span style="margin-right: 10px"> for</span>
                                                                                                            <input type="text" name="past_dues_rules[0][account_type]" value="Credit Card" class="form-control" style="width: 120px; margin-right: 10px" placeholder="Account Type">
                                                                                                            <span style="margin-right: 10px"> in the last</span>
                                                                                                            <input type="text" name="past_dues_rules[0][months]" value="1" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Months">
                                                                                                            <span style="margin-right: 10px">months</span>
                                                                                                        </div>
                                                                                                    <?php endif; ?>
                                                                                                    
                                                                                                    <div data-role="rule-row" class="align-items-center d-none gap-2 mb-3" id="approval-past-dues-rule-template">
                                                                                                        <input type="text" name="__PREFIX__[__INDEX__][value]" value="" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Amount">
                                                                                                        <span style="margin-right: 10px">for</span>
                                                                                                        <input type="text" name="__PREFIX__[__INDEX__][account_type]" value="" class="form-control" style="width: 120px; margin-right: 10px" placeholder="Account Type">
                                                                                                        <span style="margin-right: 10px">in the last</span>
                                                                                                        <input type="text" name="__PREFIX__[__INDEX__][months]" value="" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Months">
                                                                                                        <span style="margin-right: 10px">months</span>
                                                                                                        <button type="button" class="btn btn-danger btn-sm delete-rule" data-role="delete-button">
                                                                                                            <i class="fa fa-trash"></i>
                                                                                                        </button>
                                                                                                    </div>
                                                                                                </div>
                                                                                                
                                                                                                <div class="mt-2">
                                                                                                    <button type="button" class="btn btn-primary btn-sm" data-role="add-button" id="approval-add-past-dues-rule">+Add</button>
                                                                                                </div>
                                                                                            </div> 
                                                                                        </div> 
                                                                                    </div> 
                                                                                <?php elseif($value['key'] == 'account_status_rules'): ?>
                                                                                    <?php
                                                                                    $accountStatusData = null;
                                                                                    $accountStatusStatus = 0;
                                                                                    $accountStatusOwnership = [];
                                                                                    $accountStatusRules = [];
                                                                                    
                                                                                    if (isset($value['value']) && !empty($value['value'])) {
                                                                                        if (is_string($value['value'])) {
                                                                                            $accountStatusData = json_decode($value['value'], true);
                                                                                        } else {
                                                                                            $accountStatusData = $value['value'];
                                                                                        }
                                                                                        if ($accountStatusData) {
                                                                                            // handle both array and object style
                                                                                            $statusSource = is_array($accountStatusData) ? ($accountStatusData['status'] ?? 0) : ($accountStatusData->status ?? 0);
                                                                                            $ownershipSource = is_array($accountStatusData) ? ($accountStatusData['ownership'] ?? []) : ($accountStatusData->ownership ?? []);
                                                                                            $rulesSource = is_array($accountStatusData) ? ($accountStatusData['rules'] ?? []) : ($accountStatusData->rules ?? []);

                                                                                            $accountStatusStatus = (int)$statusSource;
                                                                                            $accountStatusOwnership = $ownershipSource;
                                                                                            $accountStatusRules = $rulesSource;
                                                                                        }
                                                                                    }

                                                                                    if (empty($accountStatusRules)) {
                                                                                        $accountStatusRules = [['value' => '', 'months' => '']];
                                                                                    }
                                                                                    ?>
                                                                                    
                                                                                    <div class="col-md-6 account-status-section-card mb-4" data-role="collapsible-card" data-data-key="ACCOUNT_STATUS" data-static-rules="1">
                                                                                        
                                                                                        <div class="panel-heading">
                                                                                            <h4 class="panel-title d-flex align-items-center justify-content-between">
                                                                                                <div class="d-flex align-items-center">
                                                                                                    <label for="accountStatusEnabled" class="mb-0">
                                                                                                        <a data-toggle="collapse" href="#accountStatusCollapseContent" style="font-size: 13px; color: #777171; text-decoration: none;">Account Status</a>
                                                                                                    </label>
                                                                                                    <span data-toggle="tooltip" title="If any of the selected statuses in the applicant bureau are present in the BRE account status within selected months then pass, else fail.  If the rule is “pass”, the case should be auto- rejected. Accounts used - Open Account, Closed account| Duration check- Closed date, payment date, and Reporting date." style="margin-left: 5px;">
                                                                                                    <i class="fa fa-info-circle" style="color: #9e9e9e; cursor: pointer;"></i>
                                                                                                </div>    
                                                                                                <div class="form-check form-switch">
                                                                                                    <input class="form-check-input" type="checkbox" id="accountStatusEnabled" data-role="card-checkbox" name="account_status_status" value="1" <?php if($accountStatusStatus == 1): ?> checked <?php endif; ?>>
                                                                                                    <label class="form-check-label" for="accountStatusEnabled"></label>
                                                                                                </div>
                                                                                            </h4>
                                                                                        </div>
                                                                                        
                                                                                        <div class="collapse show" id="accountStatusCollapseContent" data-role="collapse-content" aria-labelledby="accountStatusHeader">
                                                                                            <div class="panel-body p-3">
                                                                                                
                                                                                                <div class="row mb-3">
                                                                                                    <label for="account_status_ownership" class="col-sm-2 col-form-label">Ownership</label>
                                                                                                    <div class="col-sm-4">
                                                                                                        <select id="account_status_ownership" name="account_status_ownership[]" class="form-control m-input selectpicker" multiple>
                                                                                                            <option value="individual" <?php if(in_array('individual', $accountStatusOwnership ?? [])): ?> selected <?php endif; ?>>Individual</option>
                                                                                                            <option value="guarantor" <?php if(in_array('guarantor', $accountStatusOwnership ?? [])): ?> selected <?php endif; ?>>Guarantor</option>
                                                                                                            <option value="joint" <?php if(in_array('joint', $accountStatusOwnership ?? [])): ?> selected <?php endif; ?>>Joint</option>
                                                                                                            <option value="Authorized User" <?php if(in_array('Authorized User', $accountStatusOwnership ?? [])): ?> selected <?php endif; ?>>Authorized User</option>
                                                                                                        </select>
                                                                                                    </div>
                                                                                                </div>
                                                                                                
                                                                                                <div data-role="rules-container" class="account-status-rules-container"
                                                                                                    id="account-status-rules-container" 
                                                                                                    data-name-prefix="account_status_rules"
                                                                                                    data-template-id="account-status-rule-template"
                                                                                                    data-initial-count="<?php echo e(count($accountStatusRules ?? []) ?: 1); ?>">
                                                                                                    <?php if(!empty($accountStatusRules)): ?>
                                                                                                        <?php $__currentLoopData = $accountStatusRules; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $ruleIndex => $rule): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                                                                            <div class="account-status-rule-row d-flex align-items-center mb-3" data-role="rule-row" <?php if($ruleIndex == 0): ?> id="account-status-default-rule" <?php endif; ?>>
                                                                                                                <input type="text" name="account_status_rules[<?php echo e($ruleIndex); ?>][values]" value="<?php echo e(is_array($rule) ? ($rule['values'] ?? '') : ($rule->values ?? '')); ?>" class="form-control" style="width: 100px; margin-right: 10px" placeholder="Account Status">
                                                                                                                <span style="margin-right: 10px"> in the last</span>
                                                                                                                <input type="text" name="account_status_rules[<?php echo e($ruleIndex); ?>][months]" value="<?php echo e(is_array($rule) ? ($rule['months'] ?? '') : ($rule->months ?? '')); ?>" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Months">
                                                                                                                <span style="margin-right: 10px">months</span>
                                                                                                                <?php if($ruleIndex > 0): ?>
                                                                                                                    <button type="button" class="btn btn-danger btn-sm delete-rule" data-role="delete-button" style="margin-left: 10px;">
                                                                                                                        <i class="fa fa-trash"></i>
                                                                                                                    </button>
                                                                                                                <?php endif; ?>
                                                                                                            </div>
                                                                                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                                                                    <?php else: ?>
                                                                                                        
                                                                                                        <div class="account-status-rule-row d-flex align-items-center mb-3" data-role="rule-row"
                                                                                                            id="account-status-default-rule"
                                                                                                            <input type="text" name="account_status_rules[0][values]" value="Suit Filed" class="form-control" style="width: 100px; margin-right: 10px" placeholder="Account Status">
                                                                                                            <span style="margin-right: 10px"> in the last</span>
                                                                                                            <input type="text" name="account_status_rules[0][months]" value="6" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Months">
                                                                                                            <span style="margin-right: 10px">months</span>
                                                                                                        </div>
                                                                                                    <?php endif; ?>
                                                                                                    
                                                                                                    <div data-role="rule-row" class="align-items-center d-none gap-2 mb-3" id="account-status-rule-template">
                                                                                                        <input type="text" name="__PREFIX__[__INDEX__][values]" value="" class="form-control" style="width: 140px; margin-right: 10px" placeholder="Account Status">
                                                                                                        <span style="margin-right: 10px">in the last</span>
                                                                                                        <input type="text" name="__PREFIX__[__INDEX__][months]" value="" class="form-control" style="width: 50px; margin-right: 10px" placeholder="Months">
                                                                                                        <span style="margin-right: 10px">months</span>
                                                                                                        <button type="button" class="btn btn-danger btn-sm delete-rule" data-role="delete-button">
                                                                                                            <i class="fa fa-trash"></i>
                                                                                                        </button>
                                                                                                    </div>
                                                                                                </div>
                                                                                                
                                                                                                <div class="mt-2">
                                                                                                    <button type="button" class="btn btn-primary btn-sm" data-role="add-button" id="approval-add-account-status-rule">+Add</button>
                                                                                                </div>
                                                                                            </div> 
                                                                                        </div> 
                                                                                    </div> 
                                                                                <?php elseif($value['key'] == 'principal_written_off_rules'): ?>
                                                                                    <?php
                                                                                    $principalWrittenOffData = null;
                                                                                    $principalWrittenOffStatus = 0;
                                                                                    $principalWrittenOffOwnership = [];
                                                                                    $principalWrittenOffRules = [];
                                                                                    
                                                                                    if (isset($value['value']) && !empty($value['value'])) {
                                                                                        if (is_string($value['value'])) {
                                                                                            $principalWrittenOffData = json_decode($value['value'], true);
                                                                                        } else {
                                                                                            $principalWrittenOffData = $value['value'];
                                                                                        }
                                                                                        if ($principalWrittenOffData) {
                                                                                            // handle both array and object style
                                                                                            $statusSource = is_array($principalWrittenOffData) ? ($principalWrittenOffData['status'] ?? 0) : ($principalWrittenOffData->status ?? 0);
                                                                                            $ownershipSource = is_array($principalWrittenOffData) ? ($principalWrittenOffData['ownership'] ?? []) : ($principalWrittenOffData->ownership ?? []);
                                                                                            $rulesSource = is_array($principalWrittenOffData) ? ($principalWrittenOffData['rules'] ?? []) : ($principalWrittenOffData->rules ?? []);

                                                                                            $principalWrittenOffStatus = (int)$statusSource;
                                                                                            $principalWrittenOffOwnership = $ownershipSource;
                                                                                            $principalWrittenOffRules = $rulesSource;
                                                                                        }
                                                                                    }

                                                                                    if (empty($principalWrittenOffRules)) {
                                                                                        $principalWrittenOffRules = [['value' => '', 'months' => '']];
                                                                                    }
                                                                                    ?>
                                                                                    
                                                                                    <div class="col-md-6 principal-written-off-section-card mb-4" data-role="collapsible-card" data-data-key="PRINCIPAL_WRITTEN_OFF_AMOUNT" data-static-rules="1">
                                                                                        
                                                                                        <div class="panel-heading">
                                                                                            <h4 class="panel-title d-flex align-items-center justify-content-between">
                                                                                                <div class="d-flex align-items-center">
                                                                                                    <label for="principalWrittenOffEnabled" class="mb-0">
                                                                                                        <a data-toggle="collapse" href="#principalWrittenOffCollapseContent" style="font-size: 13px; color: #777171; text-decoration: none;">Principal Written Off Amount</a>
                                                                                                    </label>
                                                                                                    <span data-toggle="tooltip" title="If the Principal Written-off amount in the bureau is greater than the value set by the credit team, then 'pass', else fail.  If the rule is “pass”, the case should be auto-rejected Accounts used - Open Account, Closed account | Duration check- Closed date, payment date, and Reporting date." style="margin-left: 5px;">
                                                                                                    <i class="fa fa-info-circle" style="color: #9e9e9e; cursor: pointer;"></i>
                                                                                                </div>
                                                                                                <div class="form-check form-switch">
                                                                                                    <input class="form-check-input" type="checkbox" id="principalWrittenOffEnabled" data-role="card-checkbox" name="principal_written_off_status" value="1" <?php if($principalWrittenOffStatus == 1): ?> checked <?php endif; ?>>
                                                                                                    <label class="form-check-label" for="principalWrittenOffEnabled"></label>
                                                                                                </div>
                                                                                            </h4>
                                                                                        </div>
                                                                                        
                                                                                        <div class="collapse show" id="principalWrittenOffCollapseContent" data-role="collapse-content" aria-labelledby="principalWrittenOffHeader">
                                                                                            <div class="panel-body p-3">
                                                                                                
                                                                                                <div class="row mb-3">
                                                                                                    <label for="principal_written_off_ownership" class="col-sm-2 col-form-label">Ownership</label>
                                                                                                    <div class="col-sm-4">
                                                                                                        <select id="principal_written_off_ownership" name="principal_written_off_ownership[]" class="form-control m-input selectpicker" multiple>
                                                                                                            <option value="individual" <?php if(in_array('individual', $principalWrittenOffOwnership ?? [])): ?> selected <?php endif; ?>>Individual</option>
                                                                                                            <option value="guarantor" <?php if(in_array('guarantor', $principalWrittenOffOwnership ?? [])): ?> selected <?php endif; ?>>Guarantor</option>
                                                                                                            <option value="joint" <?php if(in_array('joint', $principalWrittenOffOwnership ?? [])): ?> selected <?php endif; ?>>Joint</option>
                                                                                                            <option value="Authorized User" <?php if(in_array('Authorized User', $principalWrittenOffOwnership ?? [])): ?> selected <?php endif; ?>>Authorized User</option>
                                                                                                        </select>
                                                                                                    </div>
                                                                                                </div>
                                                                                                
                                                                                                <div data-role="rules-container" class="principal-written-off-rules-container"
                                                                                                    id="principal-written-off-rules-container"
                                                                                                    data-name-prefix="principal_written_off_rules"
                                                                                                    data-template-id="principal-written-off-rule-template"
                                                                                                    data-initial-count="<?php echo e(count($principalWrittenOffRules ?? []) ?: 1); ?>">
                                                                                                    <?php if(!empty($principalWrittenOffRules)): ?>
                                                                                                        <?php $__currentLoopData = $principalWrittenOffRules; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $ruleIndex => $rule): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                                                                            <div class="principal-written-off-rule-row d-flex align-items-center mb-3" data-role="rule-row" <?php if($ruleIndex == 0): ?> id="principal-written-off-default-rule" <?php endif; ?>>
                                                                                                                <input type="text" name="principal_written_off_rules[<?php echo e($ruleIndex); ?>][value]" value="<?php echo e(is_array($rule) ? ($rule['value'] ?? '') : ($rule->value ?? '')); ?>" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Amount">
                                                                                                                <span style="margin-right: 10px"> in the last</span>
                                                                                                                <input type="text" name="principal_written_off_rules[<?php echo e($ruleIndex); ?>][months]" value="<?php echo e(is_array($rule) ? ($rule['months'] ?? '') : ($rule->months ?? '')); ?>" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Months">
                                                                                                                <span style="margin-right: 10px">months</span>
                                                                                                                <?php if($ruleIndex > 0): ?>
                                                                                                                    <button type="button" class="btn btn-danger btn-sm delete-rule" data-role="delete-button" style="margin-left: 10px;">
                                                                                                                        <i class="fa fa-trash"></i>
                                                                                                                    </button>
                                                                                                                <?php endif; ?>
                                                                                                            </div>
                                                                                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                                                                    <?php else: ?>
                                                                                                        
                                                                                                        <div class="principal-written-off-rule-row d-flex align-items-center mb-3" data-role="rule-row"
                                                                                                            id="principal-written-off-default-rule"
                                                                                                            <input type="text" name="principal_written_off_rules[0][value]" value="300" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Amount">
                                                                                                            <span style="margin-right: 10px"> in the last</span>
                                                                                                            <input type="text" name="principal_written_off_rules[0][months]" value="1" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Months">
                                                                                                            <span style="margin-right: 10px">months</span>
                                                                                                        </div>
                                                                                                    <?php endif; ?>
                                                                                                    
                                                                                                    <div data-role="rule-row" class="align-items-center d-none gap-2 mb-3" id="principal-written-off-rule-template">
                                                                                                        <input type="text" name="__PREFIX__[__INDEX__][value]" value="" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Amount">
                                                                                                        <span style="margin-right: 10px">in the last</span>
                                                                                                        <input type="text" name="__PREFIX__[__INDEX__][months]" value="" class="form-control" style="width: 70px; margin-right: 10px" placeholder="Months">
                                                                                                        <span style="margin-right: 10px">months</span>
                                                                                                        <button type="button" class="btn btn-danger btn-sm delete-rule" data-role="delete-button">
                                                                                                            <i class="fa fa-trash"></i>
                                                                                                        </button>
                                                                                                    </div>
                                                                                                </div>
                                                                                                
                                                                                                <div class="mt-2">
                                                                                                    <button type="button" class="btn btn-primary btn-sm" data-role="add-button" id="add-principal-written-off-rule">+Add</button>
                                                                                                </div>
                                                                                            </div> 
                                                                                        </div> 
                                                                                    </div> 
                                                                                <?php endif; ?>
                                                                                <?php if($module_counter % 2 == 0): ?>
                                                                                    </div> 
                                                                                <?php endif; ?>
                                                                                <?php $module_counter++; ?>
                                                                            <?php else: ?>
                                                                                <div class="col-lg-3">
                                                                                    <input type="<?php echo $value['type']; ?>" class="form-control m-input <?php if(isset($value['value']) && $value['value'] != ''): ?> changed <?php endif; ?>" name="<?php echo isset($value['key']) ? $value['key'] : ''; ?>" value="<?php echo isset($value['value']) ? $value['value'] : ''; ?>">
                                                                                </div>
                                                                            <?php endif; ?>
                                                                            <?php if($value['type'] != 'module'): ?>
                                                                                <?php if($counter % 2 === 0): ?>
                                                                                    </div>
                                                                                <?php endif; ?>
                                                                                <?php $counter++; ?>
                                                                            <?php endif; ?>
                                                                        <?php endif; ?>
                                                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                                    <?php if(($counter - 1) % 2 !== 0): ?>
                                                                        </div>
                                                                    <?php endif; ?>
                                                                    <?php if(($module_counter - 1) % 2 !== 0): ?>
                                                                        </div>
                                                                    <?php endif; ?>
                                                                <?php endif; ?>
                                                                <hr style="margin-bottom: 1%"/>
                                                                <div class="form-group m-form__group row">
                                                                    <label class="col-lg-3 col-form-label">Status</label>
                                                                    <div class="col-lg-6">
                                                                        <select class="form-control" name="rule_status">
                                                                            <?php if(isset($status) && $status == 0): ?>
                                                                                <option value="1">Active</option>
                                                                                <option value="0" selected="selected">Inactive</option>
                                                                            <?php else: ?>
                                                                                <option value="1" selected="selected">Active</option>
                                                                                <option value="0">Inactive</option>
                                                                            <?php endif; ?>
                                                                        </select>
                                                                    </div>
                                                                </div>
                                                                <div class="m-portlet__foot m-portlet__foot--fit">
                                                                    <div class="m-form__actions m-form__actions">
                                                                        <button type="submit" class="btn btn-primary">Update</button>
                                                                    </div>
                                                                </div>
                                                            </form>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    <?php endif; ?>
                                    </div>

                                    
                                    <div class="panel-body">
                                        <form id="approval_grade" action="/admin/grade/save" class="m-form m-form--fit m-form--label-align-right" method="POST" enctype="multipart/form-data">
                                            <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>" />
                                            <div class="panel-group">
                                                <div class="panel panel-default">
                                                    <div class="panel-heading" data-toggle="collapse" href="#collapse">
                                                        <h4 class="panel-title">
                                                            <a style="color: #6d6666;font-size: 14px;">
                                                                <i class="fa fa-plus-circle"></i> Create New Approval Rule</a>
                                                        </h4>
                                                    </div>
                                                    <div id="collapse" class="panel-collapse collapse">
                                                        <?php echo $__env->make('admin.grade.grade_form', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
                                                        <div class="m-portlet__foot m-portlet__foot--fit" style="padding-left: 12px;">
                                                            <div class="m-form__actions m-form__actions">
                                                                <button type="reset" onclick="window.history.back()" class="btn btn-secondary">
                                                                    Cancel
                                                                </button>
                                                                <button type="submit" class="btn btn-primary">
                                                                    Save
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </div>

                            </div>
                        </div>

                        
                        <div class="panel-group">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <h4 class="panel-title">
                                        <a data-toggle="collapse" href="#collapse_document_rule" style="font-size: 13px;color: #777171;">Document Rule</a>
                                    </h4>
                                </div>
                                <div id="collapse_document_rule" class="panel-collapse collapse">
                                    <div class="panel-body">
                                        <?php if(isset($grade['docRules'])): ?>
                                            <?php $__currentLoopData = $grade['docRules']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index=>$docRule): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <form action="<?php if(isset($docRule->id)): ?> <?php echo asset('admin/auto-documentation/update/'.$docRule->id); ?> <?php else: ?> <?php echo asset('admin/auto-documentation/add'); ?> <?php endif; ?>" class="m-form m-form--fit m-form--label-align-right" method="POST" enctype="multipart/form-data">
                                                    <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>" />
                                                    <input type="hidden" name="grade_id" value="<?php echo $grade->id; ?>"/>
                                                    <div class="panel-group">
                                                        <div class="panel panel-default">
                                                            <div class="panel-heading" data-toggle="collapse" href="#collapse<?php echo $index; ?>">
                                                                <h4 class="panel-title">
                                                                    <a style="color: #6d6666;font-size: 14px;"><?php if(isset($docRule->id)): ?> <?php echo isset($docRule->alice) ? $docRule->alice : 'Score '. $docRule->score_from.' - '.$docRule->score_to.' / '.$docRule->employment_type; ?> <?php else: ?> <i class="fa fa-plus-circle"></i> Create New Document Rule <?php endif; ?></a>
                                                                </h4>
                                                            </div>
                                                            <div id="collapse<?php echo $index; ?>" class="panel-collapse collapse">
                                                                <div class="panel-body">
                                                                    <div class="row">
                                                                        <div class="col-md-6">
                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-3 col-form-label">
                                                                                    Choose Alise: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-9">
                                                                                    <input type="text" class="form-control m-input" name="alice" value="<?php echo Request::old('alice',isset($docRule->alice) ? $docRule->alice : ''); ?>" placeholder="Alice Name" required="">
                                                                                </div>
                                                                            </div>
                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-3 col-form-label">
                                                                                    Credit Score: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-4">
                                                                                    <input type="text" class="form-control m-input" name="score_from" value="<?php echo Request::old('score_from',isset($docRule->score_from) ? $docRule->score_from : ''); ?>" placeholder="Score From" required="">
                                                                                </div>
                                                                                <div class="col-lg-4">
                                                                                    <input type="text" class="form-control m-input" name="score_to" value="<?php echo Request::old('score_to',isset($docRule->score_to) ? $docRule->score_to : ''); ?>" placeholder="Score To" required="">
                                                                                </div>
                                                                            </div>

                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-3 col-form-label">
                                                                                    Negative Profile:
                                                                                </label>
                                                                                <div class="col-lg-6">
                                                                                    <input type="checkbox" class="form-control m-input" <?php if(isset($docRule->negative_profile) && $docRule->negative_profile == 1): ?> checked="checked" <?php endif; ?> name="negative_profile">
                                                                                </div>
                                                                            </div>

                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-3 col-form-label">
                                                                                    Negative Area:
                                                                                </label>
                                                                                <div class="col-lg-6">
                                                                                    <input type="checkbox" class="form-control m-input" <?php if(isset($docRule->negative_area) && $docRule->negative_area == 1): ?> checked="checked" <?php endif; ?> name="negative_area">
                                                                                </div>
                                                                            </div>

                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-3 col-form-label">
                                                                                    Collateral Loan:
                                                                                </label>
                                                                                <div class="col-lg-6">
                                                                                    <input type="checkbox" class="form-control m-input" <?php if(isset($docRule->collateral_loan) && $docRule->collateral_loan == 1): ?> checked="checked" <?php endif; ?> name="collateral_loan">
                                                                                </div>
                                                                            </div>


                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-3 col-form-label">
                                                                                    Choose Employment Type:: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-6">
                                                                                    <select class="form-control" name="employment_type" data-id="<?php echo $index; ?>" required="">
                                                                                        <option value="">Select Set</option>
                                                                                        <option <?php if(isset($docRule->employment_type) && $docRule->employment_type == 'Salaried'): ?> selected="selected" <?php endif; ?> value="Salaried">Salaried</option>
                                                                                        <option <?php if(isset($docRule->employment_type) && $docRule->employment_type == 'Self Employed'): ?> selected="selected" <?php endif; ?> value="Self Employed">Self Employed</option>
                                                                                    </select>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-md-6">
                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-3 col-form-label">
                                                                                    FOIR: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-4">
                                                                                    <input type="text" class="form-control m-input" name="foir_from" value="<?php echo Request::old('foir_from',isset($docRule->foir_from) ? $docRule->foir_from : ''); ?>" placeholder="FOIR From" required="">
                                                                                </div>
                                                                                <div class="col-lg-4">
                                                                                    <input type="text" class="form-control m-input" name="foir_to" value="<?php echo Request::old('foir_to',isset($docRule->foir_to) ? $docRule->foir_to : ''); ?>" placeholder="FOIR To" required="">
                                                                                </div>
                                                                            </div>

                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-3 col-form-label">
                                                                                    Loan Amount: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-4">
                                                                                    <input type="text" class="form-control m-input" name="loan_amount_from" value="<?php echo Request::old('loan_amount_from',isset($docRule->loan_amount_from) ? $docRule->loan_amount_from : ''); ?>" placeholder="Loan Amount From" required="">
                                                                                </div>
                                                                                <div class="col-lg-4">
                                                                                    <input type="text" class="form-control m-input" name="loan_amount_to" value="<?php echo Request::old('loan_amount_to',isset($docRule->loan_amount_to) ? $docRule->loan_amount_to : ''); ?>" placeholder="Loan Amount To" required="">
                                                                                </div>
                                                                            </div>


                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-3 col-form-label">
                                                                                    Income: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-4">
                                                                                    <input type="text" class="form-control m-input" name="income_from" value="<?php echo Request::old('income_from',isset($docRule->income_from) ? $docRule->income_from : ''); ?>" placeholder="Income From" required="">
                                                                                </div>
                                                                                <div class="col-lg-4">
                                                                                    <input type="text" class="form-control m-input" name="income_to" value="<?php echo Request::old('income_to',isset($docRule->income_to) ? $docRule->income_to : ''); ?>" placeholder="Income To" required="">
                                                                                </div>
                                                                            </div>
                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-3 col-form-label">
                                                                                    Net Disbursement: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-4">
                                                                                    <input type="text" class="form-control m-input" name="disbursement_from" value="<?php echo Request::old('disbursement_from',isset($docRule->disbursement_from) ? $docRule->disbursement_from : ''); ?>" placeholder="Disbursement From" required="">
                                                                                </div>
                                                                                <div class="col-lg-4">
                                                                                    <input type="text" class="form-control m-input" name="disbursement_to" value="<?php echo Request::old('disbursement_to',isset($docRule->disbursement_to) ? $docRule->disbursement_to : ''); ?>" placeholder="Disbursement To" required="">
                                                                                </div>
                                                                            </div>
                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-3 col-form-label">
                                                                                    Choose Document Set: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-6">
                                                                                    <select class="form-control document_set_view_<?php echo $index; ?>" name="document_set" required="">
                                                                                        <option value="">Select Set</option>
                                                                                        <?php if(isset($grade['documentLists'])): ?>
                                                                                            <?php $__currentLoopData = $grade['documentLists']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $list): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                                                                <?php if(isset($list->employment_type) && isset($docRule->employment_type) && $list->employment_type == str_replace(' ','_',strtolower($docRule->employment_type))): ?>
                                                                                                    <option <?php if(isset($docRule->document_set) && $docRule->document_set == $list->id): ?> selected="selected" <?php endif; ?> value="<?php echo $list->id; ?>"><?php echo $list->name; ?></option>
                                                                                                <?php endif; ?>
                                                                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                                                        <?php endif; ?>
                                                                                    </select>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                <?php if((\Illuminate\Support\Facades\Session::has('Grades_Update|13-0-2') && isset($docRule->id)) || (!isset($docRule->id) && \Illuminate\Support\Facades\Session::has('Grades_Create|13-0-1'))): ?>
                                                                    <div class="m-portlet__foot m-portlet__foot--fit">
                                                                        <div class="m-form__actions m-form__actions">
                                                                            <button type="submit" class="btn btn-primary">
                                                                                <?php if(isset($docRule->id)): ?>
                                                                                    Update
                                                                                <?php else: ?>
                                                                                    Save
                                                                                <?php endif; ?>
                                                                            </button>
                                                                            <button type="reset" onclick="window.history.back()" class="btn btn-secondary">
                                                                                Cancel
                                                                            </button>
                                                                        </div>
                                                                    </div>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </form>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                        
                        <div class="panel-group">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <h4 class="panel-title">
                                        <a data-toggle="collapse" href="#pre_approval_rule" style="font-size: 13px;color: #777171;">Pre-Approval Rule</a>
                                    </h4>
                                </div>
                                <div id="pre_approval_rule" class="panel-collapse collapse">
                                    <div class="panel-body">
                                        <?php if(isset($grade['preApproval'])): ?>
                                            <?php $__currentLoopData = $grade['preApproval']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index=>$preApproval): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <form action="<?php if(isset($preApproval->id)): ?> <?php echo asset('admin/auto-pre-approval/update/'.$preApproval->id); ?> <?php else: ?> <?php echo asset('admin/auto-pre-approval/add'); ?> <?php endif; ?>" class="m-form m-form--fit m-form--label-align-right" method="POST" enctype="multipart/form-data">
                                                    <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>" />
                                                    <input type="hidden" name="grade_id" value="<?php echo $grade->id; ?>"/>
                                                    <div class="panel-group">
                                                        <div class="panel panel-default">
                                                            <div class="panel-heading" data-toggle="collapse" href="#collapse_pre<?php echo $index; ?>">
                                                                <h4 class="panel-title">
                                                                    <a style="color: #6d6666;font-size: 14px;"><?php if(isset($preApproval->id)): ?> <?php if(!$preApproval->thin_file): ?> <?php echo 'Score '. $preApproval->score.' / '.$preApproval->employment_type; ?> <?php else: ?> <?php echo 'Thin File / '.$preApproval->employment_type; ?> <?php endif; ?> <?php else: ?> <i class="fa fa-plus-circle"></i> Create New Pre-Approval Rule <?php endif; ?></a>
                                                                </h4>
                                                            </div>
                                                            <div id="collapse_pre<?php echo $index; ?>" class="panel-collapse collapse">
                                                                <div class="panel-body">
                                                                    <div class="row">
                                                                        <div class="col-md-6">
                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-4 col-form-label">
                                                                                    Thin File:
                                                                                </label>
                                                                                <div class="col-lg-8" style="padding-top: 10px;">
                                                                                    <input type="checkbox" class="form-control m-input" name="thin_file" <?php echo isset($preApproval->thin_file) && $preApproval->thin_file == 1 ? 'checked="checked"' : ''; ?>>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-md-6">
                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-4 col-form-label">
                                                                                    Choose Employment Type: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-8">
                                                                                    <?php $employment_type = isset($preApproval->employment_type) ? explode(',',$preApproval->employment_type) : [];  ?>
                                                                                    <select class="form-control selectpicker" multiple name="employment_type[]" required="">
                                                                                        <option value="">Select Type</option>
                                                                                        <option <?php if(isset($preApproval->employment_type) && in_array('UNEMPLOYED',$employment_type)): ?> selected="selected" <?php endif; ?> value="UNEMPLOYED">UNEMPLOYED</option>
                                                                                        <option <?php if(isset($preApproval->employment_type) && in_array('Salaried',$employment_type)): ?> selected="selected" <?php endif; ?> value="Salaried">Salaried</option>
                                                                                        <option <?php if(isset($preApproval->employment_type) && in_array('BUSINESS',$employment_type)): ?> selected="selected" <?php endif; ?> value="BUSINESS">BUSINESS</option>
                                                                                        <option <?php if(isset($preApproval->employment_type) && in_array('Self Employed - Business',$employment_type)): ?> selected="selected" <?php endif; ?> value="Self Employed - Business">Self Employed - Business</option>
                                                                                        <option <?php if(isset($preApproval->employment_type) && in_array('Self Employed - Professional',$employment_type)): ?> selected="selected" <?php endif; ?> value="Self Employed - Professional">Self Employed - Professional</option>
                                                                                    </select>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-md-6">
                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-4 col-form-label">
                                                                                    Min Loan Amount: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-8">
                                                                                    <input type="text" class="form-control m-input" name="min_loan_amount" value="<?php echo Request::old('min_loan_amount',isset($preApproval->min_loan_amount) ? $preApproval->min_loan_amount : ''); ?>" placeholder="Min Loan Amount" required="">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-md-6">
                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-4 col-form-label">
                                                                                    Max Loan Amount: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-8">
                                                                                    <input type="text" class="form-control m-input" name="loan_amount" value="<?php echo Request::old('loan_amount',isset($preApproval->loan_amount) ? $preApproval->loan_amount : ''); ?>" placeholder="Max Loan Amount" required="">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-md-6">
                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-4 col-form-label">
                                                                                    Net Tenure: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-8">
                                                                                    <input type="text" class="form-control m-input" name="net_tenure" value="<?php echo Request::old('net_tenure',isset($preApproval->net_tenure) ? $preApproval->net_tenure : ''); ?>" placeholder="Net Tenure" required="">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-md-6">
                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-4 col-form-label">
                                                                                    Score: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-8">
                                                                                    <input type="text" class="form-control m-input" name="score" value="<?php echo Request::old('score',isset($preApproval->score) ? $preApproval->score : ''); ?>" placeholder="Score" required="">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-md-6">
                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-4 col-form-label">
                                                                                    Past Dues: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-8">
                                                                                    <input type="text" class="form-control m-input" name="past_dues" value="<?php echo Request::old('past_dues',isset($preApproval->past_dues) ? $preApproval->past_dues : ''); ?>" placeholder="Past Dues" required="">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-md-6">
                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-4 col-form-label">
                                                                                    FOIR: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-8">
                                                                                    <input type="text" class="form-control m-input" name="foir" value="<?php echo Request::old('foir',isset($preApproval->foir) ? $preApproval->foir : ''); ?>" placeholder="FOIR" required="">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-md-6">
                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-4 col-form-label">
                                                                                    CF FOIR: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-8">
                                                                                    <input type="text" class="form-control m-input" name="cf_foir" value="<?php echo Request::old('cf_foir',isset($preApproval->cf_foir) ? $preApproval->cf_foir : ''); ?>" placeholder="CF FOIR" required="">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-md-6">
                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-4 col-form-label">
                                                                                    Monthly Income: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-8">
                                                                                    <input type="text" class="form-control m-input" name="monthly_income" value="<?php echo Request::old('monthly_income',isset($preApproval->monthly_income) ? $preApproval->monthly_income : ''); ?>" placeholder="Monthly Income" required="">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-md-6">
                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-4 col-form-label">
                                                                                    Minimum Age: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-8">
                                                                                    <input type="text" class="form-control m-input" name="min_age" value="<?php echo Request::old('min_age',isset($preApproval->min_age) ? $preApproval->min_age : ''); ?>" placeholder="Minimum Age" required="">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-md-6">
                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-4 col-form-label">
                                                                                    Maximum Age: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-8">
                                                                                    <input type="text" class="form-control m-input" name="max_age" value="<?php echo Request::old('max_age',isset($preApproval->max_age) ? $preApproval->max_age : ''); ?>" placeholder="Maximum Age" required="">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-md-6">
                                                                            <div class="form-group m-form__group row">
                                                                                <label class="col-lg-4 col-form-label">
                                                                                    Residence Status: <span style="color: red;">*</span>
                                                                                </label>
                                                                                <div class="col-lg-8">
                                                                                    <?php $residence_status = isset($preApproval->residence_status) ? explode(',',$preApproval->residence_status) : [];  ?>
                                                                                    <select class="form-control selectpicker" multiple name="residence_status[]" data-id="<?php echo $index; ?>" required="">
                                                                                        <option value="RENTED" <?php if(isset($preApproval->residence_status) && in_array('RENTED',$residence_status)): ?> selected="selected" <?php endif; ?>>RENTED</option>
                                                                                        <option value="OWNED" <?php if(isset($preApproval->residence_status) && in_array('OWNED',$residence_status)): ?> selected="selected" <?php endif; ?>>OWNED</option>
                                                                                        <option value="PARENTS HOUSE" <?php if(isset($preApproval->residence_status) && in_array('PARENTS HOUSE',$residence_status)): ?> selected="selected" <?php endif; ?>>PARENTS HOUSE</option>
                                                                                        <option value="Self Owned" <?php if(isset($preApproval->residence_status) && in_array('Self Owned',$residence_status)): ?> selected="selected" <?php endif; ?>>Self Owned</option>
                                                                                        <option value="Parent Owned" <?php if(isset($preApproval->residence_status) && in_array('Parent Owned',$residence_status)): ?> selected="selected" <?php endif; ?>>Parent Owned</option>
                                                                                        <option value="Rented With Family" <?php if(isset($preApproval->residence_status) && in_array('Rented With Family',$residence_status)): ?> selected="selected" <?php endif; ?>>Rented With Family</option>
                                                                                        <option value="Rented With Friend" <?php if(isset($preApproval->residence_status) && in_array('Rented With Friend',$residence_status)): ?> selected="selected" <?php endif; ?>>Rented With Friend</option>
                                                                                        <option value="Company Allotted" <?php if(isset($preApproval->residence_status) && in_array('Company Allotted',$residence_status)): ?> selected="selected" <?php endif; ?>>Company Allotted</option>
                                                                                    </select>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <?php if((\Illuminate\Support\Facades\Session::has('Grades_Update|13-0-2') && isset($preApproval->id)) || (!isset($preApproval->id) && \Illuminate\Support\Facades\Session::has('Grades_Create|13-0-1'))): ?>
                                                                            <div class="m-portlet__foot m-portlet__foot--fit" style="padding-left: 12px;">
                                                                                <div class="m-form__actions m-form__actions">
                                                                                    <button type="submit" class="btn btn-primary">
                                                                                        <?php if(isset($preApproval->id)): ?>
                                                                                            Update
                                                                                        <?php else: ?>
                                                                                            Save
                                                                                        <?php endif; ?>
                                                                                    </button>
                                                                                    <button type="reset" onclick="window.history.back()" class="btn btn-secondary">
                                                                                        Cancel
                                                                                    </button>
                                                                                </div>
                                                                            </div>
                                                                        <?php endif; ?>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </form>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                        
                        <div class="panel-group">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <h4 class="panel-title">
                                        <a data-toggle="collapse" href="#auto_reject_rule" style="font-size: 13px;color: #777171;">Auto Reject Rule</a>
                                    </h4>
                                </div>
                                <div id="auto_reject_rule" class="panel-collapse collapse">
                                    <div class="panel-body">
                                        <div class="panel-group">
                                            <div class="panel panel-default">
                                                <div class="panel-heading">
                                                    <h4 class="panel-title">
                                                        <a data-toggle="collapse" href="#c_auto_reject_rule" style="font-size: 13px;color: #777171;">Auto Reject Consumer App</a>
                                                    </h4>
                                                </div>
                                                <div id="c_auto_reject_rule" class="panel-collapse collapse">
                                                    <div class="panel-body">
                                                        <?php if(isset($grade->id)): ?>
                                                            <form action="<?php if(isset($grade['auto_reject']['consumer']->id)): ?> <?php echo asset('admin/auto-reject/update/'.$grade['auto_reject']['consumer']->id); ?> <?php else: ?> <?php echo asset('admin/auto-reject/add'); ?> <?php endif; ?>" class="m-form m-form--fit m-form--label-align-right" method="POST" enctype="multipart/form-data">
                                                                <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>" />
                                                                <input type="hidden" name="grade_id" value="<?php echo $grade->id; ?>"/>
                                                                <input type="hidden" name="for_consumer" value="1"/>
                                                                <div class="row">
                                                                    <div style="padding-left: 16px;">
                                                                        <code>If one of them condition failed than it will reject the application. There is <b>OR</b> condition between the each attributes.</code>
                                                                    </div>
                                                                    <div class="col-md-6">
                                                                        <div class="form-group m-form__group row">
                                                                            <label class="col-lg-4 col-form-label">
                                                                                Min Score (eg. <code>>= -1</code> )
                                                                            </label>
                                                                            <div class="col-lg-8" style="padding-top: 10px;">
                                                                                <input type="text" class="form-control m-input" placeholder="Score" name="min_score" value="<?php echo isset($grade['auto_reject']['consumer']->min_score) ? $grade['auto_reject']['consumer']->min_score : ''; ?>" required="required"/>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-md-6">
                                                                        <div class="form-group m-form__group row">
                                                                            <label class="col-lg-4 col-form-label">
                                                                                Max Score (eg. <code><= 625</code> )
                                                                            </label>
                                                                            <div class="col-lg-8" style="padding-top: 10px;">
                                                                                <input type="text" class="form-control m-input" placeholder="Score" name="max_score" value="<?php echo isset($grade['auto_reject']['consumer']->max_score) ? $grade['auto_reject']['consumer']->max_score : ''; ?>" required="required"/>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-md-6">
                                                                        <div class="form-group m-form__group row">
                                                                            <label class="col-lg-4 col-form-label">
                                                                                Total Past Dues
                                                                            </label>
                                                                            <div class="col-lg-8" style="padding-top: 10px;">
                                                                                <input type="text" class="form-control m-input" placeholder="Total Past Dues" name="past_dues" value="<?php echo isset($grade['auto_reject']['consumer']->past_dues) ? $grade['auto_reject']['consumer']->past_dues : ''; ?>" required="required"/>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-md-6">
                                                                        <div class="form-group m-form__group row">
                                                                            <label class="col-lg-4 col-form-label">
                                                                                Max DPD
                                                                            </label>
                                                                            <div class="col-lg-8" style="padding-top: 10px;">
                                                                                <input type="text" class="form-control m-input" placeholder="Max DPD" name="max_dpd" value="<?php echo isset($grade['auto_reject']['consumer']->max_dpd) ? $grade['auto_reject']['consumer']->max_dpd : ''; ?>" required="required"/>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-md-6">
                                                                        <div class="form-group m-form__group row">
                                                                            <label class="col-lg-4 col-form-label">
                                                                                Age
                                                                            </label>
                                                                            <div class="col-lg-8" style="padding-top: 10px;">
                                                                                <input type="text" class="form-control m-input" placeholder="Age" name="age" value="<?php echo isset($grade['auto_reject']['consumer']->age) ? $grade['auto_reject']['consumer']->age : ''; ?>" required="required"/>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-md-6">
                                                                        <div class="form-group m-form__group row">
                                                                            <label class="col-lg-4 col-form-label">
                                                                                Monthly Income
                                                                            </label>
                                                                            <div class="col-lg-8" style="padding-top: 10px;">
                                                                                <input type="text" class="form-control m-input" placeholder="Monthly Income" name="monthly_income" value="<?php echo isset($grade['auto_reject']['consumer']->monthly_income) ? $grade['auto_reject']['consumer']->monthly_income : ''; ?>" required="required"/>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-md-6">
                                                                        <div class="form-group m-form__group row">
                                                                            <label class="col-lg-4 col-form-label">
                                                                                FOIR (%)
                                                                            </label>
                                                                            <div class="col-lg-8" style="padding-top: 10px;">
                                                                                <input type="text" class="form-control m-input" placeholder="FOIR (Including CF EMI)" name="foir" value="<?php echo isset($grade['auto_reject']['consumer']->foir) ? $grade['auto_reject']['consumer']->foir : ''; ?>" required="required"/>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-md-6">
                                                                        <div class="form-group m-form__group row">
                                                                            <label class="col-lg-4 col-form-label">
                                                                                Negative Area
                                                                            </label>
                                                                            <div class="col-lg-8" style="padding-top: 10px;">
                                                                                <input type="checkbox" class="form-control m-input" name="negative_area" <?php if(isset($grade['auto_reject']['consumer']->negative_area) && $grade['auto_reject']['consumer']->negative_area == 1): ?> checked="checked" <?php endif; ?> />
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-md-6">
                                                                        <div class="form-group m-form__group row">
                                                                            <label class="col-lg-4 col-form-label">
                                                                                Pincode Should Be Approved
                                                                            </label>
                                                                            <div class="col-lg-8" style="padding-top: 10px;">
                                                                                <input type="checkbox" class="form-control m-input" name="approved_pincode" <?php if(isset($grade['auto_reject']['consumer']->approved_pincode) && $grade['auto_reject']['consumer']->approved_pincode == 1): ?> checked="checked" <?php endif; ?> />
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <?php if((\Illuminate\Support\Facades\Session::has('Grades_Update|13-0-2') && isset($grade['auto_reject']['consumer']->id)) || (!isset($grade['auto_reject']['consumer']->id) && \Illuminate\Support\Facades\Session::has('Grades_Create|13-0-1'))): ?>
                                                                        <div class="m-portlet__foot m-portlet__foot--fit" style="padding-left: 12px;">
                                                                            <div class="m-form__actions m-form__actions">
                                                                                <button type="submit" class="btn btn-primary">
                                                                                    <?php if(isset($grade['auto_reject']['consumer']->id)): ?>
                                                                                        Update
                                                                                    <?php else: ?>
                                                                                        Save
                                                                                    <?php endif; ?>
                                                                                </button>
                                                                                <button type="reset" onclick="window.history.back()" class="btn btn-secondary">
                                                                                    Cancel
                                                                                </button>
                                                                            </div>
                                                                        </div>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </form>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="panel-group">
                                            <div class="panel panel-default">
                                                <div class="panel-heading">
                                                    <h4 class="panel-title">
                                                        <a data-toggle="collapse" href="#ec_auto_reject_rule" style="font-size: 13px;color: #777171;">Auto Reject Except Consumer App</a>
                                                    </h4>
                                                </div>
                                                <div id="ec_auto_reject_rule" class="panel-collapse collapse">
                                                    <div class="panel-body">
                                                        <?php if(isset($grade->id)): ?>
                                                            <form action="<?php if(isset($grade['auto_reject']['ex_consumer']->id)): ?> <?php echo asset('admin/auto-reject/update/'.$grade['auto_reject']['ex_consumer']->id); ?> <?php else: ?> <?php echo asset('admin/auto-reject/add'); ?> <?php endif; ?>" class="m-form m-form--fit m-form--label-align-right" method="POST" enctype="multipart/form-data">
                                                                <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>" />
                                                                <input type="hidden" name="grade_id" value="<?php echo $grade->id; ?>"/>
                                                                <input type="hidden" name="for_consumer" value="0"/>
                                                                <div class="row">
                                                                    <div class="col-12 mb-3">
                                                                        <ul class="nav nav-tabs" role="tablist" style="margin-bottom: 20px; border-bottom: 1px solid #ebedf2;">
                                                                            <li class="nav-item">
                                                                                <a class="nav-link active" data-toggle="tab" href="#applicant_tab" style="font-weight: 500;">Applicant</a>
                                                                            </li>
                                                                            <li class="nav-item">
                                                                                <a class="nav-link" data-toggle="tab" href="#co_applicant_income_tab" style="font-weight: 500;">Co-applicant for Income</a>
                                                                            </li>
                                                                            <li class="nav-item">
                                                                                <a class="nav-link" data-toggle="tab" href="#co_applicant_signing_tab" style="font-weight: 500;">Co-applicant for Signing</a>
                                                                            </li>
                                                                        </ul>
                                                                    </div>
                                                                    <div class="tab-content col-12">
                                                                        
                                                                        <div id="applicant_tab" class="tab-pane active">
                                                                            <div style="padding-bottom: 15px;">
                                                                                <code>If one of the conditions is passed for the Applicant, then it will reject the application.</code>
                                                                            </div>
                                                                            <div class="row">
                                                                                <?php echo $__env->make('admin.grade.partials.auto_reject_fields', ['prefix' => 'applicant', 'type' => 'applicant'], array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
                                                                            </div>
                                                                        </div>
                                                                        
                                                                        <div id="co_applicant_income_tab" class="tab-pane">
                                                                            <div style="padding-bottom: 15px;">
                                                                                <code>If one of the conditions is passed for the Co-applicant for Income, then it will reject the application.</code>
                                                                            </div>
                                                                            <div class="row">
                                                                                <?php echo $__env->make('admin.grade.partials.auto_reject_fields', ['prefix' => 'co_applicant_for_income', 'type' => 'co_applicant_income'], array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
                                                                            </div>
                                                                        </div>
                                                                        
                                                                        <div id="co_applicant_signing_tab" class="tab-pane">
                                                                            <div style="padding-bottom: 15px;">
                                                                                <code>If one of the conditions is passed for the Co-applicant for Signing, then it will reject the application.</code>
                                                                            </div>
                                                                            <div class="row">
                                                                                <?php echo $__env->make('admin.grade.partials.auto_reject_fields', ['prefix' => 'co_applicant_for_signing', 'type' => 'co_applicant_signing'], array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
                                                                            </div>
                                                                        </div>
                                                                    </div>

                                                                    <?php if((\Illuminate\Support\Facades\Session::has('Grades_Update|13-0-2') && isset($grade['auto_reject']['ex_consumer']->id)) || (!isset($grade['auto_reject']['ex_consumer']->id) && \Illuminate\Support\Facades\Session::has('Grades_Create|13-0-1'))): ?>
                                                                        <div class="col-12 mt-3 text-end" style="padding-left: 12px; border-top: 1px solid #ebedf2; padding-top: 20px;">
                                                                            <div class="m-form__actions m-form__actions">
                                                                                <button type="submit" class="btn btn-primary">
                                                                                    <?php if(isset($grade['auto_reject']['ex_consumer']->id)): ?>
                                                                                        Update
                                                                                    <?php else: ?>
                                                                                        Save
                                                                                    <?php endif; ?>
                                                                                </button>
                                                                                <button type="reset" onclick="window.history.back()" class="btn btn-secondary">
                                                                                    Cancel
                                                                                </button>
                                                                            </div>
                                                                        </div>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </form>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        
                        <div class="m-portlet__foot m-portlet__foot--fit" style="margin-top: 20px;padding-top: 30px;" >
                            <div class="m-form__actions m-form__actions">
                                <input type="button" class="btn btn-primary save-grade-name" value="Save">
                                <input type="button" class="btn btn-secondary" value="Cancel" onclick="window.history.back()">
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<div class="modal fade" id="surrogateModal" role="dialog" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Surrogate Configuration</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-striped" id="surrogateTable">
                        <thead>
                            <tr>
                                <th>Account Type</th>
                                <th>Ownership Type</th>
                                <th>Personal Account Count Config</th>
                                <th>Limit (%)</th>
                                <th>Open Tradeline Vintage (in months)</th>
                                <th>Close Tradeline Vintage (in months)</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="surrogateTableBody">
                            <!-- Data will be populated via JavaScript -->
                        </tbody>
                    </table>
                </div>
                <div style="margin-top: 10px;">
                    <button type="button" class="btn btn-sm btn-success" id="addSurrogateRow">Add Row</button>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="saveSurrogate">Save</button>
            </div>
        </div>
    </div>
</div>


<div class="modal fade" id="personalAccountCountModal" role="dialog" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-md">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Personal Account Count Configuration</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <table class="table table-bordered table-sm" id="pacTable">
                    <thead>
                        <tr>
                            <th>Personal Account Count</th>
                            <th>Percentage Limit (%)</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody id="pacTableBody">
                        
                    </tbody>
                </table>
                <div style="margin-top: 8px;">
                    <button type="button" class="btn btn-sm btn-success" id="addPacRow">+ Add Row</button>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="savePersonalAccountCount">Save</button>
            </div>
        </div>
    </div>
</div>


<div class="modal fade" id="trackRecordModal" role="dialog" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Track Record Configuration</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <div id="trackRecordContent"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="saveSurrogate">Save</button>
            </div>
        </div>
    </div>
</div>

<?php echo $__env->make("admin.layouts.footer", array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
<?php if(!empty($applicant_rejection_json)): ?>
    <script>
        const applicantJsonData = JSON.parse(`<?php echo $applicant_rejection_json; ?>`);
    </script>
<?php endif; ?>
<?php if(!empty($co_applicant_income_rejection_json)): ?>
    <script>
        const coApplicantIncomeJsonData = JSON.parse(`<?php echo $co_applicant_income_rejection_json; ?>`);
    </script>
<?php endif; ?>
<?php if(!empty($co_applicant_signing_rejection_json)): ?>
    <script>
        const coApplicantSigningJsonData = JSON.parse(`<?php echo $co_applicant_signing_rejection_json; ?>`);
    </script>
<?php endif; ?>
<script>

    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
      return new bootstrap.Tooltip(tooltipTriggerEl)
    })

    document.addEventListener('DOMContentLoaded', function() {

        const cardSelectors = document.querySelectorAll('[data-role="collapsible-card"]');

        function applyViewMoreVisibility(rulesContainer, maxVisible = 3) {
            const ruleRows = Array.from(rulesContainer.querySelectorAll('[data-role="rule-row"]:not(.d-none)'));
            const card = rulesContainer.closest('[data-role="collapsible-card"]');
            const addButton = card.querySelector('[data-role="add-button"]');

            let isExpanded = rulesContainer.getAttribute('data-expanded') === 'true';

            // Remove existing toggle button
            let existingToggleBtn = rulesContainer.querySelector('[data-role="toggle-view-button"]');
            if (existingToggleBtn) existingToggleBtn.remove();

            // If already expanded, just show everything
            if (isExpanded || ruleRows.length <= maxVisible) {
                ruleRows.forEach(row => row.style.display = 'flex');
                if (addButton) addButton.style.display = '';
                return;
            }

            // Initially show only first `maxVisible` rows
            ruleRows.forEach((row, index) => {
                row.style.display = index < maxVisible ? 'flex' : 'none';
            });

            if (addButton) addButton.style.display = 'none';

            // Create the toggle button
            const toggleBtn = document.createElement('button');
            toggleBtn.setAttribute('type', 'button');
            toggleBtn.setAttribute('data-role', 'toggle-view-button');
            toggleBtn.classList.add('btn', 'btn-link', 'mt-2');
            toggleBtn.textContent = 'View More';

            toggleBtn.addEventListener('click', () => {
                isExpanded = !isExpanded;

                rulesContainer.setAttribute('data-expanded', isExpanded ? 'true' : 'false');

                if (isExpanded) {
                    ruleRows.forEach(row => row.style.display = 'flex');
                    toggleBtn.textContent = 'View Less';
                    if (addButton) addButton.style.display = '';
                    rulesContainer.appendChild(toggleBtn);
                } else {
                    ruleRows.forEach((row, index) => {
                        row.style.display = index < maxVisible ? 'flex' : 'none';
                    });
                    toggleBtn.textContent = 'View More';
                    if (addButton) addButton.style.display = 'none';

                    const thirdRow = ruleRows[maxVisible - 1];
                    thirdRow.insertAdjacentElement('afterend', toggleBtn);
                }
            });

            // Insert toggle after the third row initially
            const thirdRow = ruleRows[maxVisible - 1];
            thirdRow.insertAdjacentElement('afterend', toggleBtn);
        }

        function setupCollapsibleCard(cardSelector) {
            const card = cardSelector;

            const checkbox = card.querySelector('[data-role="card-checkbox"]');
            const collapseContent = card.querySelector('[data-role="collapse-content"]');
            const rulesContainer = card.querySelector('[data-role="rules-container"]');
            const addButton = card.querySelector('[data-role="add-button"]');

            const viewMoreButton = card.querySelector('[data-role="view-more-button"]');

            if (viewMoreButton) {
                viewMoreButton.addEventListener('click', function () {
                    const ruleRows = rulesContainer.querySelectorAll('[data-role="rule-row"]');
                    ruleRows.forEach(row => {
                        row.style.display = 'flex';
                    });
                    viewMoreButton.classList.add('d-none');
                });
            }

            if (!card) {
                console.warn(`Collapsible card not found for selector: ${cardSelector}`);
                return;
            }

            if (!checkbox || !collapseContent || !rulesContainer) {
                console.error(`Missing required data-role elements within card: ${cardSelector}`);
                return;
            }

            const namePrefix = rulesContainer.dataset.namePrefix;
            const templateRowId = rulesContainer.dataset.templateId;
            const initialRuleCount = parseInt(rulesContainer.dataset.initialCount || '1', 10);
            
            // Try to find template within rulesContainer first, then fallback to ID
            const templateRow = rulesContainer.querySelector(`[id="${templateRowId}"]`) || document.getElementById(templateRowId);
            let ruleIndex = initialRuleCount;

            if (!namePrefix || !templateRowId) {
                console.error(`Missing data-name-prefix or data-template-id on rules container within card: ${cardSelector}`);
                return;
            }

            function toggleCardSection() {
                const isChecked = checkbox.checked;
                enableFormElements(card, !isChecked);
                if (isChecked) {
                    card.classList.remove('disabled'); 
                } else {
                    card.classList.add('disabled');
                }
            }

            function enableFormElements(element, disabled) {
                const formElements = element.querySelectorAll(`input:not([data-role="card-checkbox"]), select, button:not([data-role="card-checkbox"])`);
                formElements.forEach(el => {
                    if (!el.closest(`#${templateRowId}`)) {
                        // For select elements that use bootstrap-select (selectpicker), use jQuery to toggle disabled and refresh
                        if (el.tagName === 'SELECT' && window.jQuery) {
                            const $el = jQuery(el);
                            $el.prop('disabled', disabled);
                            if ($el.hasClass('selectpicker') && typeof $el.selectpicker === 'function') {
                                $el.selectpicker('refresh');
                            }
                        } else {
                            el.disabled = disabled;
                        }
                    }
                });
                // Explicitly handle the add button state based on checkbox, even if inside template query
                if (addButton) {
                    addButton.disabled = disabled;
                }
            }

            // --- Event Listeners ---

            // Add Rule Button
            if (addButton) {
                addButton.addEventListener('click', function() {
                    // Count current non-template rows to get the next available index.
                    // This handles the case where populateCard() added rows after setupCollapsibleCard()
                    // initialised ruleIndex, which would cause stale indices to collide with existing rows.
                    const existingRows = rulesContainer.querySelectorAll(`[data-role="rule-row"]:not(#${templateRowId}):not(.d-none)`);
                    const nextIndex = existingRows.length;

                    // Prevent adding more than 1 row for nach-bounce
                    if (templateRowId === 'nach-bounce-rule-template' && nextIndex >= 1) {
                        alert('Only 1 row can be added for this rule.');
                        return;
                    }
                    const newRow = templateRow.cloneNode(true);
                    newRow.classList.remove('d-none');
                    newRow.style.display = 'flex';
                    newRow.removeAttribute('id');

                    // Update name attributes with the correct prefix and new index
                    newRow.querySelectorAll('[name]').forEach(input => {
                        if (input.hasAttribute('name')) {
                            input.name = input.name.replace('__PREFIX__', namePrefix)
                                                .replace('__INDEX__', nextIndex);
                        }
                        input.disabled = !checkbox.checked;
                        input.required = true;
                    });

                    // Enable the delete button in the new row if the card is enabled
                    const deleteButton = newRow.querySelector('[data-role="delete-button"]');
                    if(deleteButton){
                        deleteButton.disabled = !checkbox.checked;
                    }

                    rulesContainer.appendChild(newRow);
                    applyViewMoreVisibility(rulesContainer);
                });
            }

            rulesContainer.addEventListener('click', function(event) {
                const deleteButton = event.target.closest('[data-role="delete-button"]');
                if (deleteButton && !deleteButton.disabled) {
                    const rowToRemove = deleteButton.closest('[data-role="rule-row"]');
                    if (rowToRemove && rowToRemove.id !== templateRowId) {
                        rowToRemove.remove();
                    }
                }
            });

            toggleCardSection();

            checkbox.addEventListener('change', toggleCardSection);
        }

        cardSelectors.forEach(cardElement => {
            setupCollapsibleCard(cardElement);
        });

        function populateCard(cardElement, data) {
            if (cardElement == 'principal_written_off_rules') {
                const card = $(cardElement) + '-rejection';
            }
            const card = $(cardElement);
            const cardIdentifier = cardElement.id ? `#${cardElement.id}` : `.${cardElement.className.split(' ').join('.')}`;

            const rulesContainer = card.find('[data-role="rules-container"]');
            const ownershipSelect = card.find('select[data-role="ownership-select"]');
            const templateId = rulesContainer.length ? rulesContainer.data('template-id') : null;

            if (rulesContainer.length && templateId) {
                // Find template within rulesContainer or global fallback
                const templateRowFound = rulesContainer.find('#' + templateId).length ? rulesContainer.find('#' + templateId) : $('#' + templateId);
                if (templateRowFound.length) {
                    rulesContainer.find(`[data-role="rule-row"]:not(#${templateId})`).remove();
                } else {
                    rulesContainer.find(`[data-role="rule-row"]`).remove();
                }
            } else if(rulesContainer.length) {
                rulesContainer.find(`[data-role="rule-row"]`).remove();
            }

            if (ownershipSelect.length) {
                ownershipSelect.find('option').prop('selected', false);
                if (ownershipSelect.hasClass('selectpicker')) {
                    ownershipSelect.selectpicker('refresh');
                }
            }

            const templateRow = templateId ? (rulesContainer.find('#' + templateId).length ? rulesContainer.find('#' + templateId) : $('#' + templateId)) : null;
            const namePrefix = rulesContainer.length ? rulesContainer.data('name-prefix') : null; // Get prefix here

            if (!rulesContainer.length || !templateRow || !templateRow.length || !namePrefix) {
                console.error(`populateCard: Required elements/attributes for population not found within card: ${cardIdentifier}`);
                return;
            }

            // Clear existing rule rows
            rulesContainer.find(`[data-role="rule-row"]:not(#${templateId})`).remove();

            // Populate Ownership
            const ownershipValues = data[0].ownership || [];
            if (ownershipSelect.length) {
                ownershipValues.forEach(ownershipValue => {
                    ownershipSelect.find(`option[value="${ownershipValue}"]`).prop('selected', true);
                });
                if (ownershipSelect.hasClass('selectpicker')) {
                    ownershipSelect.selectpicker('refresh');
                }
            }

            //Populate Rules
            const rules = data[0].rules || [];

            if (rules.length == 0) {
                card.find('input[type="checkbox"]').prop('checked', false);
                card.addClass('disabled');
                card.find('[data-role="collapse-content"]').find('input, select, textarea, button').prop('disabled', true);
            }

            rules.forEach((rule, ruleIndex) => {
                const newRow = templateRow.clone();
                newRow.removeClass('d-none hidden-rule-row');
                newRow.css('display', 'flex');
                newRow.removeAttr('id');
                if (!newRow.is('[data-role="rule-row"]')) {
                    newRow.attr('data-role', 'rule-row');
                }

                // Populate fields conditionally
                newRow.find('[name$="[values]"]').val(rule.value);
                newRow.find('[name$="[months]"]').val(rule.months);
                const operatorSelect = newRow.find('[name$="[operator]"]');
                if (operatorSelect.length) operatorSelect.val(rule.operator);
                const tradelinesInput = newRow.find('[name$="[tradelines]"]');
                if (tradelinesInput.length) tradelinesInput.val(rule.tradelines);
                const accountTypeInput = newRow.find('[name$="[account_type]"]');
                if (accountTypeInput.length) accountTypeInput.val(rule.account_type);

                // Update name attributes
                newRow.find('[name]').each(function() {
                    let input = $(this);
                    let currentName = input.attr('name');
                    if (currentName) {
                        let newName = currentName.replace('__PREFIX__', namePrefix)
                                                .replace('__INDEX__', ruleIndex);
                        input.attr('name', newName);
                    }
                    input.attr('required', true);
                });

                // Remove delete button for first row
                const deleteButton = newRow.find('[data-role="delete-button"]');
                if (ruleIndex === 0 && deleteButton.length) {
                    deleteButton.remove();
                }

                rulesContainer.append(newRow);
                applyViewMoreVisibility(rulesContainer[0]);
            });
        }

        function populateElements(jsonBody, containerSelector) {
            if (!jsonBody || !jsonBody.new_rejection_rules) return;

            const $container = $(containerSelector);
            const rulesData = jsonBody.new_rejection_rules;

            // populate non collapsible fields
            for (const key in rulesData) {
                if (rulesData.hasOwnProperty(key)) {
                    const value = rulesData[key];
                    const selector = `input[data-key="ec_${key.toLowerCase()}"]`;
                    const element = $container.find(selector);
                    if (element.length) {
                        if (element.is('input[type="checkbox"]')) {
                            element.prop('checked', !!value);
                        } else {
                            element.val(value);
                        }
                    }
                }
            }

            const cardElementsToPopulate = $container.find('[data-role="collapsible-card"][data-data-key]');

            cardElementsToPopulate.each(function() {
                const cardElement = this;
                const dataKey = cardElement.dataset.dataKey;
                let cardData = [];
                if (cardElement.hasAttribute('data-static-rules')) {
                    return;
                }

                if (dataKey && rulesData.hasOwnProperty(dataKey) && Array.isArray(rulesData[dataKey]) && rulesData[dataKey].length > 0) {
                    if(rulesData[dataKey][0] && rulesData[dataKey][0].ownership && rulesData[dataKey][0].rules) {
                        cardData = rulesData[dataKey];
                    }
                }

                if (cardData.length > 0) {
                    populateCard(cardElement, cardData);
                }
            });
        }

        if (typeof applicantJsonData !== 'undefined') {
            populateElements(applicantJsonData, '#applicant_tab');
        }
        if (typeof coApplicantIncomeJsonData !== 'undefined') {
            populateElements(coApplicantIncomeJsonData, '#co_applicant_income_tab');
        }
        if (typeof coApplicantSigningJsonData !== 'undefined') {
            populateElements(coApplicantSigningJsonData, '#co_applicant_signing_tab');
        }
    });

    $( document ).ready(function() {
        $('#employee_status').selectpicker('refresh');
        $('#solar_financing_for').selectpicker('refresh');
        $('#solar_power_type').selectpicker('refresh');
        $('.selectpicker').selectpicker('refresh'); // Refresh all for tabs
    });

    $(function () {
        $('[data-toggle="tooltip"]').tooltip({placement: 'top'});
    });

    $( document ).ready(function() {
        var $ecAutoRejectRule = $('#ec_auto_reject_rule');
        $('input, select, textarea').each(function() {
        // Remove the "required" attribute unless the element is inside the specific div
            if (!$ecAutoRejectRule.has($(this)).length) {
                $(this).removeAttr('required');
            }
        });

        // Handle tab switching on validation failure for auto reject except consumer form
        // Native browser validation blocks submit event when required fields are in hidden tabs,
        // so we intercept the button click instead and validate manually.
        $('#ec_auto_reject_rule').on('click', 'button[type="submit"]', function(e) {
            try {
                e.preventDefault();
                var $form = $(this).closest('form');
                // Clear previous validation state
                $form.find('.tab-validation-error').remove();
                $form.find('.is-invalid').removeClass('is-invalid');

                var firstInvalidEl = null;

                // Check all required inputs across all tabs
                $form.find('input[required]').each(function() {
                    if ($.trim($(this).val()) === '') {
                        firstInvalidEl = this;
                        return false; // break
                    }
                });

                if (firstInvalidEl) {
                    var $invalid = $(firstInvalidEl);
                    var $tabPane = $invalid.closest('.tab-pane');
                    var tabId = $tabPane.attr('id');

                    // Manually switch tabs: update nav links
                    $form.find('.nav-tabs .nav-link').removeClass('active');
                    $form.find('.nav-tabs a[href="#' + tabId + '"]').addClass('active');

                    // Manually switch tabs: update tab panes
                    $form.find('.tab-content .tab-pane').removeClass('active');
                    $tabPane.addClass('active');

                    // Show error - use placeholder as field name
                    var fieldName = $invalid.attr('name');
                    $invalid.addClass('is-invalid');
                    $tabPane.find('.row').first().before(
                        '<div class="tab-validation-error alert alert-danger" style="margin-bottom:15px;">' +
                        '<strong>' + fieldName + '</strong> is required. Please fill in all required fields in this tab.' +
                        '</div>'
                    );
                    $invalid.focus();
                } else {
                    // Serialize all form fields into a single JSON payload to avoid SecArgumentsLimit
                    var formFields = $form.serializeArray();
                    var _token = '';
                    var grade_id = '';
                    var for_consumer = '';
                    var payloadFields = [];

                    for (var i = 0; i < formFields.length; i++) {
                        var f = formFields[i];
                        if (f.name === '_token') { _token = f.value; }
                        else if (f.name === 'grade_id') { grade_id = f.value; }
                        else if (f.name === 'for_consumer') { for_consumer = f.value; }
                        else { payloadFields.push(f); }
                    }

                    $.ajax({
                        type: 'POST',
                        url: $form.attr('action'),
                        data: {
                            _token: _token,
                            grade_id: grade_id,
                            for_consumer: for_consumer,
                            form_data: JSON.stringify(payloadFields)
                        },
                        success: function() {
                            window.location.reload();
                        },
                        error: function(xhr) {
                            console.error('Auto reject save error:', xhr.status, xhr.responseText);
                            alert('Error saving: ' + xhr.statusText);
                        }
                    });
                }
            } catch(err) {
                console.error('Auto reject tab validation error:', err);
            }
        });
    });

    $("input,select").on("change",function(){
        $(this).addClass("changed");
        $(this).attr("data-changed", "true");
        $(".field-hint").css("display", 'none');
    });

    $(document).ready(function() {
        $("#update_approval_grade").on("change", "input", "select", function () {
            $(this).addClass("changed");
            $(this).attr("data-changed", "true");
            $(".field-hint").css("display", 'none');
        });
    });

    // API call for saving Grade name
    $('.save-grade-name').click(function(){
        var _token = '<?php echo csrf_token(); ?>';
        let grade_alias = $("input[name='grade_alias']").val();
        let grade_name_changed = $("input[name='grade_alias']").attr("data-changed");
        let grade_id = $("input[name='grade_alias']").attr("data-id");
        if(grade_name_changed){
            $.ajax({
                type: 'POST',
                url: "/admin/grade/save-grade-name",
                data: {grade_id: grade_id, grade_alias: grade_alias, _token: _token},
                dataType: "JSON",
                success: function (response) {
                    $(".init-loader").css({'display': 'none'});
                    window.location.href = '/admin/grades';
                }
            });

        }
    })

    $(document).on("submit", "#approval_grade", function(e){
        e.preventDefault();
        let _token = '<?php echo csrf_token(); ?>';
        let grade_alias = $("input[name='grade_alias']").val();
        let grade_id = $("input[name='grade_alias']").attr("data-id");

        if(grade_alias === ''){
            $("input[name='grade_alias']").focus();
            $(".field-hint").css("display", 'block');
            e.preventDefault();
        }else{
            const $form = $('#approval_grade');

            // If any collapsible card header checkbox is checked, mark all its fields as changed
            $form.find('[data-role="collapsible-card"]').each(function () {
                const $card = $(this);
                const $checkbox = $card.find('[data-role="card-checkbox"]');
                if ($checkbox.length && $checkbox.is(':checked')) {
                    $card.find('input, select, textarea').addClass('changed');
                }
            });

            // Disable surrogate/track record hidden inputs if their checkboxes are unchecked
            $form.find('[id^="surrogate_checkbox_"]').each(function() {
                var checkbox = $(this);
                if (!checkbox.is(':checked')) {
                    // Find the hidden input as a sibling (they're in the same parent div)
                    var hiddenInput = checkbox.siblings('input[type="hidden"][id^="surrogate_data_"]');
                    // If not found as sibling, try by ID within the form (fallback)
                    if (hiddenInput.length === 0) {
                        var label = checkbox.attr('id').replace('surrogate_checkbox_', '');
                        // Use attribute selector to avoid issues with special characters in IDs
                        hiddenInput = $form.find('input[type="hidden"][id="surrogate_data_' + label + '"]');
                    }
                    if (hiddenInput.length) {
                        hiddenInput.prop('disabled', true);
                    }
                }
            });
            $form.find('[id^="track_record_checkbox_"]').each(function() {
                var checkbox = $(this);
                if (!checkbox.is(':checked')) {
                    // Find the hidden input as a sibling (they're in the same parent div)
                    var hiddenInput = checkbox.siblings('input[type="hidden"][id^="track_record_data_"]');
                    // If not found as sibling, try by ID within the form using attribute selector (fallback)
                    if (hiddenInput.length === 0) {
                        var label = checkbox.attr('id').replace('track_record_checkbox_', '');
                        // Use attribute selector to avoid issues with special characters in IDs
                        hiddenInput = $form.find('input[type="hidden"][id="track_record_data_' + label + '"]');
                    }
                    if (hiddenInput.length) {
                        hiddenInput.prop('disabled', true);
                    }
                }
            });

            // Disable only inputs that are not marked as changed so they are not included in the payload
            const $nonChangedInputs = $form.find('input:not(.changed)');
            $nonChangedInputs.prop('disabled', true);

            // Disable empty range fields (age_salaried, age_employed, age_self_employed, etc. with [0] and [1] indices)
            $form.find('input[name$="[0]"], input[name$="[1]"]').each(function() {
                if ($(this).val() === '') {
                    $(this).prop('disabled', true);
                }
            });

            let formData = $form.serialize();

            // Re-enable previously disabled inputs for further interactions
            $nonChangedInputs.prop('disabled', false);
            $form.find('[id^="surrogate_data_"], [id^="track_record_data_"]').prop('disabled', false);
            $form.find('input[name$="[0]"], input[name$="[1]"]').prop('disabled', false);

            $.ajax({
                type: 'POST',
                url: "/admin/grade/save",
                data: {grade_id: grade_id, grade_alias: grade_alias, formData: formData, _token: _token},
                dataType: "JSON",
                success: function (response) {
                    $(".init-loader").css({'display': 'none'});
                    window.location.reload();
                }
            });
        }

    })

    $(document).on("submit", "form[id^='update_approval_grade_']", function(e){
        e.preventDefault();
        let _token = '<?php echo csrf_token(); ?>';
        let grade_alias = $("input[name='grade_alias']").val();
        let grade_id = $("input[name='grade_alias']").attr("data-id");
        let $form = $(this);

        if(grade_alias === ''){
            $("input[name='grade_alias']").focus();
            $(".field-hint").css("display", 'block');
            e.preventDefault();
        }else{
            // If any collapsible card header checkbox is checked inside this form, mark all its fields as changed
            $form.find('[data-role="collapsible-card"]').each(function () {
                const $card = $(this);
                const $checkbox = $card.find('[data-role="card-checkbox"]');
                if ($checkbox.length && $checkbox.is(':checked')) {
                    $card.find('input, select, textarea').addClass('changed');
                }
            });

            // Disable surrogate/track record hidden inputs if their checkboxes are unchecked
            $form.find('[id^="surrogate_checkbox_"]').each(function() {
                var checkbox = $(this);
                if (!checkbox.is(':checked')) {
                    // Find the hidden input as a sibling (they're in the same parent div)
                    var hiddenInput = checkbox.siblings('input[type="hidden"][id^="surrogate_data_"]');
                    if (hiddenInput.length === 0) {
                        var label = checkbox.attr('id').replace('surrogate_checkbox_', '');
                        // Use attribute selector to avoid issues with special characters in IDs
                        hiddenInput = $form.find('input[type="hidden"][id="surrogate_data_' + label + '"]');
                    }
                    if (hiddenInput.length) {
                        hiddenInput.prop('disabled', true);
                    }
                }
            });
            $form.find('[id^="track_record_checkbox_"]').each(function() {
                var checkbox = $(this);
                if (!checkbox.is(':checked')) {
                    // Find the hidden input as a sibling (they're in the same parent div)
                    var hiddenInput = checkbox.siblings('input[type="hidden"][id^="track_record_data_"]');
                    // If not found as sibling, try by ID within the form using attribute selector (fallback)
                    if (hiddenInput.length === 0) {
                        var label = checkbox.attr('id').replace('track_record_checkbox_', '');
                        // Use attribute selector to avoid issues with special characters in IDs
                        hiddenInput = $form.find('input[type="hidden"][id="track_record_data_' + label + '"]');
                    }
                    if (hiddenInput.length) {
                        hiddenInput.prop('disabled', true);
                    }
                }
            });

            // Disable only inputs that are not marked as changed so they are not included in the payload
            const $nonChangedInputs = $form.find('input:not(.changed)');
            $nonChangedInputs.prop('disabled', true);

            let formData = $form.serialize();

            // Re-enable previously disabled inputs for further interactions
            $nonChangedInputs.prop('disabled', false);
            $form.find('[id^="surrogate_data_"], [id^="track_record_data_"]').prop('disabled', false);
            let details = {grade_id: grade_id, grade_alias: grade_alias, formData: formData, _token: _token, is_update: true};
            $.ajax({
                type: 'POST',
                url: "/admin/grade/save",
                data: details,
                dataType: "JSON",
                success: function (response) {
                    $(".init-loader").css({'display': 'none'});
                    window.location.reload();
                }
            });
        }

    })

    $("select[name='employment_type']").change(function(){
        var type = $(this).find('option:selected').val();
        var id = $(this).attr('data-id');
        var _token = '<?php echo csrf_token(); ?>';
        if (type && id) {
            $(".init-loader").css({'display': 'block'});
            $.ajax({
                type: 'POST',
                url: "/admin/consumer-application/get-document-by-emp-type",
                data: {type: type, _token: _token},
                dataType: "JSON",
                success: function (response) {
                    $(".init-loader").css({'display': 'none'});
                    $("select.document_set_view_" + id).html(response.data);
                }
            });
        }
    });

    // Handle Surrogate checkbox change event
    $(document).on('change', '[id^="surrogate_checkbox_"]', function() {
        var checkbox = $(this);
        var checkboxId = checkbox.attr('id');
        var label = checkboxId.replace('surrogate_checkbox_', '');
        var buttonId = 'surrogate_btn_' + label;
        var button = $('[id="' + buttonId + '"]');
        var hiddenInputId = 'surrogate_data_' + label;
        var hiddenInput = $('#' + hiddenInputId);
        
        if (checkbox.is(':checked')) {
            button.prop('disabled', false);
            // Update the status in hidden input field
            if (hiddenInput.length) {
                try {
                    var currentData = JSON.parse(hiddenInput.val() || '{"values":[],"status":0}');
                    currentData.status = 1;
                    hiddenInput.val(JSON.stringify(currentData));
                    hiddenInput.addClass('changed');
                } catch (e) {
                    console.error('Error updating surrogate status:', e);
                }
            }
        } else {
            button.prop('disabled', true);
            // Reset to default empty state when unchecked
            if (hiddenInput.length) {
                hiddenInput.val('{"values":[],"status":0}');
                hiddenInput.removeClass('changed');
            }
        }
        
        checkbox.addClass('changed');
    });

    // Handle Track Record checkbox change event
    $(document).on('change', '[id^="track_record_checkbox_"]', function() {
        var checkbox = $(this);
        var checkboxId = checkbox.attr('id');
        var label = checkboxId.replace('track_record_checkbox_', '');
        var buttonId = 'track_record_btn_' + label;
        var button = $('[id="' + buttonId + '"]');
        var hiddenInputId = 'track_record_data_' + label;
        var hiddenInput = $('#' + hiddenInputId);
        
        if (checkbox.is(':checked')) {
            button.prop('disabled', false);
            // Update the status in hidden input field
            if (hiddenInput.length) {
                try {
                    var currentData = JSON.parse(hiddenInput.val() || '{"ownership":"","years":0,"months":0,"percentage":0,"amount":0,"status":0}');
                    currentData.status = 1;
                    hiddenInput.val(JSON.stringify(currentData));
                    hiddenInput.addClass('changed');
                } catch (e) {
                    console.error('Error updating track record status:', e);
                }
            }
        } else {
            button.prop('disabled', true);
            // Reset to default empty state when unchecked
            if (hiddenInput.length) {
                hiddenInput.val('{"ownership":"","years":0,"months":0,"percentage":0,"amount":0,"status":0}');
                hiddenInput.removeClass('changed');
            }
        }
        
        checkbox.addClass('changed');
    });

    // Store current button reference for save functionality
    var currentSurrogateButton = null;
    var currentSurrogateLabel = null;

    // Account type and ownership type options
    var accountTypeOptions = ['Home Loan', 'Personal Loan', 'Credit Card', 'Auto Loan', 'Gold Loan', 'Business Loan', 'Education Loan', 'Other'];
    var ownershipTypeOptions = ['Individual', 'Joint', 'Guarantor', 'Other'];
    // Function to create a table row with editable fields
    function createSurrogateRow(data, index) {
        data = data || {};
        var accountType = data.account_type || '';
        var ownershipType = data.ownership_type || '';
        var limit = data.limit || '';
        var openVintage = data.open_vintage || '';
        var closeVintage = data.close_vintage || '';
        var accountTypeCount = data.account_type_count || '';
        var status = data.status || 0;
        const account_types = <?php echo json_encode($account_type_list); ?>;

        var row = '<tr data-row-index="' + index + '">';
        
        // Account Type dropdown
        row += '<td><select class="form-control m-input selectpicker" name="surrogate_account_type[]" id="surrogate_account_type" multiple data-selected-text-format="count > 2">';
        $.each(account_types, function(i, option) {
            var isSelected = accountType && (Array.isArray(accountType) ? accountType.some(o => o.toLowerCase() === option.toLowerCase()) : accountType.toLowerCase() === option.toLowerCase());
            row += '<option value="' + option + '" ' + (isSelected ? 'selected' : '') + '>' + option + '</option>';
        });
        row += '</select></td>';
        
        // Ownership Type dropdown
        row += '<td><select class="form-control m-input selectpicker" name="surrogate_ownership_type[]" id="surrogate_ownership_type" multiple>';
        $.each(ownershipTypeOptions, function(i, option) {
            var isSelected = ownershipType && (Array.isArray(ownershipType) ? ownershipType.some(o => o.toLowerCase() === option.toLowerCase()) : ownershipType.toLowerCase() === option.toLowerCase());
            row += '<option value="' + option + '" ' + (isSelected ? 'selected' : '') + '>' + option + '</option>';
        });
        row += '</select></td>';
        
        // Personal Account Count Config button
        // accountTypeCount can be: an array of {personal_count, percentage_limit} objects (new format),
        // a legacy single object, or empty.
        var pacRows = [];
        if (Array.isArray(accountTypeCount) && accountTypeCount.length > 0) {
            pacRows = accountTypeCount;
        } else if (accountTypeCount && typeof accountTypeCount === 'object' && !Array.isArray(accountTypeCount)) {
            // Legacy single-object: wrap in array if it has data
            if (accountTypeCount.personal_count || accountTypeCount.percentage_limit) {
                pacRows = [accountTypeCount];
            }
        } else if (accountTypeCount && typeof accountTypeCount === 'number') {
            pacRows = [{ personal_count: accountTypeCount, percentage_limit: 0 }];
        }
        var pacLabel = pacRows.length > 0 ? pacRows.length + ' row(s) configured' : 'Configure';
        var pacDataRaw = JSON.stringify(pacRows);
        var pacHasCfg = pacRows.length > 0;
        row += '<td><button type="button" class="btn btn-sm ' + (pacHasCfg ? 'btn-success' : 'btn-info') + ' surrogate-pac-btn" data-pac=\'' + pacDataRaw.replace(/'/g, '&#39;') + '\' style="white-space: nowrap;">' + pacLabel + '</button></td>';

        // Limit, Open Vintage, and Close Vintage inputs — disabled when PAC is configured
        var inputDisabled = pacHasCfg ? 'disabled title="Disabled: PAC config overrides this field"' : '';
        row += '<td><input type="number" class="form-control surrogate-limit" value="' + limit + '" min="0" style="width: 80px;" ' + inputDisabled + '></td>';
        
        // Open Vintage input
        row += '<td><input type="number" class="form-control surrogate-open-vintage" value="' + openVintage + '" min="0" style="width: 80px;" ' + inputDisabled + '></td>';
        
        // Close Vintage input
        row += '<td><input type="number" class="form-control surrogate-close-vintage" value="' + closeVintage + '" min="0" style="width: 80px;" ' + inputDisabled + '></td>';
        
        // Status checkbox
        row += '<td><input type="checkbox" class="surrogate-status-checkbox" ' + (status == 1 ? 'checked' : '') + '></td>';
        
        // Delete button
        row += '<td><button type="button" class="btn btn-sm btn-danger delete-surrogate-row">Delete</button></td>';
        
        row += '</tr>';
        return row;
    }

    // Function to create a track record table row
    function createTrackRecordRow(data) {
        data = data || {};
        const ownership = data.value?.ownership || '';
        const close_months = data.value?.close_months || '';
        const open_months = data.value?.open_months || '';
        const percentage = data.value?.percentage || '';
        const amount = data.value?.amount || '';
        const exceptions = data.value?.exception || '';
        const account_types = <?php echo json_encode($account_type_list); ?>;

        let paragraph = '<p class="track-record-sentence" style="line-height: 2;">';
        paragraph += '<span style="white-space: nowrap;">Ownership type should be ';

        paragraph += '<select class="form-control m-input selectpicker track-record-select" name="track_record_ownership[]" id="track_record_ownership" multiple data-selected-text-format="count > 3" data-width="100px">';
        $.each(ownershipTypeOptions, function(i, option) {
            var isSelected = ownership && (Array.isArray(ownership) ? ownership.some(o => o.toLowerCase() === option.toLowerCase()) : ownership.toLowerCase() === option.toLowerCase());
            paragraph += '<option value="' + option + '" ' + (isSelected ? 'selected' : '') + '>' + option + '</option>';
        });
        paragraph += '</select></span>';
        
        paragraph += ' <span style="white-space: nowrap;">and should have a closed loan within last ';
        paragraph += '<input type="number" class="form-control track-record-close-months" value="' + close_months + '" min="0" style="display: inline-block; width: 60px;">';
        paragraph += ' months</span> <span style="white-space: nowrap;">or / and active loan with a vintage of minimum ';
        paragraph += '<input type="number" class="form-control track-record-open-months" value="' + open_months + '" min="0" style="display: inline-block; width: 60px;">';
        paragraph += ' months</span> <span style="white-space: nowrap;">(except ';
        
        // Exceptions Dropdown (Select Element)
        paragraph += '<select class="form-control m-input selectpicker track-record-select" name="track_record_exceptions[]" id="track_record_exceptions" multiple data-selected-text-format="count > 3" data-width="100px">'
        $.each(account_types, function(i, option) {
            var isSelected = exceptions && (Array.isArray(exceptions) ? exceptions.some(o => o.toLowerCase() === option.toLowerCase()) : exceptions.toLowerCase() === option.toLowerCase());
            paragraph += '<option value="' + option + '" ' + (isSelected ? 'selected' : '') + '>' + option + '</option>';
        });
        paragraph += '</select></span>';
        paragraph += ' <span style="white-space: nowrap;">) OR / and Sanction Limit Or Amount of ';
        paragraph += '<input type="number" class="form-control track-record-percentage" value="' + percentage + '" min="0" max="100" step="0.01" style="display: inline-block; width: 60px;">';
        paragraph += ' % of proposed loan value or Rs ';
        paragraph += '<input type="number" class="form-control track-record-amount" value="' + amount + '" min="0" style="display: inline-block; width: 80px;">';
        paragraph += ' whichever is lower.</span></p>';
        
        return paragraph;
    }

    // Function to decode HTML entities
    function decodeHtmlEntities(str) {
        var textarea = document.createElement('textarea');
        textarea.innerHTML = str;
        return textarea.value;
    }

    // Wrapper function to read data from button and open modal (generic for both Surrogate and Track Record)
    function openModalFromButton(buttonElement) {
        var button = $(buttonElement);
        var label = button.data('label') || button.attr('data-label');
        var modalType = button.data('modal-type') || button.attr('data-modal-type') || 'surrogate';
        var jsonDataRaw = button.attr('data-json-data');
        
        var jsonData = null;
        if (jsonDataRaw) {
            try {
                var decodedJson = decodeHtmlEntities(jsonDataRaw);
                jsonData = JSON.parse(decodedJson);
            } catch (e) {
                console.error('Error parsing JSON from data attribute:', e, 'Raw data:', jsonDataRaw);
            }
        }
        
        openModal(label, jsonData, modalType);
    }

    var currentModalType = '';

    // Function to open modal with JSON data (generic for both Surrogate and Track Record)
    function openModal(label, jsonData, modalType) {
        modalType = modalType;
        currentModalType = modalType;
        currentSurrogateLabel = label;
        
        var buttonId = modalType === 'track-record' ? 'track_record_btn_' + label : 'surrogate_btn_' + label;
        var button = $('#' + buttonId);
        currentSurrogateButton = button;
        
        var modalTitle = modalType === 'track-record' ? 'Track Record Configuration' : 'Surrogate Configuration';
        $('#surrogateModal .modal-title').text(modalTitle);
        
        if (modalType === 'track-record') {
            $('#addSurrogateRow').hide();
        } else {
            $('#addSurrogateRow').show();
        }
        
        if (modalType === 'track-record') {
            // Handle Track Record data (single object)
            var trackRecordData = {};
            if (jsonData) {
                // If it's a string, decode HTML entities first, then parse
                if (typeof jsonData === 'string') {
                    try {
                        var decodedJson = decodeHtmlEntities(jsonData);
                        trackRecordData = JSON.parse(decodedJson);
                    } catch (e) {
                        console.error('Error parsing Track Record JSON string:', e, 'Original data:', jsonData);
                        trackRecordData = {};
                    }
                } else {
                    trackRecordData = jsonData;
                }
            }
            trackRecordContent = $('#trackRecordContent');
            trackRecordContent.html(createTrackRecordRow(trackRecordData));
            $('#track_record_exceptions').selectpicker('refresh');
            $('#track_record_ownership').selectpicker('refresh');
            
            // Function to apply styles to Bootstrap Select wrapper
            function applySelectStyles() {
                // Bootstrap Select wraps the select in a div.bootstrap-select
                var ownershipSelect = $('#track_record_ownership');
                var exceptionsSelect = $('#track_record_exceptions');
                
                // Try to find the wrapper - it could be next sibling or parent
                var ownershipWrapper = ownershipSelect.next('.bootstrap-select');
                var exceptionsWrapper = exceptionsSelect.next('.bootstrap-select');
                
                if (ownershipWrapper.length === 0) {
                    ownershipWrapper = ownershipSelect.parent().find('.bootstrap-select').first();
                }
                if (exceptionsWrapper.length === 0) {
                    exceptionsWrapper = exceptionsSelect.parent().find('.bootstrap-select').first();
                }
                
                if (ownershipWrapper.length > 0) {
                    ownershipWrapper.css({
                        'display': 'inline-block',
                        'width': '100px',
                        'vertical-align': 'middle',
                        'margin': '0 5px'
                    });
                }
                if (exceptionsWrapper.length > 0) {
                    exceptionsWrapper.css({
                        'display': 'inline-block',
                        'width': '100px',
                        'vertical-align': 'middle',
                        'margin': '0 5px'
                    });
                }
            }
            
            // Apply styles after a short delay to ensure Bootstrap Select has initialized
            setTimeout(applySelectStyles, 100);
            
            // Also apply when modal is fully shown
            $('#trackRecordModal').off('shown.bs.modal').on('shown.bs.modal', function() {
                setTimeout(applySelectStyles, 50);
            });
            
            $('#trackRecordModal').modal('show');
        } else {
            var surrogateData = [];
            var tableHead = $('#surrogateTable thead tr');
            tableHead.html('<th>Account Type</th><th>Ownership Type</th><th>Personal Account Count Config</th><th>Limit (%)</th><th>Open Tradeline Vintage (in months)</th><th>Close Tradeline Vintage (in months)</th><th>Status</th><th>Action</th>');
            var tableBody = $('#surrogateTableBody');
            tableBody.empty();
            if (jsonData) {
                if (typeof jsonData === 'string') {
                    try {
                        var decodedJson = decodeHtmlEntities(jsonData);
                        jsonData = JSON.parse(decodedJson);
                    } catch (e) {
                        console.error('Error parsing JSON string:', e, 'Original data:', jsonData);
                        jsonData = null;
                    }
                }
                if (jsonData) {
                    if (jsonData.values && Array.isArray(jsonData.values)) {
                        surrogateData = jsonData.values;
                    } else if (Array.isArray(jsonData)) {
                        surrogateData = jsonData;
                    } else if (jsonData.values) {
                        surrogateData = Array.isArray(jsonData.values) ? jsonData.values : [];
                    }
                }
            }
            if (surrogateData && surrogateData.length > 0) {
                $.each(surrogateData, function(index, item) {
                    tableBody.append(createSurrogateRow(item, index));
                });
            } else {
                // Add one empty row if no data
                tableBody.append(createSurrogateRow({}, 0));
            }
            $('#surrogateTableBody').find('[name="surrogate_ownership_type[]"]').selectpicker('refresh');
            $('#surrogateTableBody').find('[name="surrogate_account_type[]"]').selectpicker('refresh');
            $('#surrogateModal').modal('show');
        }
    }

    // Handle add row button
    $(document).on('click', '#addSurrogateRow', function() {
        var tableBody = $('#surrogateTableBody');
        var rowCount = tableBody.find('tr').length;
        tableBody.append(createSurrogateRow({}, rowCount));
        $('#surrogateTableBody').find('[name="surrogate_ownership_type[]"]').selectpicker('refresh');
        $('#surrogateTableBody').find('[name="surrogate_account_type[]"]').selectpicker('refresh');
    });

    // Handle delete row button
    $(document).on('click', '.delete-surrogate-row', function() {
        $(this).closest('tr').remove();
    });

    // Handle save button click (generic for both Surrogate and Track Record)
    $(document).on('click', '#saveSurrogate', function() {
        var completeData = null;
        var completeJsonData = null;
        
        if (currentModalType === 'track-record') {
            var trackRecordContent = $('#trackRecordContent');
            if (trackRecordContent.length) {
                var ownership = trackRecordContent.find('#track_record_ownership').val();
                var close_months = trackRecordContent.find('.track-record-close-months').val();
                var open_months = trackRecordContent.find('.track-record-open-months').val();
                var percentage = trackRecordContent.find('.track-record-percentage').val();
                var amount = trackRecordContent.find('.track-record-amount').val();
                var exceptions = trackRecordContent.find('#track_record_exceptions').val();
                completeData = {
                    value: {
                        ownership: ownership || '',
                        close_months: close_months ? parseInt(close_months) : 0,
                        open_months: open_months ? parseInt(open_months) : 0,
                        percentage: percentage ? parseFloat(percentage) : 0,
                        amount: amount ? parseInt(amount) : 0,
                        exception: exceptions || ''
                    }
                };
                completeJsonData = JSON.stringify(completeData);
            } else {
                alert('Please fill in the track record data.');
                return;
            }
        } else {
            var tableBody = $('#surrogateTableBody');
            var rows = tableBody.find('tr');
            var surrogateData = [];
            
            rows.each(function() {
                var row = $(this);
                var accountType = row.find('[name="surrogate_account_type[]"]').val();
                var ownershipType = row.find('[name="surrogate_ownership_type[]"]').val();
                var pacBtn = row.find('.surrogate-pac-btn');
                var pacRows = [];
                try { pacRows = JSON.parse(pacBtn.attr('data-pac') || '[]'); } catch(e) { pacRows = []; }
                if (!Array.isArray(pacRows)) { pacRows = []; }
                var limit = row.find('.surrogate-limit').val();
                var openVintage = row.find('.surrogate-open-vintage').val();
                var closeVintage = row.find('.surrogate-close-vintage').val();
                var status = row.find('.surrogate-status-checkbox').is(':checked') ? 1 : 0;

                // Only add row if at least account_type is filled
                if (accountType) {
                    var rowData = {
                        account_type: accountType,
                        ownership_type: ownershipType,
                        account_type_count: pacRows,
                        limit: limit ? parseInt(limit) : 0,
                        open_vintage: openVintage ? parseInt(openVintage) : 0,
                        close_vintage: closeVintage ? parseInt(closeVintage) : 0,
                        status: status
                    };
                    surrogateData.push(rowData);
                }
            });
            
            if (surrogateData.length === 0) {
                alert('Please add at least one row with Account Type.');
                return;
            }
            
            var checkboxId = currentModalType === 'track-record' ? 'track_record_checkbox_' : 'surrogate_checkbox_';
            checkboxId += currentSurrogateLabel;
            const escapedCheckboxId = $.escapeSelector(checkboxId);
            var checkbox = $('#' + escapedCheckboxId);
            var checkboxStatus = checkbox.is(':checked') ? 1 : 0;
            
            // Create complete JSON structure for Surrogate
            completeData = {
                values: surrogateData,
                status: checkboxStatus
            };
            completeJsonData = JSON.stringify(completeData);
        }
        
        // Get checkbox and status for both types
        var checkboxId = currentModalType === 'track-record' ? 'track_record_checkbox_' : 'surrogate_checkbox_';
        checkboxId += currentSurrogateLabel;
        const escapedCheckboxId = $.escapeSelector(checkboxId);
        var checkbox = $('#' + escapedCheckboxId);
        var checkboxStatus = checkbox.is(':checked') ? 1 : 0;
        
        // For track record, add status to the data
        if (currentModalType === 'track-record') {
            completeData.status = checkboxStatus;
            completeJsonData = JSON.stringify(completeData);
        }
        
        // Update the hidden input field
        var hiddenInputId = currentModalType === 'track-record' ? 'track_record_data_' : 'surrogate_data_';
        hiddenInputId += currentSurrogateLabel;
        const escapedHiddenInputId = $.escapeSelector(hiddenInputId);
        var hiddenInput = $('#' + escapedHiddenInputId);
        if (hiddenInput.length) {
            hiddenInput.val(completeJsonData);
            hiddenInput.addClass('changed');
        }

        // Update button data attribute
        var buttonId = currentModalType === 'track-record' ? 'track_record_btn_' : 'surrogate_btn_';
        buttonId += currentSurrogateLabel;
        const escapedButtonId = $.escapeSelector(buttonId);
        var button = $('#' + escapedButtonId);
        if (button.length) {
            button.attr('data-json-data', completeJsonData);
        }
        var successMsg = currentModalType === 'track-record' ? 'Track Record data saved successfully!' : 'Surrogate data saved successfully!';
        alert(successMsg);
        if (currentModalType === 'track-record') {
            $('#trackRecordModal').modal('hide');
        } else {
            $('#surrogateModal').modal('hide');
        }
    });

    // ── Personal Account Count Sub-Modal Logic ──
    var currentPacBtn = null;

    // Helper: create a PAC table row element
    function createPacTableRow(personal_count, percentage_limit) {
        var pc = personal_count !== undefined && personal_count !== null ? personal_count : '';
        var pl = percentage_limit !== undefined && percentage_limit !== null ? percentage_limit : '';
        var $tr = $('<tr>' +
            '<td><input type="number" class="form-control pac-personal-count" min="0" placeholder="e.g. 3" value="' + pc + '"></td>' +
            '<td><input type="number" class="form-control pac-percentage-limit" min="0" max="100" step="0.01" placeholder="e.g. 50" value="' + pl + '"></td>' +
            '<td><button type="button" class="btn btn-sm btn-danger delete-pac-row">Delete</button></td>' +
            '</tr>');
        return $tr;
    }

    // Add a blank PAC row when button clicked
    $(document).on('click', '#addPacRow', function() {
        $('#pacTableBody').append(createPacTableRow('', ''));
    });

    // Delete a PAC row
    $(document).on('click', '.delete-pac-row', function() {
        $(this).closest('tr').remove();
    });

    // Open sub-modal when a PAC button is clicked inside the surrogate table
    $(document).on('click', '.surrogate-pac-btn', function() {
        currentPacBtn = $(this);
        var pacRows = [];
        try { pacRows = JSON.parse(currentPacBtn.attr('data-pac') || '[]'); } catch(e) { pacRows = []; }
        if (!Array.isArray(pacRows)) {
            // Legacy single-object
            pacRows = (pacRows && (pacRows.personal_count || pacRows.percentage_limit)) ? [pacRows] : [];
        }
        var $body = $('#pacTableBody').empty();
        if (pacRows.length === 0) {
            $body.append(createPacTableRow('', ''));
        } else {
            $.each(pacRows, function(i, r) {
                $body.append(createPacTableRow(r.personal_count, r.percentage_limit));
            });
        }
        $('#personalAccountCountModal').modal('show');
        // Fix Bootstrap 3 stacked modal: raise the new backdrop above the surrogate modal
        setTimeout(function() {
            $('.modal-backdrop').not('.pac-backdrop').last().addClass('pac-backdrop').css('z-index', 1055);
        }, 50);
    });

    // Save the PAC sub-modal data back to the button, then disable/enable the Limit cell
    $(document).on('click', '#savePersonalAccountCount', function() {
        var pacRows = [];
        $('#pacTableBody tr').each(function() {
            var pc = $(this).find('.pac-personal-count').val();
            var pl = $(this).find('.pac-percentage-limit').val();
            // Only include rows with at least one value
            if (pc !== '' || pl !== '') {
                pacRows.push({
                    personal_count: pc !== '' ? parseInt(pc) : 0,
                    percentage_limit: pl !== '' ? parseFloat(pl) : 0
                });
            }
        });

        if (currentPacBtn) {
            var hasCfg = pacRows.length > 0;
            currentPacBtn.attr('data-pac', JSON.stringify(pacRows));
            currentPacBtn.text(hasCfg ? pacRows.length + ' row(s) configured' : 'Configure');
            currentPacBtn.removeClass('btn-info btn-success').addClass(hasCfg ? 'btn-success' : 'btn-info');

            // Disable / enable the Limit, Open Vintage, and Close Vintage inputs in this surrogate row
            var $row = currentPacBtn.closest('tr');
            var $limitInput = $row.find('.surrogate-limit');
            var $openVintageInput = $row.find('.surrogate-open-vintage');
            var $closeVintageInput = $row.find('.surrogate-close-vintage');
            if (hasCfg) {
                $limitInput.val('').prop('disabled', true).attr('title', 'Disabled: PAC config overrides this field');
                $openVintageInput.val('').prop('disabled', true).attr('title', 'Disabled: PAC config overrides this field');
                $closeVintageInput.val('').prop('disabled', true).attr('title', 'Disabled: PAC config overrides this field');
            } else {
                $limitInput.prop('disabled', false).removeAttr('title');
                $openVintageInput.prop('disabled', false).removeAttr('title');
                $closeVintageInput.prop('disabled', false).removeAttr('title');
            }
        }
        $('#personalAccountCountModal').modal('hide');
    });

</script>
