@extends('template.app')

@section('meta') 
@endsection

@section('title')
    Target
@endsection

@section('styles')
<style>
     .highlight {
        background-color: #ffff99; 
    }
    #data-table td,
    #data-table th {
        padding: 10px 12px !important; 
        font-size: 15px;
        text-align: center;
        white-space: nowrap;
        min-width: 120px; 
    }
    .form-group .custom_color {
        background-color: lightgrey !important;
    }
</style>
@endsection
@section('content')
<!-- 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;
        text-align: center;
    }

    .select2-container .select2-selection--single
    {
     
      height: 30px;
    }
    .mt-2
    {
        font-size: 15px;
        margin-left: 15px;
    }
    
    .custom-select {
        width: 200px !important;
    }
    
    .custom-form-spacing {
      margin-bottom: -19px;
    }
    
    .custom-label {
        color: #000 !important;
        font-weight: 600;
    }
    /*.table {*/
    /*    min-height: 600px;*/
    /*}*/

</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">Target</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('target') }}" class="text-muted">Target</a></li>
                    </ol>
                </nav>
            </div>
        </div>
        <div class="col-5 align-self-center">
            <div class="customize-input float-right">
                <a class="btn waves-effect waves-light btn-rounded btn-outline-primary pull-right" href="{{url('/example-xlsx/example-target.xlsx')}}" download> Example Excel </a>
                <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>
                <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>
                <a class="btn btn-outline-primary btn-rounded" data-bs-toggle="modal" data-bs-target="#inquiryModal">  Add New </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('target.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>
                                </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>Branch</th>
                                <th>Model</th>
                                <th>Fuel Type</th>
                                <th>Target Value</th>
                                <th>Team Name</th>
                                <th>Kec Name</th>
                                <th>Action</th>
                            </tr>
                            <tr class="filterrow">
                                <th></th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="date" value="{{ request()->get('date', '') }}" class="form-control text-capitalize" autocomplete="off" tabindex="1" id="date" placeholder="YYYY-MM">
                                        </div>
                                    </div>
                                </th>
                            
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="branch" value="{{ request()->get('branch', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" id="branch" autofocus tabindex="2">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="model" value="{{ request()->get('model', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" id="model" autofocus tabindex="3">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="fuel_type" value="{{ request()->get('fuel_type', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" id="fuel_type" autofocus tabindex="4">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="target_value" value="{{ request()->get('target_value', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" id="target_value" autofocus tabindex="3">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="team_id" value="{{ request()->get('team_id', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" id="team_id" autofocus tabindex="5">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="kec_name" value="{{ request()->get('kec_name', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" id="kec_name" autofocus tabindex="6">
                                        </div>
                                    </div>
                                </th>
                                <th></th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
        

        <!-- Target Modal -->
        <div class="modal fade" id="inquiryModal" role="dialog">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <!-- Modal Header -->
                    <div class="modal-header">
                        <h3 class="modal-title">Target</h3>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">&times;</button>
                    </div>
    
                    <!-- Modal Body -->
                    <div class="modal-body">
                        <form id="inquiryForm">
                            @csrf
                            <input type="hidden" id="inquiry_encoded_id" name="encoded_id"> 
    
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="custom-label">Month</label>
                                   <!-- <input type="date" name="date" id="modal_date" class="form-control">-->
                                    <input type="month" name="date" id="modal_date" class="form-control" required>
                                </div>
                                <div class="col-md-6">
                                    <label for="branch" class="form-label custom-label">Branch</label>
                                    <select name="branch" id="modal_branch" class="form-control" required>
                                        <option value="">Select Branch</option>
                                        @foreach($branch as $item)
                                            <option value="{{ $item->id }}">{{ $item->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label for="target_type">Target Type</label>
                                    <select name="target_type" id="modal_target_type" class="form-control" required>
                                        <option value="">Select Target Type</option>
                                        <option value="wholesale">Wholesale Target</option>
                                        <option value="retail">Retail Target</option>
                                    </select>
                                </div>
                                 <div class="col-md-6">
                                    <label class="custom-label">Target Value (No. Of Vehicle)</label>
                                    <input type="number" name="target_value" id="modal_target_value" class="form-control">
                                </div>
                                <div class="col-md-6">
                                    <label for="model" class="form-label custom-label">Model</label>
                                    <select name="model" id="modal_model" class="form-control">
                                        <option value="">Select Model</option>
                                        @foreach($product as $item)
                                            <option value="{{ $item->id }}">{{ $item->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label for="fuel_type" class="form-label custom-label">Fuel Type</label>
                                    <select name="fuel_type" id="modal_fuel_type" class="form-control">
                                        <option value="">Select Fuel Type</option>
                                        @foreach($fuel_type as $item)
                                            <option value="{{ $item->id }}">{{ $item->title }}</option>
                                        @endforeach
                                    </select>
                                </div>
                               
                                <div class="col-md-6 retail-field">
                                    <label for="team_id" class="form-label custom-label">Team Name</label>
                                    <select name="team_id" id="modal_team_id" class="form-control">
                                        <option value="">Select Team</option>
                                    </select>
                                </div>
                            
                                <div class="col-md-6 retail-field">
                                    <label for="kec_name" class="form-label custom-label">KEC Name</label>
                                    <select name="kec_name" id="modal_kec_name" class="form-control">
                                        <option value="">Select KEC</option>
                                    </select>
                                </div>
                            </div>
                        </form>
                    </div>
    
                    <!-- Modal Footer -->
                    <div class="modal-footer">
                        <button type="submit" id="inquirySubmit" class="btn btn-outline-primary btn-sm">Submit</button>
                        <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
        <!-- Modal -->
        
        <!-- View Target Modal -->
        <div class="modal fade" id="viewModal" role="dialog">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
        
                    <div class="modal-header">
                        <h3 class="modal-title">View Target</h3>
                        <button type="button" class="btn-close" data-bs-dismiss="modal">&times;</button>
                    </div>
        
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-md-6"><label class="custom-label">Month</label><input type="text" id="view_date" class="form-control" readonly></div>
                            <div class="col-md-6"><label class="custom-label">Branch</label><input type="text" id="view_branch" class="form-control" readonly></div>
                            <div class="col-md-6"><label class="custom-label">Target Type</label><input type="text" id="view_target_type" class="form-control" readonly></div>
                            <div class="col-md-6"><label class="custom-label">Target Value</label><input type="text" id="view_target_value" class="form-control" readonly></div>
                            <div class="col-md-6 view_retail_field"><label class="custom-label">Model</label><input type="text" id="view_model" class="form-control" readonly></div>
                            <div class="col-md-6 view_retail_field"><label class="custom-label">Fuel Type</label><input type="text" id="view_fuel_type" class="form-control" readonly></div>
                            <div class="col-md-6 view_retail_field"><label class="custom-label">Team Name</label><input type="text" id="view_team" class="form-control" readonly></div>
                            <div class="col-md-6 view_retail_field"><label class="custom-label">KEC Name</label><input type="text" id="view_kec" class="form-control" readonly></div>
                        </div>
                    </div>
        
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Close</button>
                    </div>
        
                </div>
            </div>
        </div>

        <!-- Import Modal -->
         <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('target.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>
            </div>
        </div>
    </div>
</div>
@endsection
@section('scripts')
<!-- jQuery -->
<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>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css" />
<script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.10.0/css/bootstrap-datepicker.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.10.0/js/bootstrap-datepicker.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@2.29.4/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>

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

    $(document).ready(function () {
        $('#date').datepicker({
            format: "yyyy-mm",
            startView: "months",
            minViewMode: "months",
            autoclose: true
        });
        
        $('#date').on('change', function () {
            $('#data-table').DataTable().draw();
        });

        // $('#date').daterangepicker({
        //     autoUpdateInput: false,
        //     locale: {
        //         format: 'DD-MM-YYYY',
        //         cancelLabel: 'Clear'
        //     }
        // });
    
        // $('#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();
        // });
    
        // $('#date').on('cancel.daterangepicker', function(ev, picker) {
        //     $(this).val('');
        //     $('#data-table').DataTable().draw();
        // });
        
        // if ($("table tbody tr").length < 3) {
        //     $(".table").css("height", "600px");
        // }

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

        let tableColumns = [
            { data: 'id', name: 'id', class: 'text-center width_100' },
            { data: 'date', name: 'date', class: 'text-center width_100' },
            { data: 'location_name', name: 'location_name', class: 'width_200' },
            { data: 'model_name', name: 'model_name', class: 'width_150' },
            { data: 'fule_type', name: 'fule_type', class: 'width_150' },
            { data: 'target_value', name: 'target_value', class: 'width_150' },
            { data: 'team_name', name: 'team_name', class: 'width_200' },
            { data: 'sales_person_name', name: 'sales_person_name', class: 'width_200' },
            {
                data: 'action',
                name: 'action',
                orderable: false,
                searchable: false,
            }
        ];

        // Initialize DataTable
        window.LaravelDataTables = window.LaravelDataTables || {};
        window.LaravelDataTables["dataTableBuilder"] = $("#data-table").DataTable({
            processing: true,
            serverSide: true,
            ajax: {
                url: '{{ route("target") }}',
                method: 'POST',
                data: function (d) {
                    d.date = $(".datatable-form-filter input[name='date']").val();
                    d.branch = $(".datatable-form-filter select[name='branch']").val();
                    d.model = $(".datatable-form-filter select[name='model']").val();
                    d.fuel_type = $(".datatable-form-filter select[name='fuel_type']").val();
                    d.target_value = $(".datatable-form-filter input[name='target_value']").val();
                    d.team_id = $(".datatable-form-filter select[name='team_id']").val();
                    d.sales_person_name = $(".datatable-form-filter select[name='sales_person_name']").val();
                }
            },
            columns: tableColumns,
            language: {
                "info": "_START_ - _END_ of _TOTAL_",
                "lengthMenu": "_MENU_ ",
                "infoFiltered": ""
            },
            paging: true,
            searching: false,
            scrollCollapse: true,
            bSortCellsTop: true,
            order: [[0, 'DESC']],
            responsive: true,
            dom: '<"top"f>rt<"bottom"ipl><"clear">',
            pageLength: 25,
        });

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

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

    // Submit Insert/Update
    $(document).on('click', '#inquirySubmit', function (e) {
        e.preventDefault();

        let form = $('#inquiryForm')[0];
        let formData = new FormData(form);

        $.ajax({
            url: '{{ route("target.insert") }}',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,

            success: function (response) {
                if (response.success) {
                    $('#inquiryModal').modal('hide');
                    $('#inquiryForm')[0].reset();
                    window.LaravelDataTables["dataTableBuilder"].ajax.reload(null, false);
                    toastr.success(response.message || "Target submitted successfully!");
                } else {
                    toastr.error(response.message || "Submission failed.");
                }
            },
            error: function (xhr) {
                if (xhr.responseJSON && xhr.responseJSON.errors) {
                    $.each(xhr.responseJSON.errors, function (key, messages) {
                        toastr.error(messages[0]);
                    });
                } else {
                    toastr.error("Something went wrong.");
                }
            }
        });
    });

    // Edit target
    $(document).on('click', '.editInquiry', function () {
        let encodedId = $(this).data('id');

        $.ajax({
            url: '/target/edit/' + encodedId,
            method: 'GET',
            success: function (response) {
                if (response.success) {
                    let data = response.data;
                    var fullDate = data.date;
                    var monthValue = fullDate.substring(0, 7);
        
                    $('#inquiry_encoded_id').val(encodedId);
                    $('#modal_date').val(monthValue);
                    $('#modal_branch').val(data.branch);
                    $('#modal_model').val(data.model);
                    $('#modal_target_type').val(data.target_type);
                    $('#modal_fuel_type').val(data.fuel_type);
                    $('#modal_target_value').val(data.target_value);
                    $('#modal_team_id').val(data.team_id);
                    $('#modal_kec_name').val(data.kec_name);
                    if(data.target_type == 'wholesale'){
                        $('.retail-field').hide();
                    }else{
                        $('.retail-field').show();
                    }
                    $('#inquiryModal').modal('show');
                } else {
                    toastr.error('Failed to fetch target data.');
                }
            },
            error: function () {
                toastr.error('An error occurred while fetching target data.');
            }
        });
    });

    $(document).on('click', '.viewInquiry', function () {
        let id = $(this).data('id');
    
        $.ajax({
            url: '/target/view/' + id,
            method: 'GET',
            success: function (res) {
                if (res.success) {
                    const d = res.data;
                   
                    // $('#view_date').val(d.date || '-');
                    $('#view_date').val(d.date || '-');
                    $('#view_branch').val(d.branch_name || '-');
                    $('#view_model').val(d.model_name || '-');
                    $('#view_fuel_type').val(d.fuel_type_name || '-');
                    $('#view_target_type').val(d.target_type);
                    $('#view_target_value').val(d.target_value || '-');
                    $('#view_team').val(d.team_name || '-');
                    $('#view_kec').val(d.kec_name || '-');
                    
                    if(d.target_type == 'wholesale'){
                        $('.view_retail_field').hide();
                    }else{
                        $('.view_retail_field').show();
                    }
    
                    $('#viewModal').modal('show');
                } else {
                    toastr.error(res.message);
                }
            },
            error: function () {
                toastr.error('Unable to fetch target data.');
            }
        });
    });

    // Delete target
    $(document).on('click', '.deleteInquiry', function () {
        let id = $(this).data('id');
    
        Swal.fire({
            title: 'Are you sure?',
            text: "This action cannot be undone.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, delete it!',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ route("target.delete") }}',
                    method: 'POST',
                    data: {
                        _token: $('meta[name="csrf-token"]').attr('content'),
                        id: id
                    },
                    success: function (res) {
                        if (res.success) {
                            toastr.success(res.message);
                            window.LaravelDataTables["dataTableBuilder"].ajax.reload(null, false);
                        } else {
                            toastr.error(res.message);
                        }
                    },
                    error: function () {
                        toastr.error('Server error during delete.');
                    }
                });
            }
        });
    });
    
    $('.retail-field').show();
    $('#modal_target_type').on('change', function () {
        var type = $('#modal_target_type').val();
         if (type === 'wholesale') {
            $('.retail-field').hide();
            $('#modal_model').val('');
            $('#modal_fuel_type').val('');
         }else{
             $('.retail-field').show();
             $('#modal_branch').change();
         }
    });
    
    $('#modal_branch').on('change', function () {
        var branch_id = $(this).val();
        var target_type = $('#modal_target_type').val();
        $('#modal_team_id').empty();
        if (branch_id) {
            $.ajax({
                url: "{{ route('get.teams', ':branch_id') }}".replace(':branch_id', branch_id),
                type: 'GET',
                success: function (response) {
                    $('#modal_team_id').empty();
                    $('#modal_team_id').append('<option value="">Select Team</option>');
    
                    if (response.status) {
                        $.each(response.data, function (key, team) {
                            $('#modal_team_id').append(
                                '<option value="' + team.id + '">' +
                                team.team_name +
                                '</option>'
                            );
                        });
    
                    }
    
                }
            });
    
        } else {
            $('#modal_team_id').empty();
            $('#modal_team_id').append('<option value="">Select Team</option>');
        }
    
    });
    
    $('#modal_team_id').on('change', function () {
        var team_id = $(this).val();
        $('#modal_kec_name').empty();
        
        if (team_id) {
            $.ajax({
                url: "{{ route('get.kecs', ':team_id') }}".replace(':team_id', team_id),
                type: 'GET',
                success: function (response) {
                    $('#modal_kec_name').append('<option value="">Select KEC</option>');
                    if (response.status) {
                        $.each(response.data, function (key, team) {
                            $('#modal_kec_name').append(
                                '<option value="' + team.id + '">' +
                                team.kec_name +
                                '</option>'
                            );
                        });
    
                    }
    
                }
            });
    
        } else {
            $('#modal_kec_name').empty();
            $('#modal_kec_name').append('<option value="">Select KEC</option>');
        }
    
    });

</script>

@endsection