@extends('template.app')

@section('meta') 
@endsection

@section('title')
    OBF
@endsection

@section('styles')
<style>
     .highlight {
        background-color: #ffff99; 
    }
    #data-table.dataTable tbody td {
        padding: 0px !important;
        height: 20px !important;
        line-height: 35px !important;
        font-size: 15px !important;
        text-align: center;
    }
    .form-group .custom_color {
        background-color: lightgrey !important;
    }
</style>
@endsection
@section('content')
@php
 if(Auth::user()->roles->pluck('name') == 'fasttag')
@endphp
<!-- Flatpickr CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/jquery.dataTables.min.css">
<style>
    #data-table td {
        white-space: nowrap;
        padding: 0.5rem !important;
        font-size: 15px;
    }

    .select2-container .select2-selection--single
    {
     
      height: 30px;
    }
    .mt-2
    {
        font-size: 15px;
        margin-left: 15px;
    }
    
    .custom-form-spacing {
      margin-bottom: -19px;
    }
    
    
    .width_150 {
        width: 150px;
    }
    .width_200 {
        width: 200px;
    }
    .width_250 {
        width: 250px;
    }
    .width_300 {
        width: 300px;
    }
    .table {
        min-height: 800px;
    }

</style>
<div class="page-breadcrumb">
    
    <div class="row">
        <div class="col-7 align-self-center">
            <h4 class="page-title text-truncate text-dark font-weight-medium mb-1">OBF - Order Booking Forms</h4>
            <div class="d-flex align-items-center">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb m-0 p-0">
                        <li class="breadcrumb-item"><a href="{{ route('dashboard') }}" class="text-muted">Dashboard</a></li>
                        <li class="breadcrumb-item"><a href="{{ route('obf') }}" class="text-muted">OBF</a></li>
                        <li class="breadcrumb-item text-muted active" aria-current="page">List</li>
                    </ol>
                </nav>
            </div>
        </div>
        <div class="col-5 align-self-center">
            <div class="customize-input float-right">
                <!-- Import -->
                     <a class="btn waves-effect waves-light btn-rounded btn-outline-primary pull-right" data-toggle="modal" data-target="#exampleModal" href="Javascript:void(0)">Import</a> 
                <!-- Import -->
                <!-- Export -->
                    <!-- <button class="btn waves-effect waves-light btn-rounded btn-outline-primary pull-right" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">Export</button> -->
                <!-- Export -->
                @canany(['obf-create'])
                    <a class="btn waves-effect waves-light btn-rounded btn-outline-primary pull-right" href="{{ route('obf.create') }}">Add New</a>
                   
                @endcanany
                <!-- <a class="btn waves-effect waves-light btn-rounded btn-outline-primary pull-right" href="{{ url('/example-xlsx/obf_sample.xlsx') }}">Example Excel</a> -->
            </div>
        </div>
        <div class="col-sm-8"></div>
        <div class="col-sm-4">
            <div class="col-md-12 align-self-center collapse" id="collapseExample">
                <div class="customize-input float-right">
                    <form action="{{ route('obf.export') }}" method="get">
                        <div class="row">
                            <div class="form-group col-md-6 ">
                                <select name="slug" class="form-control" required>
                                    <option value="">Select Status</option>
                                    <option value="all">All</option>
                                    <option value="pending">Pending</option>
                                    <option value="accepted">Accepted</option>
                                    <option value="obf_accepted">OBF Accepted</option>
                                    <option value="account_accepted">Account Accepted</option>
                                    <option value="obf_rejected">OBF Accepted</option>
                                    <option value="account_rejected">Account Accepted</option>
                                    <option value="rejected">Rejected</option>
                                    <option value="deleted">Deleted</option>
                                    <option value="completed">Completed</option>
                                </select>
                            </div>
                            <div class="form-group col-md-6">
                                <button class="btn btn-primary" type="submit">Submit</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-body table-responsive" id="datatable" style="text-align: center;">
                    <table class="table table-bordered data-table tables" id="data-table" cellspacing="0" width="100%">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th> Date</th>
                                <th> Location</th>
                                <th> Customer Name (Bill To)</th>
                                <th> GST No </th>
                                <th> Customer Name (Ship To)</th>
                                <th> Team Leader </th>
                                <th> KEC Name </th>
                                <th> Model </th>
                                <th> Variant </th>
                                <th> Exterior Color </th>
                                <th> VIN Number </th>
                                <th width="100"> On Road Price(A) </th>
                                <th> Booking Amount (B(+)) </th>
                                <th> DP Amount Received (C(+)) </th>
                                <th> Finance Amount </th> 
                                <th> Net Disbusment Amount (D(+)) </th>
                                <th> Exchange Amount (E(+)) </th>
                                <th> Total received amount (B+C+D+E = F) </th>
                                <th> Discount (G(-)) </th>
                                <th width="100"> Net Amount Received (F-G=H) </th>
                                <th width="100"> Access / Sort Amount </th>
                                <th width="100"> Due Amount  (A-H=I) </th>
                                <th> OBF Status </th>
                                <th> OBF Approval Status </th>
                                <th> Discount Status </th>
                                <th> Invoice No.</th>
                                <th> Invoice Date </th>
                                <th> EW Status </th>
                                <th> MCP Status </th>
                                <th> RSA Status </th>
                                <th> Accessory Status </th>
                                <th> RTO Status </th>
                                <th> Insurance Status </th>
                                <th> Fasttag Status</th>
                                <th> Municipal Tax Status</th>
                                <th>Action</th>
                            </tr>
                            <tr class="filterrow">
                                <th></th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_150">
                                        <div class="form-group is-empty">
                                            <input type="text" name="booking_date" value="{{ request()->get('booking_date', '') }}" class="form-control text-capitalize" autocomplete="off" tabindex="1" id="booking_date" placeholder="DD-MM-YYYY to DD-MM-YYYY">
                                        </div>
                                    </div>
                                </th>

                                <th>
                                    <div class="search-box-container datatable-form-filter width_250">
                                        <div class="form-group is-empty">
                                            <input type="text" name="branch_name" value="{{ request()->get('branch_name', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="2">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_300">
                                        <div class="form-group is-empty">
                                            <input type="text" name="customer_name" value="{{ request()->get('customer_name', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="3">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_150">
                                        <div class="form-group is-empty">
                                            <input type="text" name="gst" value="{{ request()->get('gst', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="4">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_300">
                                        <div class="form-group is-empty">
                                            <input type="text" name="ship_to_customer_name" value="{{ request()->get('ship_to_customer_name', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="5">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_200">
                                        <div class="form-group is-empty">
                                            <input type="text" name="team_name" value="{{ request()->get('team_name', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="6">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_200">
                                        <div class="form-group is-empty">
                                            <input type="text" name="sales_person_name" value="{{ request()->get('sales_person_name', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="7">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_150">
                                        <div class="form-group is-empty">
                                            <input type="text" name="product" value="{{ request()->get('product', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="8">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_250">
                                        <div class="form-group is-empty">
                                            <input type="text" name="car_varient_name" value="{{ request()->get('car_varient_name', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="9">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_200">
                                        <div class="form-group is-empty">
                                            <input type="text" name="exterior_color" value="{{ request()->get('exterior_color', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="10">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_200">
                                        <div class="form-group is-empty">
                                            <input type="text" name="vin_number" value="{{ request()->get('vin_number', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="11">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_150">
                                        <div class="form-group is-empty">
                                            <input type="text" name="on_road_price" value="{{ request()->get('on_road_price', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="12">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_150">
                                        <div class="form-group is-empty">
                                            <input type="text" name="booking_amount" value="{{ request()->get('booking_amount', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="13">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_150">
                                        <div class="form-group is-empty">
                                            <input type="text" name="dp_amount" value="{{ request()->get('dp_amount', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="14">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_150">
                                        <div class="form-group is-empty">
                                            <input type="text" name="loan_amount" value="{{ request()->get('loan_amount', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="15">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_150">
                                        <div class="form-group is-empty">
                                            <input type="text" name="net_disbusment" value="{{ request()->get('net_disbusment', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="16">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_150">
                                        <div class="form-group is-empty">
                                            <input type="text" name="total_exchange_amount" value="{{ request()->get('total_exchange_amount', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="17">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_150">
                                        <div class="form-group is-empty">
                                            <input type="text" name="final_total" value="{{ request()->get('final_total', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="18">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_150">
                                        <div class="form-group is-empty">
                                            <input type="text" name="finance_discount" value="{{ request()->get('finance_discount', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="19">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_150">
                                        <div class="form-group is-empty">
                                            <input type="text" name="net_total" value="{{ request()->get('net_total', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="20">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_150">
                                        <div class="form-group is-empty">
                                            <input type="text" name="access_sort_amount" value="{{ request()->get('access_sort_amount', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="21">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_150">
                                        <div class="form-group is-empty">
                                            <input type="text" name="due_amount" value="{{ request()->get('due_amount', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="22">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                    <div class="form-group">
                                    <select name="status" class="form-control text-capitalize custom_color" tabindex="15">
                                        <option value=""> -- Select Status -- </option>
                                        <option value="pending" {{ request()->get('status') == 'pending' ? 'selected' : '' }}>Pending</option>
                                        <option value="accepted" {{ request()->get('status') == 'accepted' ? 'selected' : '' }}>Accepted</option>
                                        <option value="obf_accepted" {{ request()->get('status') == 'obf_accepted' ? 'obf_accepted' : '' }}>Obf Accepted</option>
                                        <option value="account_accepted" {{ request()->get('status') == 'account_accepted' ? 'account_accepted' : '' }}>Account Accepted</option>
                                        <option value="obf_rejected" {{ request()->get('status') == 'obf_rejected' ? 'obf_rejected' : '' }}>Obf Rejected</option>
                                        <option value="account_rejected" {{ request()->get('status') == 'account_rejected' ? 'account_rejected' : '' }}>Account Rejected</option>
                                        <option value="rejected" {{ request()->get('status') == 'rejected' ? 'rejected' : '' }}>Rejected</option>
                                        <option value="deleted" {{ request()->get('status') == 'deleted' ? 'deleted' : '' }}>Deleted</option>
                                        <option value="completed" {{ request()->get('status') == 'completed' ? 'completed' : '' }}>Completed</option>
                                        <option value="cancel" {{ request()->get('status') == 'cancel' ? 'selected' : '' }}>Cancel</option>
                                        <option value="deal_generated" {{ request()->get('status') == 'deal_generated' ? 'selected' : '' }}>Deal Generated</option>
                                        <option value="refund_process" {{ request()->get('status') == 'refund_process' ? 'selected' : '' }}>Refund Process</option>
                                    </select>
                                    </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group">
                                            <select name="approval_status" class="form-control text-capitalize custom_color" tabindex="23">
                                                <option value=""> -- Select Status -- </option>
                                                <option value="pending" {{ request()->get('status') == 'pending' ? 'selected' : '' }}>Pending</option>
                                                <option value="obf_tl_accepted" {{ request()->get('status') == 'obf_tl_accepted' ? 'selected' : '' }}>Obf TL Accepted</option>
                                                <option value="obf_tl_rejected" {{ request()->get('status') == 'obf_tl_rejected' ? 'obf_tl_rejected' : '' }}>Obf TL Rejected</option>
                                                <option value="obf_sm_accepted" {{ request()->get('status') == 'obf_sm_accepted' ? 'obf_sm_accepted' : '' }}>Obf SM Accepted</option>
                                                <option value="obf_gm_accepted" {{ request()->get('status') == 'obf_gm_accepted' ? 'obf_gm_accepted' : '' }}>Obf GM Accepted</option>
                                                <option value="obf_gm_rejected" {{ request()->get('status') == 'obf_gm_rejected' ? 'obf_gm_rejected' : '' }}>Obf GM Rejected</option>
                                                <option value="obf_accountant_accepted" {{ request()->get('status') == 'obf_accountant_accepted' ? 'obf_accountant_accepted' : '' }}>Obf Accountant Accepted</option>
                                                <option value="obf_accountant_rejected" {{ request()->get('status') == 'obf_accountant_rejected' ? 'obf_accountant_rejected' : '' }}>Obf Accountant Rejected</option>
                                            </select>
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group">
                                            <select name="discount_flag" class="form-control text-capitalize custom_color" tabindex="24">
                                                <option value=""> -- Select Status -- </option>
                                                <option value="0" @selected(request('discount_flag') === '0')>No Discount Required</option>
                                                <option value="2" @selected(request('discount_flag') == 2)>KEC Discount Approved</option>
                                                <option value="3" @selected(request('discount_flag') == 3)>TL Discount Approved</option>
                                                <option value="4" @selected(request('discount_flag') == 4)>SM Discount Approved</option>
                                                <option value="5" @selected(request('discount_flag') == 5)>GM Discount Approved</option>
                                                <option value="6" @selected(request('discount_flag') == 6)>BH Discount Approved</option>
                                                <option value="7" @selected(request('discount_flag') == 7)>CEO Discount Approved</option>
                                                <option value="8" @selected(request('discount_flag') == 8)>MD Discount Approved</option>
                                            </select>
                                        </div>
                                    </div>

                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_150">
                                        <div class="form-group is-empty">
                                            <input type="text" name="invoice_no" value="{{ request()->get('invoice_no', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="25">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter width_150"> 
                                        <div class="form-group is-empty">
                                            <input type="text" name="invoice_date" value="{{ request()->get('invoice_date', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="26">
                                        </div>
                                    </div>
                                </th>
                                <th><div class="search-box-container datatable-form-filter width_150"></div></th>
                                <th><div class="search-box-container datatable-form-filter width_150"></div></th>
                                <th><div class="search-box-container datatable-form-filter width_150"></div></th>
                                <th><div class="search-box-container datatable-form-filter width_150"></div></th>
                                <th><div class="search-box-container datatable-form-filter width_150"></div></th>
                                <th><div class="search-box-container datatable-form-filter width_150"></div></th>
                                <th><div class="search-box-container datatable-form-filter width_150"></div></th>
                                <th><div class="search-box-container datatable-form-filter width_150"></div></th>
                                <th><div class="search-box-container datatable-form-filter width_150"></div></th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
        
        <!-- Modal For Import -->
        <div class="modal fade" id="exampleModal" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title">Import</h3>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>

                    </div>
                    <form action="{{ route('obf.import') }}" name="form" id="form" method="post" enctype="multipart/form-data"> 
                        @csrf
                        <div class="modal-body">
                            <div class="row">
                                <div class="form-group col-sm-12">
                                    <label for="first_name">Upload File Here</label>
                                    <input type="file" name="file" id="file" class="form-control" placeholder="Plese upload file here" required>
                                    <span class="kt-form__help error file"></span>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="submit" class="btn btn-default">Submit!</button>
                            <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
                        </div>
                     </form> 
                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog -->
        </div>
        
        <!-- Modal For Cancel -->
        <div class="modal fade" id="cancelReasonModal" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title" id="Cancel_module_title">Cancellation Reason</h3> 
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close">&times;</button>
                    </div> 
                    <div class="modal-body">
                        <form id="cancelReasonForm">
                            @csrf
                            <input type="hidden" id="cancel_record_id" name="record_id"> <!-- Store record ID -->
                            <input type="hidden" id="status" name="status"> <!-- Store record ID -->
                            <div class="row">
                                <div class="form-group col-sm-2"></div>
                                <div class="form-group col-sm-8" id="cancel_reason_div">
                                    <select class="form-control" name="cancel_reason" id="cancel_reason">
                                        <option value="">Select Reason</option>
                                        @if(isset($cancel_reason) && $cancel_reason->isNotEmpty())
                                            @foreach($cancel_reason as $row)
                                                <option value="{{ $row->id }}"> {{ $row->name }} </option>
                                            @endforeach
                                        @endif
                                    </select>
                                </div>
                                <div class="form-group col-sm-2"></div>
                            </div>
                            <div class="row">
                                <div class="form-group col-sm-2"></div>
                                <div class="form-group col-sm-8">
                                    <textarea name="cancel_remark" id="cancel_remark" class="form-control" placeholder="Enter Remark"></textarea>
                                </div>
                                <div class="form-group col-sm-2"></div>
                            </div>
                        </form>    
                    </div>
                    <div class="modal-footer">
                        <button type="submit" id="cancelReasonSubmit" class="btn btn-outline-primary btn-sm pull-right">Submit!</button>
                        <button type="button" class="btn btn-outline-primary btn-sm pull-right" data-dismiss="modal">Close</button>
                    </div>  
                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog -->
        </div>
        <!-- Modal -->
        
        <!-- Liquidation Process Modal -->
        <div class="modal fade" id="liquidationModal" role="dialog">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title">Liquidation Process</h3>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close">&times;</button>
                    </div>
                    <div class="modal-body">
                        <form id="liquidationForm">
                            @csrf
                            <input type="hidden" id="liquidation_encoded_id" name="encoded_id"> <!-- Hidden encoded ID -->
                            <input type="hidden" id="hidden_total" name="hidden_total">
                            
                            <div class="row mb-3">
                                <div class="form-group col-sm-2"></div>
                                <div class="form-group col-sm-8">
                                    <select name="approval_status" class="form-control text-capitalize" id="approval_status" tabindex="23" required>
                                        <option value=""> -- Select Refund Type -- </option>
                                        <option value="booking_cancel">Booking cancel</option>
                                        <option value="excess_amount">Excess Amount</option>
                                    </select>    
                                </div>
                                <div class="form-group col-sm-2"></div>
                            </div>
                            <div class="row mb-3">
                                <div class="form-group col-sm-2"></div>
                                <div class="form-group col-sm-8">
                                    <textarea name="refund_remark" id="refund_remark" class="form-control" placeholder="Enter Remarks" required></textarea>
                                </div>
                                <div class="form-group col-sm-2"></div>
                            </div>
                            <div class="row mb-3">
                                <div class="form-group col-sm-2"></div>
                                <div class="form-group col-sm-8">
                                    <input type="text" name="refund_amount" id="refund_amount" class="form-control" placeholder="Enter Amount" min="0" required>
                                </div>
                                <div class="form-group col-sm-2"></div>
                            </div>
                            <div class="row mb-3">
                                <div class="form-group col-sm-2"></div>
                                <div class="form-group col-sm-8">
                                    <p style="color:red;">Do Not Consider Finance Amount Here...</p>
                                    <p style="color:red;">Do Not Consider Discount Amount Here...</p>
                                    <p style="color:red;" id="dynamic_amount"></p>
                                </div>
                                <div class="form-group col-sm-2"></div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" id="liquidationSubmit" class="btn btn-outline-primary btn-sm pull-right">Submit</button>
                        <button type="button" class="btn btn-outline-primary btn-sm pull-right" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog -->
        </div> 
        <!-- Modal -->
        
        <!-- Discount Process Modal -->
        <div class="modal fade" id="discountModal" role="dialog">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title">Discount Process</h3>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close">&times;</button>
                    </div>
                    <div class="modal-body">
                        <form id="discountForm">
                            @csrf
                            <input type="hidden" id="discount_encoded_id" name="encoded_id"> <!-- Hidden encoded ID -->
                            <input type="hidden" id="way_off" name="way_off">
                            
                            <!-- Vehicle / Customer Info -->
                            <div class="table-responsive mb-3">
                                <table class="table table-bordered table-sm text-center" style="min-height:100px!important">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Customer Name</th>
                                            <th>Model</th>
                                            <th>Fuel Type</th>
                                            <th>Variant</th>
                                            <th>On Road Value</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td id="dp_customer_name">--</td>
                                            <td id="dp_model">--</td>
                                            <td id="dp_fuel">--</td>
                                            <td id="dp_variant">--</td>
                                            <td id="dp_on_road">--</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            
                            @php
                                $role = auth()->user()->roles()->pluck('name')->first();
                            
                                // role hierarchy
                                $roleLevel = [
                                    'KEC'                     => 1,
                                    'Team leader'             => 2,
                                    'Sales Manager'           => 3,
                                    'General Manager - Sales' => 4,
                                    'Business Head'           => 5,
                                    'CEO'                     => 6,
                                    'Managing director'       => 7,
                                ];
                            
                                $currentLevel = $roleLevel[$role] ?? 1;

                                $roleMap = [
                                    'KEC' => ['level' => 1, 'field' => 'kec_discount'],
                                    'Team leader' => ['level' => 2, 'field' => 'tl_discount'],
                                    'Sales Manager' => ['level' => 3, 'field' => 'sm_discount'],
                                    'General Manager - Sales' => ['level' => 4, 'field' => 'gm_discount'],
                                    'Business Head' => ['level' => 5, 'field' => 'bh_discount'],
                                    'CEO' => ['level' => 6, 'field' => 'ceo_discount'],
                                    'Managing director' => ['level' => 7, 'field' => 'md_discount'],
                                ];
                                
                                $currentRoleData = $roleMap[$role] ?? null;

                            @endphp
                            
                            <!-- Discount Part -->
                            <div class="table-responsive mb-2">
                                <table class="table table-bordered table-sm" style="min-height:100px!important">
                                    <thead>
                                        <tr>
                                            <th colspan="2" class="text-center fw-bold">Discount Part</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @if ($currentLevel > 1)
                                            <tr>
                                                <td>KEC (Sales Executive)</td>
                                                <td class="text-end" id="dp_kec">0</td>
                                            </tr>
                                        @endif
                            
                                        @if ($currentLevel > 2)
                                            <tr>
                                                <td>Team Leader</td>
                                                <td class="text-end" id="dp_tl">0</td>
                                            </tr>
                                        @endif
                            
                                        @if ($currentLevel > 3)
                                            <tr>
                                                <td>Sales Manager</td>
                                                <td class="text-end" id="dp_sm">0</td>
                                            </tr>
                                        @endif
                            
                                        @if ($currentLevel > 4)
                                            <tr>
                                                <td>General Manager</td>
                                                <td class="text-end" id="dp_gm">0</td>
                                            </tr>
                                        @endif
                            
                                        @if ($currentLevel > 5)
                                            <tr>
                                                <td>Business Head</td>
                                                <td class="text-end" id="dp_bh">0</td>
                                            </tr>
                                        @endif
                            
                                        @if ($currentLevel > 6)
                                            <tr>
                                                <td>C.E.O.</td>
                                                <td class="text-end" id="dp_ceo">0</td>
                                            </tr>
                                        @endif
                            
                                        @if ($currentLevel > 7)
                                            <tr>
                                                <td>Managing Director</td>
                                                <td class="text-end" id="dp_md">0</td>
                                            </tr>
                                        @endif
                                    </tbody>
                                    <tbody>
                                        <input type="hidden" id="base_on_road_price">
                                        <input type="hidden" id="max_role_discount" value="0">
                                        @if(isset($currentRoleData) && $currentRoleData['level'] != 1)
                                            <tr class="fw-bold">
                                                <td class="text-end">{{ $role }}</td>
                                                <td class="text-end">
                                                    <input type="number" min="0" class="form-control form-control-sm text-end role-discount-input" id="dp_role_input" name="{{ $currentRoleData['field'] }}" data-level="{{ $currentRoleData['level'] }}" value="0">
                                                    
                                                    <!-- LIMIT MESSAGE -->
                                                    <small class="text-danger d-none" id="role_discount_error" style="font-size:15px;!important">Maximum allowed discount is ₹0 </small>
                                                </td>
                                            </tr>
                                        @endif
                                    </tbody>
                                    
                                    <tbody>
                                        <tr class="fw-bold">
                                            <td class="text-end">TOTAL</td>
                                            <td class="text-end" id="dp_total_discount">0</td>
                                        </tr>
                                    </tbody>
                                    
                                </table>
                            </div>
                    
                            <!-- After Discount Price -->
                            <div class="table-responsive">
                                <table class="table table-bordered table-sm" style="min-height:50px!important">
                                    <thead>
                                        <tr class="fw-bold">
                                            <th style="font-size:15px!important;">After Discount On Road Price</th>
                                            <th  style="font-size:15px!important;" id="dp_after_discount" class="text-end">0</th>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" id="discountSubmit" class="btn btn-outline-primary btn-sm">Submit</button>
                        <button type="button" id="discountNeedMore" class="btn btn-outline-warning btn-sm">Need More Discount</button>
                        <button type="button" class="btn btn-outline-primary btn-sm pull-right" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-md-4">
        <canvas id="modelChart" width="400" height="400"></canvas>
    </div>
    <div class="col-md-4">
        <canvas id="variantChart" width="400" height="400"></canvas>
    </div>
    <div class="col-md-4">
        <canvas id="statusChart" width="400" height="400"></canvas>
    </div>
</div>
@endsection
@section('scripts')
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<script src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
<script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>

<script type="text/javascript">
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
</script>
<script type="text/javascript">
    

    $(document).ready(function() {
        $('#booking_date').daterangepicker({
            autoUpdateInput: false,
            locale: {
                format: 'DD-MM-YYYY',
                cancelLabel: 'Clear'
            }
        });
    
        $('#booking_date').on('apply.daterangepicker', function(ev, picker) {
            $(this).val(picker.startDate.format('DD-MM-YYYY') + ' to ' + picker.endDate.format('DD-MM-YYYY'));
            $('#data-table').DataTable().draw();
        });
    
        $('#booking_date').on('cancel.daterangepicker', function(ev, picker) {
            $(this).val('');
            $('#data-table').DataTable().draw();
        });
        
        // let rowCount = $("table tbody tr").length;
        // if (rowCount < 3) {
        //     $(".table").css("height", "600px");
        // }

        $('.js-example-basic-single').select2();

        var tableColumns = [
            {data: 'id', name: 'id',class:'text-center id',title: 'No.', orderable: false, width:100,default: true},
            {data: 'booking_date', name: 'booking_date',class:'text-center booking_date',title: 'Date', orderable: false,default: true},
            {data: 'branch_name', name: 'branch_name',class:'text-center branch_name',title: 'Location', orderable: true,default: true},
            {data: 'customer_name', name: 'customer_name',class:'text-center customer_name',title: 'Customer Name (Bill To)', orderable: true,default: true},
            {data: 'gst', name: 'gst',class:'text-center gst',title: 'GST No. (Bill To)', orderable: true,default: true},
            {data: 'ship_to_customer_name', name: 'ship_to_customer_name',class:'text-center ship_to_customer_name',title: 'Customer Name (Ship To)', orderable: true,default: true},
            {data: 'team_name', name: 'team_name',class:'text-center team_name',title: 'Team Leader', orderable: true,default: true},
            {data: 'sales_person_name', name: 'sales_person_name',class:'text-center sales_person_name',title: 'KEC Name', orderable: true,default: true},
            {data: 'product', name: 'product',class:'text-center product',title: 'Model', orderable: true,default: true},
            {data: 'car_varient_name', name: 'car_varient_name',class:'text-center car_varient_name',title: 'Variant', orderable: true,default: true},
            {data: 'exterior_color', name: 'exterior_color',class:'text-center exterior_color',title: 'Exterior Color', orderable: true,default: true},
            {data: 'vin_number', name: 'vin_number',class:'text-center vin_number',title: 'VIN No.', orderable: true,default: true},
            {data: 'on_road_price', name: 'on_road_price',class:'text-center on_road_price',title: 'On Road Price (A)', orderable: false,default: true},
            {data: 'booking_amount', name: 'booking_amount',class:'text-center booking_amount',title: 'Booking Amount (B(+))', orderable: false,default: true},
            {data: 'dp_amount', name: 'dp_amount',class:'text-center dp_amount',title: 'DP Amount Received (C(+))', orderable: false,default: true},
            {data: 'loan_amount', name: 'loan_amount',class:'text-center loan_amount',title: 'Finance Amount', orderable: false,default: true},
            {data: 'net_disbusment', name: 'net_disbusment',class:'text-center net_disbusment',title: 'Net Disbusment Amount (D(+))', orderable: false,default: true},
            {data: 'total_exchange_amount', name: 'total_exchange_amount',class:'text-center total_exchange_amount',title: 'Exchange Amount (E(+))', orderable: false,default: true},
            {data: 'final_total', name: 'final_total',class:'text-center final_total',title: 'Total received amount (B+C+D+E = F)', orderable: false,default: true},
            {data: 'finance_discount', name: 'finance_discount',class:'text-center finance_discount',title: 'Total Discount (G(-))', orderable: false,default: true},
            {data: 'net_total', name: 'net_total',class:'text-center net_total',title: 'Total Amount Receivable (A-G = H)', orderable: false,default: true},
            {data: 'access_sort_amount', name: 'access_sort_amount',class:'text-center access_sort_amount',title: 'Access / Sort Amount', orderable: false,default: true},
            {data: 'due_amount', name: 'due_amount',class:'text-center due_amount',title: 'Due Amount  (H-F=J)', orderable: false,default: true},
            {data: 'status', name: 'status',class:'text-center status',title: 'Finance Progress Status', orderable: true,default: true},
            {data: 'approval_status', name: 'approval_status',class:'text-center approval_status',title: 'Sales Progress Status', orderable: true,default: true},
            {data: 'discount_flag', name: 'discount_flag',class:'text-center discount_flag',title: 'Discount Status', orderable: true,default: true},
            {data: 'invoice_no', name: 'invoice_no',class:'text-center invoice_no',title: 'Invoice No.', orderable: true,default: true},
            {data: 'invoice_date', name: 'invoice_date',class:'text-center invoice_date',title: 'Invoice Date', orderable: true,default: true},
            {data: 'ew_status', name: 'ew_status',class:'text-center ew_status',title: 'EW Status', orderable: true,default: true},
            {data: 'mcp_status', name: 'mcp_status',class:'text-center mcp_status',title: 'MCP Status', orderable: true,default: true},
            {data: 'rsa_status', name: 'rsa_status',class:'text-center rsa_status',title: 'RSA Status', orderable: true,default: true},
            {data: 'accesories_status', name: 'accesories_status',class:'text-center accesories_status',title: 'Accessory Status', orderable: true,default: true},
            {data: 'rto_status', name: 'rto_status',class:'text-center rto_status',title: 'RTO Status', orderable: true,default: true},
            {data: 'insurance_status', name: 'insurance_status',class:'text-center insurance_status',title: 'Insurance Status', orderable: true,default: true},
            {data: 'fasttag_status', name: 'fasttag_status',class:'text-center fasttag_status',title: 'Fasttag Status', orderable: true,default: true},
            {data: 'municipal_tax_status', name: 'municipal_tax_status',class:'text-center municipal_tax_status',title: 'Municipal Tax Status', orderable: true,default: true},
        ];

        tableColumns.push({ 
            data: 'action',
            name: 'action',
            orderable: false,
            searchable: true,
        });

        (function(window, $) {
            window.LaravelDataTables = window.LaravelDataTables || {};
            window.LaravelDataTables["dataTableBuilder"] = $("#data-table").DataTable({
                processing: true,
                serverSide: true,
                language: {
                    "info": "_START_ - _END_ of _TOTAL_",
                    "lengthMenu": "_MENU_ ",
                    "infoFiltered": ""
                },
                // scrollX: true,
                // scrollY: "400px", 
                scrollCollapse: true,
                paging: true,
                searching: false,
    
                bSortCellsTop : true,
                ajax: {
                    url: '{!! route("obf") !!}',
                    method: "POST",
                    data: function (d) {
                        d.booking_date = jQuery(".datatable-form-filter input[name='booking_date']").val();
                        d.branch_name = jQuery(".datatable-form-filter input[name='branch_name']").val();
                        d.customer_name = jQuery(".datatable-form-filter input[name='customer_name']").val();
                        d.gst = jQuery(".datatable-form-filter input[name='gst']").val();
                        d.ship_to_customer_name = jQuery(".datatable-form-filter input[name='ship_to_customer_name']").val();
                        d.team_name = jQuery(".datatable-form-filter input[name='team_name']").val();
                        d.sales_person_name = jQuery(".datatable-form-filter input[name='sales_person_name']").val();
                        d.product = jQuery(".datatable-form-filter input[name='product']").val();
                        d.car_varient_name = jQuery(".datatable-form-filter input[name='car_varient_name']").val();
                        d.exterior_color = jQuery(".datatable-form-filter input[name='exterior_color']").val();
                        d.vin_number = jQuery(".datatable-form-filter input[name='vin_number']").val();
                        d.on_road_price = jQuery(".datatable-form-filter input[name='on_road_price']").val();
                        d.booking_amount = jQuery(".datatable-form-filter input[name='booking_amount']").val();
                        d.dp_amount = jQuery(".datatable-form-filter input[name='dp_amount']").val();
                        d.loan_amount = jQuery(".datatable-form-filter input[name='loan_amount']").val();
                        d.net_disbusment = jQuery(".datatable-form-filter input[name='net_disbusment']").val();
                        d.total_exchange_amount = jQuery(".datatable-form-filter input[name='total_exchange_amount']").val();
                        d.final_total = jQuery(".datatable-form-filter input[name='final_total']").val();
                        d.finance_discount = jQuery(".datatable-form-filter input[name='finance_discount']").val();
                        d.net_total = jQuery(".datatable-form-filter input[name='net_total']").val();
                        d.access_sort_amount = jQuery(".datatable-form-filter input[name='access_sort_amount']").val();
                        d.due_amount = jQuery(".datatable-form-filter input[name='due_amount']").val();
                        d.status = jQuery(".datatable-form-filter select[name='status']").val();
                        d.approval_status = jQuery(".datatable-form-filter select[name='approval_status']").val();
                        d.discount_flag = jQuery(".datatable-form-filter select[name='discount_flag']").val();
                        d.invoice_no = jQuery(".datatable-form-filter input[name='invoice_no']").val();
                        d.invoice_date = jQuery(".datatable-form-filter input[name='invoice_date']").val();
                    },
                    error : function(d) {}
                },
                columns: tableColumns,
                lengthMenu: [
                    [25, 50,100, -1 ],['25', '50','100', 'Show all' ]
                ],
                order: [ [0,'DESC'] ],
                responsive: true,
                colReorder:{
                    enable: false,
                },
                dom: '<"top"f>rt<"bottom"ipl><"clear">',
                fnInitComplete: function(settings, json) {
                    jQuery('table.table input:checkbox').map(function() {
                        if(jQuery(this).prop("checked") != true){
                            var column = table.column( jQuery(this).attr('data-column') );
                            column.visible(false);
                        }
                    });
                },
                pageLength: 25,
            });
        })(window, jQuery);

        $("#min").flatpickr({ onSelect: function () { window.LaravelDataTables["dataTableBuilder"].draw(); }, changeMonth: true, changeYear: true });

        $(document).on("change", "#min", function () {
            window.LaravelDataTables["dataTableBuilder"].draw();
        });

        
        $.ajax({
            url: "{{ route('getObfCounts') }}",
            method: "GET",
            success: function(data) {
                createPieChart(data);
            },
            error: function() {
                console.error("Failed to fetch chart data");
            }
        });
    });

    function createPieChart(data) {
        const ctx = document.getElementById('chartCanvas').getContext('2d');
        new Chart(ctx, {
            type: 'pie',
            data: {
                labels: Object.keys(data),
                datasets: [{
                    label: 'Count',
                    data: Object.values(data),
                    backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF'],
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                }
            }
        });
    }
    
    function cancel_reason(object) {
        var modalElement = document.getElementById('cancelReasonModal');
        var recordId = $(object).data("id"); // Correct reference
        var status = $(object).data("status");
        
        $("#cancel_record_id").val(recordId); // Store record ID
        $("#status").val(status);
        
        if (status === 'delete') {
            $('#Cancel_module_title').text('Deletation Reason');
            $('#cancel_reason_div').hide();
        } else {
            $('#Cancel_module_title').text('Cancellation Reason');
            $('#cancel_reason_div').show();
        }
        
        if (modalElement) {
            var myModal = new bootstrap.Modal(modalElement);
            myModal.show(); // Open modal
        } else {
            console.error("Modal element not found in DOM!");
        }
    }
    
    $(document).ready(function () {
        $("#cancelReasonSubmit").on("click", function () {
            var recordId = $("#cancel_record_id").val();
            var cancelReason = $("#cancel_reason").val();
            var cancelRemark = $("#cancel_remark").val();
            var status = $("#status").val();
            if(status === 'pending'){
                if (cancelReason === "") {
                    alert("Please select a reason!");
                return;
            }    
            }
    
            $.ajax({
                url: "{{ route('obf.cancel') }}",  // Change this to your actual route
                method: "POST",
                data: {
                    _token: "{{ csrf_token() }}", // CSRF token for Laravel
                    record_id: recordId,
                    cancel_reason: cancelReason,
                    cancel_remark: cancelRemark,
                    status: status
                },
                beforeSend: function () {
                    $("#cancelReasonSubmit").prop("disabled", true).text("Submitting...");
                },
                success: function (response) {
                    if(response.success === true){
                        alert(response.message); // Show success message
                        $("#cancelReasonModal").modal("hide"); // Hide modal
                        $("#cancelReasonForm")[0].reset(); // Reset form fields
                        
                        // Wait for modal to fully close before reloading
                        $('#cancelReasonModal').on('hidden.bs.modal', function () {
                            location.reload(); // Refresh page
                        });   
                    }
                },
                error: function (xhr) {
                    alert("Something went wrong. Please try again.");
                },
                complete: function () {
                    $("#cancelReasonSubmit").prop("disabled", false).text("Submit!");
                }
            });
        });
    });

    let cashTotalData = @json($cash_total);
    function liquidation_process(object) {
        var modalElement = document.getElementById('liquidationModal');
        var recordId = $(object).data("id"); 
        
        $("#liquidation_encoded_id").val(recordId); 
        
        const decodedId = atob($(object).data("id"));
        var relatedCash = cashTotalData.filter(item => item.obf_id == decodedId);

        var totalAmount = relatedCash.reduce((sum, item) => {
            return sum + parseFloat(item.amount);
        }, 0);
        
        if (totalAmount > 0) {
            $('#dynamic_amount').html(`You cannot proceed more than ₹${totalAmount.toLocaleString('en-IN')} Amount.`);
        } else {
            $('#dynamic_amount').html(''); // Clear if nothing matches
        }
        
        $("#hidden_total").val(totalAmount);
        if (modalElement) {
            var myModal = new bootstrap.Modal(modalElement);
            myModal.show(); 
        } else {
            console.error("Liquidation modal element not found in DOM!");
        }
    }
    
    $(document).ready(function () {
        $("#liquidationSubmit").on("click", function () {
            var encodedId = $("#liquidation_encoded_id").val();
            var approvalStatus = $("#approval_status").val();
            var refundRemark = $("#refund_remark").val();
            var refundAmount = $("#refund_amount").val();
            var hidden_total = $("#hidden_total").val();
            
            if (!approvalStatus || approvalStatus.trim() === "") {
                alert("Please select refund type.");
                return;
            }
    
            if (!refundRemark || refundRemark.trim() === "") {
                alert("Please enter a remark.");
                return;
            }

            if (refundAmount === "" || isNaN(refundAmount) || parseFloat(refundAmount) < 0) {
                alert("Please enter a valid refund amount.");
                return;
            }
    
            $.ajax({
                url: "{{ route('obf.liquidationprocess') }}",
                method: "POST",
                data: {
                    _token: "{{ csrf_token() }}",
                    encoded_id: encodedId,
                    liquidation_type: approvalStatus, 
                    refund_remark: refundRemark,
                    refund_amount: refundAmount
                },
                beforeSend: function () {
                    $("#liquidationSubmit").prop("disabled", true).text("Submitting...");
                },
                success: function (response) {
                    if (response.success === true) {
                        alert(response.message || "Liquidation processed successfully.");
                        $("#liquidationModal").modal("hide");
                        $("#liquidationForm")[0].reset();
    
                        $('#liquidationModal').on('hidden.bs.modal', function () {
                            location.reload(); 
                        });
                    } else {
                        alert(response.message || "Failed to process liquidation.");
                    }
                },
                error: function () {
                    alert("Something went wrong. Please try again.");
                },
                complete: function () {
                    $("#liquidationSubmit").prop("disabled", false).text("Submit");
                }
            });
        });
    });
    
    /*function discount_process(object) {

        let encodedId = $(object).data('id');
    
        let fetchUrl = $(object).data('fetch-url').replace(':id', encodedId);
    
        $("#discount_encoded_id").val(encodedId);
    
        // 🔹 Existing logic (unchanged)
        const decodedId = atob(encodedId);
    
        // 🔹 Fetch record data
        $.ajax({
            url: fetchUrl,
            type: 'GET',
            success: function (res) {
                
                if (!res.status) return;

                let d = res.data;
    
                // 🔹 Top table
                $('#dp_customer_name').text(d.customer_name ?? '--');
                $('#dp_model').text(d.model ?? '--');
                $('#dp_fuel').text(d.fuel_type_name ?? '--');
                $('#dp_variant').text(d.varient ?? '--');
                $('#dp_on_road').text(
                    '₹' + Number(d.on_road_price ?? 0).toLocaleString('en-IN')
                );
    
                // 🔹 Reset all discounts
                $('#dp_kec, #dp_tl, #dp_sm, #dp_gm, #dp_bh, #dp_ceo, #dp_md').text('0');
    
                let total = 0;
    
                if (res.discount) {
    
                    if (res.data.way_off) {
                        let kec = Number(res.data.way_off);
                        $('#dp_kec').text('₹' + kec.toLocaleString('en-IN'));
                        total += kec;
                    }
                    
                    if (res.discount.tl_discount) {
                        let tl = Number(res.discount.tl_discount);
                        $('#dp_tl').text('₹' + tl.toLocaleString('en-IN'));
                        total += tl;
                    }
                    
                    if (res.discount.sm_discount) {
                        let sm = Number(res.discount.sm_discount);
                        $('#dp_sm').text('₹' + sm.toLocaleString('en-IN'));
                        total += sm;
                    }
                    
                    if (res.discount.gm_discount) {
                        let gm = Number(res.discount.gm_discount);
                        $('#dp_gm').text('₹' + gm.toLocaleString('en-IN'));
                        total += gm;
                    }
                    
                    if (res.discount.bh_discount) {
                        let bh = Number(res.discount.bh_discount);
                        $('#dp_bh').text('₹' + bh.toLocaleString('en-IN'));
                        total += bh;
                    }
                    
                    if (res.discount.ceo_discount) {
                        let ceo = Number(res.discount.ceo_discount);
                        $('#dp_ceo').text('₹' + ceo.toLocaleString('en-IN'));
                        total += ceo;
                    }
                    
                    if (res.discount.md_discount) {
                        let md = Number(res.discount.md_discount);
                        $('#dp_md').text('₹' + md.toLocaleString('en-IN'));
                        total += md;
                    }
                }
    
                // 🔹 Total + After Discount
                $('#dp_total_discount').text('₹' + total.toLocaleString('en-IN'));
    
                let afterDiscount = (d.on_road_price ?? 0) - total;
    
                $('#dp_after_discount').text(
                    '₹' + afterDiscount.toLocaleString('en-IN')
                );
    
                new bootstrap.Modal('#discountModal').show();
            },
            error: function () {
                alert('Failed to fetch discount data');
            }
        });
    }*/
    
    
    function discount_process(object) {

        let encodedId = $(object).data('id');
        let fetchUrl  = $(object).data('fetch-url').replace(':id', encodedId);
    
        $("#discount_encoded_id").val(encodedId);
    
        $.ajax({
            url: fetchUrl,
            type: 'GET',
            success: function (res) {
    
                if (!res.status) return;
    
                let d = res.data;
    
                /* ================= TOP SUMMARY ================= */
                $('#dp_customer_name').text(d.customer_name || '--');
                $('#dp_model').text(d.model || '--');
                $('#dp_fuel').text(d.fuel_type_name || '--');
                $('#dp_variant').text(d.varient || '--');
    
                let basePrice = Number(d.on_road_price || 0);
                $('#dp_on_road').text('₹' + basePrice.toLocaleString('en-IN'));
                $('#base_on_road_price').val(basePrice);
    
                /* ================= ROLE LIMIT ================= */
                let maxLimit = Number(res.discount || 0);
                $('#max_role_discount').val(maxLimit);
    
                /* ================= EXISTING DISCOUNTS ================= */
                let total = 0;
    
                // KEC (fixed)
                let kec = Number(d.way_off || 0);
                $('#dp_kec').text('₹' + kec.toLocaleString('en-IN'));
                total += kec;
    
                updateTotals(basePrice, total);
    
                /* ================= LIVE INPUT HANDLER ================= */
                $(document)
                    .off('input.roleDiscount')
                    .on('input.roleDiscount', '.role-discount-input', function () {
    
                        let entered = Number($(this).val() || 0);
                        let $error  = $('#role_discount_error');
    
                        if (entered > maxLimit) {
                            $(this).val(maxLimit);
    
                            $error
                                .text(
                                    'Maximum allowed discount is ₹' +
                                    maxLimit.toLocaleString('en-IN')
                                )
                                .removeClass('d-none');
                        } else {
                            $error.addClass('d-none');
                        }
    
                        /* 🔁 LIVE RECALC */
                        let dynamicTotal = kec;
    
                        $('.role-discount-input').each(function () {
                            dynamicTotal += Number($(this).val() || 0);
                        });
    
                        updateTotals(basePrice, dynamicTotal);
                    });
    
                new bootstrap.Modal('#discountModal').show();
            },
            error: function () {
                alert('Failed to fetch discount data');
            }
        });
    
        /* ================= HELPER ================= */
        function updateTotals(basePrice, total) {
            $('#dp_total_discount').text('₹' + total.toLocaleString('en-IN'));
    
            let afterDiscount = basePrice - total;
            $('#dp_after_discount').text(
                '₹' + afterDiscount.toLocaleString('en-IN')
            );
        }
    }


    $(document).ready(function () {

        function submitDiscount(actionType) {
            let encodedId   = $("#discount_encoded_id").val();
            let discountVal = $("#dp_role_input").val();
            let finalPrice  = $("#dp_after_discount").text().replace(/,/g, '');
    
            $.ajax({
                url: "{{ route('obf.discount_process') }}",
                type: "POST",
                data: {
                    _token: "{{ csrf_token() }}",
                    encoded_id: encodedId,
                    action: actionType, // submit | need_more
                    discount_value: discountVal,
                    final_price: finalPrice
                },
                beforeSend: function () {
                    $("#discountSubmit, #discountNeedMore")
                        .prop("disabled", true);
                },
                success: function (res) {
                    if (res.success) {
                        alert(res.message);
                        $("#discountModal").modal("hide");
                        location.reload();
                    } else {
                        alert(res.message);
                    }
                },
                error: function () {
                    alert("Something went wrong.");
                },
                complete: function () {
                    $("#discountSubmit, #discountNeedMore")
                        .prop("disabled", false);
                }
            });
        }
    
        $("#discountSubmit").on("click", function () {
            submitDiscount('submit');
        });
    
        $("#discountNeedMore").on("click", function () {
            submitDiscount('need_more');
        });
    
    });


    jQuery('.datatable-form-filter input').on('keyup', function (e) {
        if(jQuery(this).val().length >= 3 || e.keyCode == 13 || !jQuery(this).val()) {
            window.LaravelDataTables["dataTableBuilder"].draw();
            e.preventDefault();
        }
    });

    jQuery('.datatable-form-filter select').on('change', function (e) {
        window.LaravelDataTables["dataTableBuilder"].draw();
        e.preventDefault();
    });

    jQuery('input:checkbox[name="name_sort_asc"],input:checkbox[name="name_sort_desc"]').on('click', function (e) {
        window.LaravelDataTables["dataTableBuilder"].draw();
        e.preventDefault();
    });
</script>
@endsection



