Untitled

 avatar
user_6618186
plain_text
2 months ago
101 kB
4
Indexable
@extends('layouts.app')
@php
use Jenssegers\Agent\Facades\Agent;
// dd($warrantys);
@endphp

@section('css')

<style>
    .py-0 {
        padding: 0px;
    }

    .my-0 {
        margin: 0px;
    }

    .d-none {
        display: none;

    }

    .d-block {
        display: block;

    }

    .loader_wrapper {
        width: 100vw;
        height: 100vw;
        position: fixed;
        background: rgba(0, 0, 0, .3);
        z-index: 9999;
    }

    .loader_inner {
        height: 5rem;
        width: 5rem;
        border-radius: 50%;
        border: 10px solid orange;
        border-top-color: #002147;
        box-sizing: border-box;
        background: transparent;
        animation: loading 1s linear infinite;
        top: 50%;
        left: 50%;
        position: fixed;
    }

    .device-box {
        margin-top: 40px;
    }
    .tagify{
        display: block!important;
    }

    .delete-btn {
        float: inline-end;
        text-align-last: right;
        margin-top: 30px;
    }

    @keyframes loading {
        0% {
            transform: rotate(0deg);
        }

        0% {
            transform: rotate(360deg);
        }
    }
    .drop-zone {
    width: 100%;
    padding: 20px;
    border: 2px dashed #009578;
    border-radius: 10px;
    background-color: #f8f9fa;
    text-align: center;
    font-family: "Quicksand", sans-serif;
    font-weight: 500;
    font-size: 16px;
    color: #009578;
    cursor: pointer;
    transition: background-color 0.3s;
}

.drop-zone:hover {
    background-color: #e2e6ea;
}

.drop-zone--over {
    border-style: solid;
    background-color: #d1ecf1;
}

.drop-zone__input {
    display: none;
}

.drop-zone__prompt {
    display: block;
}

.image-preview-container {
    margin-top: 10px;
    display: flex;
    flex-wrap: wrap;
}

.image-preview {
    width: 100px;
    height: 100px;
    margin: 5px;
    border-radius: 5px;
    border: 1px solid #ddd;
    object-fit: cover;
}
.drop-zone__input {
    display: none !important;
}


</style>
@endsection
@section('title', __('repair::lang.add_job_sheet'))

@section('content')
<div class="loader d-none">
    <div class="loader_wrapper">
        <div class="loader_inner"></div>
    </div>
</div>
<!-- Content Header (Page header) -->
<section class="content-header no-print">
    @php
    $darkmode = (int)DB::table('business')->where('id',session()->get('business.id'))->value('enable_darkmode');
    @endphp
    <h1 class="@if ($darkmode==1) darkm-text @endif">
        @lang('repair::lang.job_sheet')
        {{-- <small>@lang('repair::lang.create')</small> --}}
        <a href="{{route('gui.create')}}" class="btn btn-primary">
            Easy Mode
        </a>
        <a class="btn btn-primary" onclick="introJs().start();">
            Guide Me
        </a>
    </h1>
</section>
<section class="content" onload="opencustomer()">
    @if(!empty($repair_settings))
    @php
    $product_conf = isset($repair_settings['product_configuration']) ? explode(',',
    $repair_settings['product_configuration']) : [];

    $defects = isset($repair_settings['problem_reported_by_customer']) ? explode(',',
    $repair_settings['problem_reported_by_customer']) : [];

    $product_cond = isset($repair_settings['product_condition']) ? explode(',', $repair_settings['product_condition']) :
    [];
    @endphp
    @else
    @php
    $product_conf = [];
    $defects = [];
    $product_cond = [];
    @endphp
    @endif
    {!! Form::open(['action' => '\Modules\Repair\Http\Controllers\JobSheetController@store', 'id' => 'job_sheet_form',
    'method' => 'post', 'files' => true]) !!}
    @includeIf('repair::job_sheet.partials.scurity_modal')
    <div class="box box-solid">
        <div class="box-body">
            <div class="row">
                @if(count($business_locations) == 1)
                @php
                $default_location = current(array_keys($business_locations->toArray()));
                @endphp
                @else
                @php $default_location = null;
                @endphp
                @endif
                <div class="col-md-2">
                    <div class="form-group" data-title="Select Branch"
                        data-intro="Please Select the branch for which you are creating this Jobsheet." data-step="1">
                        {!! Form::label('location_id', __('business.business_location') . ':*' )!!}
                        {!! Form::select('location_id', $business_locations, $default_location, ['class' =>
                        'form-control', 'placeholder' => __('messages.please_select'), 'required',
                        'onload'=>'opencustomer()','style' => 'width: 100%;','tabindex' => '1' ]); !!}
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-group" data-title="Select Customer"
                        data-intro="Please Select name of the Customer for whom your are creating this Jobsheet. You can also search them using Phone No."
                        data-step="2">
                        {!! Form::label('contact_id', __('role.customer') .':*') !!}
                        <button type="button" @if(!auth()->user()->can('customer.create')) disabled @endif class="btn
                            btn-link px-1-add add_new_customer"
                            data-href="{{action('ContactController@create',['quick_add' =>
                            true])}}" title="Add Customer" data-container=".view_modal" data-title="Add
                            Customer" data-intro="If customer doesn't exist, then you can add them using this button."
                            data-step="3"><i class="fa fa-plus-circle text-primary fa-lg"></i></button>
                        <div class="input-group">
                            <input type="hidden" id="default_customer_id" value="{{ $walk_in_customer['id'] ?? ''}}">
                            <input type="hidden" id="default_customer_name"
                                value="{{ $walk_in_customer['name'] ?? ''}}">
                            <input type="hidden" id="default_customer_balance"
                                value="{{ $walk_in_customer['balance'] ?? ''}}">

                            {!! Form::select('contact_id',
                            [], null, ['class' => 'form-control mousetrap', 'id' => 'customer_id','onchange' =>
                            'opentech()','placeholder' => 'Enter Customer name / phone', 'required', 'style' => 'width:
                            100%;','tabindex' => '2']); !!}
                            {{-- <span class="input-group-btn">
                                <button type="button" class="" Poppins", sans-serif" data-name=""
                                    @if(!auth()->user()->can('customer.create')) disabled @endif><i
                                        class="fa fa-plus-circle text-primary fa-lg"></i></button>
                            </span> --}}
                        </div>
                    </div>
                </div>
                <div class="col-md-2" data-title="Select Service Type"
                    data-intro="Select where you will provide service or repair a device. <br><b>Select Carry In</b> - If Customer has come to your store with his/her device. <br><b>Select Pickup</b> - If you have to go to Customer's Place to Get the device and repair it at your Service Center. <br><b>Select On Site</b> - If your Technician will visit at your Customer's Place and repair it there. <br>If you select Pick up or On Site, you will have to add customer's address from where Pickup will be done or repairing will be done. "
                    data-step="5">
                    {!! Form::label('service_type', __('repair::lang.service_type').':*', ['style' =>
                    'margin-left:20px;']) !!}
                    <br>
                    {!! Form::select('service_type', [
                    'carry_in' => __('repair::lang.carry_in'),
                    'pick_up' => __('repair::lang.pick_up'),
                    'on_site' => __('repair::lang.on_site')
                    ], 'carry_in', ['class' => 'form-control select2', 'required']) !!}
                </div>
                <div class="col-md-2" data-title="Select Current Status"
                    data-intro="Select Status of Device, by default it should be Received as you are just receiving the Device. Later customer can track the status of Service like Assigned to Technician, In Progress or delivered etc."
                    data-step="13">
                    <div class="form-group">
                        <label for="status_id">{{__('sale.status') . ':*'}}
                        </label>
                        <button type="button" @if(!auth()->user()->can('brand.create')) disabled @endif class="btn-add
                            bg-white px-1-add btn-flat btn-modal"
                            data-href="{{action('\Modules\Repair\Http\Controllers\RepairStatusController@create')}}"
                            data-container=".view_modal" data-title="Create Status" data-intro="If you have permission,
                            you can create Status as per your need like Taken From Customer, Under Repairing etc, which
                            will help you to understand the status or repairing." data-step="14"><i
                                class="fa fa-plus-circle text-primary fa-lg"></i></button>
                        <br>
                        <!-- <select name="status_id" class="form-control status" required>
                                    <option value="">select status</option>
                                    @foreach ($repair_statuses as $item)
                                        <option value="{{$item->id}}">{{$item->name}}</option>
                                    @endforeach
                                </select> -->
                        <select name="status_id" class="form-control status" id="status_id" required>
                        </select>

                        <!--added from add brand -->

                        <!-- <span class="input-group-btn"> -->

                        <!-- </span> -->

                        <!-- till here added from add brand -->
                    </div>
                </div>
            </div>
            <div class="row pick_up_onsite_addr" style="display: none;">
                <div class="row">
                    <div class="col-md-3">
                        {!! Form::label('pick_up_on_site_addr', __('repair::lang.pick_up_on_site_addr') . ':') !!}
                        {!! Form::textarea('pick_up_on_site_addr',null, ['class' => 'form-control ', 'id' =>
                        'pick_up_on_site_addr', 'placeholder' => __('repair::lang.pick_up_on_site_addr'), 'rows' => 3]);
                        !!}
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-12">
        <button type="button" class="btn btn-success pull-right" id="addNewDeviceBtn">
            <i class="fa fa-plus"></i> Add New Device
        </button>
    </div>
    <!--PRODUCT BOX-->
    <div id="devicesContainer">
        <div class="box box-solid device-box" id="deviceForm_1">
            <div class="box-body">
                <div class="row">
                    <div class="col-sm-2" data-title="Select Brand"
                        data-intro="Select Brand of the device like if it's iPhone 15, brand will be Apple"
                        data-step="7">
                        <div class="form-group">
                            {!! Form::label('brand_id', __('product.brand') . ':*') !!}
                            <button type="button" class="btn-add bg-white btn-flat px-1-add btn-modal add-brand-btn"
                                data-href="{{action('BrandController@create',['quick_add' => true])}}"
                                title="@lang('brand.add_brand')" data-container=".view_modal"><i
                                    class="fa fa-plus-circle text-primary fa-lg"></i></button>
                            <br>
                            <div class="input-group">
                                {!! Form::select('brand_id[]', $brands, !empty($duplicate_product->brand_id) ?
                                $duplicate_product->brand_id : null, ['placeholder' => __('messages.please_select'),
                                'class' => 'form-control select2 brand_id','required']); !!}
                            </div>
                        </div>
                    </div>

                    <div class="col-sm-2" data-title="Select Device"
                        data-intro="Select Device, device could be Mobile, Washing Machine, Laptop, Fridge etc."
                        data-step="8">
                        <div class="form-group">
                            {!! Form::label('device_id', __('repair::lang.device') . ':*') !!}
                            <button type="button" class="btn-add bg-white btn-flat btn-modal add-device-btn"
                                data-href="{{action('TaxonomyController@create')}}?type=device"
                                data-container=".category_modal"><i
                                    class="fa fa-plus-circle text-primary fa-lg"></i></button>
                            <br>
                            {!! Form::select('device_id[]', $devices, null, ['class' => 'form-control select2
                            device_id', 'required', 'placeholder' => __('messages.please_select')]); !!}
                        </div>
                    </div>

                    <div class="col-sm-2" data-title="Select Model"
                        data-intro="After Selecting Brand and Device, here you will select Model of the device. Example: If you have selected Apple as a Brand, Mobile as a Device, now you will select iPhone 14 as a Model."
                        data-step="9">
                        <div class="form-group">
                            {!! Form::label('device_model_id', __('repair::lang.device_model') . ':*') !!}
                            <button type="button" @if(!auth()->user()->can('brand.create')) disabled @endif
                                class="btn-add
                                bg-white btn-flat px-1-add btn-modal"
                                data-href="{{action('\Modules\Repair\Http\Controllers\DeviceModelController@create')}}"
                                id="add_device_model"><i class="fa fa-plus-circle text-primary fa-lg"></i></button>
                            <br>
                            {!! Form::select('device_model_id[]', [], null, ['class' => 'form-control select2
                            device_model_id','required',
                            'placeholder' => __('messages.please_select')]); !!}
                        </div>
                        <ul id="related-items">

                        </ul>
                    </div>
                    <div class="col-sm-2" data-title="Enter IMEI/Device ID/Serial No."
                        data-intro="Enter IMEI/Serial No. for the device you are taking. It will help you to identify the device at the time of Delivery."
                        data-step="10">
                        <div class="form-group">
                            {!! Form::label('serial_no', __('repair::lang.serial_no') . ':*') !!}
                            {!! Form::text('serial_no[]', null, ['class' => 'form-control', 'placeholder' =>
                            __('repair::lang.serial_no'), 'required']); !!}
                        </div>
                    </div>
                    <div class="col-md-2" data-title="Enter Password"
                        data-intro="If customer has set the password, ask them and enter here only if it's required for repairing."
                        data-step="11">
                        {{-- <div class="form-group">
                            {!! Form::label('security_pwd', __('repair::lang.repair_passcode') . ':') !!}
                            <div class="input-group">
                                {!! Form::text('security_pwd[]', null, ['class' => 'form-control', 'placeholder' =>
                                __('lang_v1.password'),'onchange'=>'openstatus()']); !!}
                                <span class="input-group-btn">
                                    <button type="button" class="btn  btn-flat" data-toggle="modal"
                                        data-target="#security_pattern" data-title="Make Pattern Lock"
                                        data-intro="Older device has Pattern Lock feature, if that's the case, ask the Pattern that he/she has setup for lock."
                                        data-step="12">
                                        <i class="fas fa-lock"></i> @lang('repair::lang.pattern_lock')
                                    </button>
                                </span>
                            </div>
                        </div> --}}
                        <div class="form-group">
                            {!! Form::label('security_pwd', __('repair::lang.repair_passcode') . ':') !!}
                            <div class="input-group">
                                {!! Form::text('security_pwd[]', null, ['class' => 'form-control', 'placeholder' =>
                                __('lang_v1.password')]) !!}
                                <span class="input-group-btn">
                                    <button type="button" class="btn btn-flat" data-toggle="modal"
                                        data-target="#security_pattern">
                                        <i class="fas fa-lock"></i> @lang('repair::lang.pattern_lock')
                                    </button>
                                </span>
                                {{-- Add the hidden input field for security pattern here --}}
                                {!! Form::hidden('security_pattern[]', null, ['class' => 'security_pattern_input']) !!}
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group" data-title="Enter Color of Device"
                            data-intro="In this field, you have to enter color of the device, which will help you to identify the device at the time of delivery."
                            data-step="15">
                            <label for="invoice_color">Device Color :*
                            </label>
                            <br>
                            {!! Form::text('invoice_color[]', null, ['class' => 'form-control', 'placeholder' => "Color","id"=>"invoice_color", "required"=>true]); !!}
                        </div>

                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4" data-title="Enter Problem in Device"
                    data-intro="Enter the issue or problem that customer has told you or you have identified about the device. Later on it can be edited if there is new problem that you find."
                    data-step="17">
                    <div class="form-group">
                        {!! Form::label('defects_1', __('repair::lang.problem_reported_by_customer') . ':') !!} <br>
                        {!! Form::textarea('defects[]', null, ['class' => 'tags-look defects', 'rows' => 3, 'id' =>
                        'defects_1']); !!}
                    </div>
                </div>

                    @if($Isprint==1)
                    @if(in_array('types_of_service', $enabled_modules) && !empty($types_of_service))
                    <div class="col-md-2">
                        <label for="types_of_service_id">{{__('Service Type') . ':*'}}
                        </label>
                        <div class="input-group">

                            <div class="form-group">
                                <div class="input-group">
                                    <span class="input-group-addon">
                                        <i class="fa fa-external-link-square-alt text-primary service_modal_btn"></i>
                                    </span>
                                    {!! Form::select('types_of_service_id[]', $types_of_service, 0, ['class' =>
                                    'form-control
                                    select2', 'id' => 'types_of_service_id', 'style' => 'width: 100%;','placeholder' =>
                                    __('messages.please_select')]); !!}


                                    {!! Form::hidden('types_of_service_price_group[]', null, ['id' =>
                                    'types_of_service_price_group']) !!}

                                    <span class="input-group-addon">
                                        @show_tooltip(__('lang_v1.types_of_service_help'))
                                    </span>

                                </div>
                                <small>
                                    <p class="help-block hide" id="price_group_text">@lang('lang_v1.price_group'):
                                        <span></span>
                                    </p>
                                </small>
                            </div>
                            <div class="modal fade types_of_service_modal" role="dialog"
                                aria-labelledby="gridSystemModalLabel"></div>


                        </div>
                    </div>
                    @endif
                    @endif



                    <div class="col-md-2" data-title="Select Expected Delivery Date"
                        data-intro="Select Date and Time when you expect it to be delivered or date and time by when you can think it can be repaired. <br> It's an expected time, its not neccessary that you deliver it at this time."
                        data-step="16">
                        <div class="form-group">
                            {!! Form::label('delivery_date', __('repair::lang.expected_delivery_date') . ':') !!}
                            <div class="input-group">
                                <span class="input-group-addon">
                                    <i class="fa fa-calendar"></i>
                                </span>
                                
                                {!! Form::text('delivery_date[]', null, ['class' => 'form-control delivery_date',
                                'readonly']); !!}
                                <span class="input-group-addon">
                                    <i class="fas fa-times-circle cursor-pointer clear_delivery_date"></i>
                                </span>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-2" data-title="Enter Estimated Cost"
                        data-intro="Here you can tell customer, the estimated cost for repairing based on the problem that you have identified. <br>Later, you can edit it. It's not the billing amount, just an amount for reference."
                        data-step="18">
                        <div class="form-group">

                            {!! Form::label('estimated_cost', __('repair::lang.estimated_cost') . ':') !!}

                            @if($Isprint==1)
                            {{-- <span id="est_cost_span">0</span> --}}
                            {!! Form::text('estimated_cost[]', null, ['class' => 'form-control input_number',
                            'id'=>'est_cost','placeholder' => __('repair::lang.estimated_cost'),'readonly'=>true]); !!}
                            @else
                            {{-- <span id="est_cost_span">0</span> --}}
                            {!! Form::text('estimated_cost[]', null, ['class' => 'form-control input_number',
                            'id'=>'est_cost','placeholder' => __('repair::lang.estimated_cost')]); !!}
                            @endif

                        </div>
                    </div>

                    @if ($Isprint)
                    <div class="col-md-2">
                        <div class="form-group">
                            {!! Form::label('advance_payment', 'Advance Paid:') !!}
                            @show_tooltip('Advance Paid by Customer')
                            <div class="input-group">
                                <!-- <span class="input-group-addon">
                        <i class="fa fa-money-bill"></i>
                    </span> -->
                                {!! Form::text('advance_payment[]', null, ['class' => 'form-control
                                input_number','placeholder' => __('Advance
                                Paid'),'id'=>'input_advance_pay','readonly'=>'true']); !!}

                            </div>
                        </div>
                    </div>
                    @else
                    <div class="col-md-2" data-title="Enter Advance Amount"
                        data-intro="If customer has given you advance, you can put it here. It will be managed at the time of billing."
                        data-step="19">
                        <div class="form-group">
                            {!! Form::label('advance_payment', 'Advance Paid:') !!}
                            @show_tooltip('Advance Paid by Customer')
                            <div class="input-group">
                                <!-- <span class="input-group-addon">
                        <i class="fa fa-money-bill"></i>
                        </span> -->
                                {!! Form::text('advance_payment[]', null, ['class' => 'form-control
                                input_number','placeholder' => __('Advance Paid')]); !!}

                            </div>
                        </div>
                    </div>
                    <div class="col-md-2" data-title="Select Technician"
                        data-intro="Here you can select Technician who will work or repair the device, for which you are creating this Jobsheet."
                        data-step="6" style="background:#e2ffd5">
                        @if(in_array('service_staff' ,$enabled_modules))
                        {{-- <div class="form-group">
                            {!! Form::label('service_staff', __('repair::lang.assign_service_staff') . ':') !!}
                            <br>
                            {!! Form::select('service_staff[]', $technecians, null, ['class' => 'form-control
                            select2
                            width-default', 'placeholder' => __('restaurant.select_service_staff'), 'tabindex'
                            =>
                            '3','onchange'=> 'openbrand()']); !!}
                        </div> --}}
                        {{-- <div class="form-group">
                            <label for="technecians">Technician</label>
                            <select name="technecians" id="technecians" class="form-control select2">
                                <option value="">{{ __('Select Technician') }}</option>
                                @foreach($technecians as $id => $name)
                                    <option value="{{ $id }}">
                                        {{ $name }} ({{ $todays_jobsheet_counts[$id] ?? 0 }} Jobsheet{{ ($todays_jobsheet_counts[$id] ?? 0) == 1 ? '' : 's' }} Assigned today)
                                    </option>
                                @endforeach
                            </select>
                        </div> --}}
                        <div class="form-group">
                            {!! Form::label('service_staff', __('repair::lang.assign_service_staff') . ':') !!}
                            <br>
                            <select name="service_staff[]" class="form-control select2 width-default" placeholder="{{ __('restaurant.select_service_staff') }}" tabindex="3" onchange="openbrand()">
                                <option value="">{{ __('Select Technician') }}</option>
                                @foreach($technecians as $id => $name)
                                    <option value="{{ $id }}">
                                        {{ $name }} ({{ $todays_jobsheet_counts[$id] ?? 0 }} {{ ($todays_jobsheet_counts[$id] ?? 0) == 1 ? '' : '' }} Assigned today)
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        
                        
                        @endif
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            {!! Form::label('product_configuration', __('repair::lang.product_configuration') . ':') !!}
                            <br>
                            {!! Form::textarea('product_configuration[]', null, ['class' => 'tags-look', 'rows' => 3]); !!}
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            {!! Form::label('product_condition', __('repair::lang.condition_of_product') . ':') !!} <br>
                            {!! Form::textarea('product_condition[]', null, ['class' => 'tags-look', 'rows' => 3]); !!}
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="device-container device-box" data-index="1" id="deviceForm_1">
                            <label>{{ __('Device Images') }}</label>
                        
                            <!-- Drag & Drop Area -->
                            <div class="drop-zone" id="dropzone-1">
                                <span class="drop-zone__prompt">Drop files here or click to upload</span>
                                <input type="file" name="device_images[1][]" class="drop-zone__input" id="device-image-input-1" multiple accept="image/*">
                            </div>
                        
                            <!-- Image Preview Area -->
                            <div class="image-preview-container d-flex flex-wrap" id="image-preview-container-1"></div>
                        
                            <!-- Capture from Webcam Button -->
                            <button type="button" class="btn btn-primary btn-sm mt-2 open-webcam" data-device-index="1">
                                Capture from Webcam
                            </button>
                        
                            <!-- Webcam Modal -->
                            <div class="modal fade" id="webcam-modal-1" tabindex="-1" role="dialog" aria-hidden="true">
                                <div class="modal-dialog modal-dialog-centered" role="document">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title">Capture Image</h5>
                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                <span aria-hidden="true">&times;</span>
                                            </button>
                                        </div>
                                        <div class="modal-body text-center">
                                            <video id="webcam-stream-1" autoplay class="border"></video>
                                            <canvas id="webcam-canvas-1" class="d-none"></canvas>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-success capture-image" data-device-index="1">
                                                Capture
                                            </button>
                                            <button type="button" class="btn btn-secondary" data-dismiss="modal">
                                                Close
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                    </div>                    
                    {{-- @if($partyRepairEnabled)
                        <div class="col-md-2">
                            <div class="form-group">
                                {!! Form::label('courier_company', __('Courier Company') . ':') !!} <br>
                                {!! Form::text('courier_company[]', null,['class' => 'form-control']) !!}
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                {!! Form::label('courier_consignment_code', __('Consignment Code') . ':') !!} <br>
                                {!! Form::text('courier_consignment_code[]', null,['class' => 'form-control']) !!}
                            </div>
                        </div>
                    @endif --}}
                    {{-- <div class="clearfix">
                    </div>
                    <div class="col-sm-3">
                        <div class="form-group">
                            {!! Form::label('images', __('repair::lang.document') . ':') !!}
                            {!! Form::file('images[]', ['id' => 'upload_job_sheet_image', 'accept' => implode(',', array_keys(config('constants.document_upload_mimes_types'))), 'multiple']); !!}
                            <small>
                                <p class="help-block">
                                    @lang('purchase.max_file_size', ['size' => (config('constants.document_size_limit') / 1000000)])
                                    @includeIf('components.document_help_text')
                                </p>
                            </small>
                        </div>
                    </div>                    --}}
                </div>
                    @endif
                    <div class="clearfix">
                    </div>
                    <div class="row">
                    <div class="col-md-12" data-title="Select Checklist"
                        data-intro="Checklist is added when you add device, checklist will help you to note the condition of the device like have scratch on Screen, Backside is broken etc. <br>You can also use it to mark the items that you are taking along with the device like charger, memory card, cover etc."
                        data-step="20" style="padding-left:2px;">

                        <div class="box-header with-border" style="padding-left:0px;">

                            <h5 class="box-title">
                                @lang('repair::lang.pre_repair_checklist'):
                            </h5>
                        </div>
                        <div class="box-body">
                            <div class="append_checklists"></div>
                        </div>

                    </div>
                    <div class="col-md-12" style="padding-left:2px;">

                        <div class="box-header with-border" style="padding-left:0px;">
                            <h5 class="box-title">
                                @lang('repair::lang.repair_est_cost'):
                            </h5>
                        </div>
                        <div class="box-body">
                            <div class="append_est_costs"></div>
                        </div>
                        <div class="row">
                            <div class="col-md-4 delete-btn">
                            </div>
                        </div>
                    </div>
                    {{--
                    <!-- <div class="col-md-2">
                            <div class="form-group">
                                <label>@lang('repair::lang.send_notification')</label><br>
                                <div class="checkbox-inline">
                                    <label class="cursor-pointer">
                                        <input type="checkbox" name="send_notification[]" value="sms">
                                        @lang('repair::lang.sms')
                                    </label>
                                </div>
                                <div class="checkbox-inline">
                                    <label class="cursor-pointer">
                                        <input type="checkbox" name="send_notification[]" value="email">
                                        @lang('business.email')
                                    </label>
                                </div>
                            </div>
                        </div> --> --}}
                </div>
            </div>
        </div>
    </div>
    <!--PRODUCT BOX-->

    {{-- More info part added to hid box --}}

    <div class="box box-solid">
        <div class="col-md-12" style="text-align:center" data-title="Select if you want to add more Information"
            data-intro="You can add more information like comment by Technician about the device.<br>It is an optional step. You can ignore it too."
            data-step="21">
            <button type="button" class="btn btn-primary more_btn2" data-target="#more_div"
                style="margin-bottom: 20px;margin-top: 20px;">@lang('lang_v1.more_info') <i
                    class="fa fa-chevron-down"></i></button>
        </div>

    </div>


    <!--More Info-->
    <div id="more_div" class="hide">
        <div class="box-body">

            <div class="row">

                {{-- product search and document added in hide box more info --}}
                <div class="col-12">
                    @if($Isprint==1)

                    @component('components.widget', ['class' => 'box-solid', 'title' => __('repair::lang.add_parts')])
                    <div class="row">
                        <div class="col-sm-8 col-sm-offset-2">
                            <div class="form-group">
                                <div class="input-group">
                                    <span class="input-group-addon">
                                        <i class="fa fa-search"></i>
                                        {{-- ['placeholder' => __('messages.please_select'), ] --}}
                                    </span>
                                    {!! Form::text('search_product', null, ['class' => 'form-control', 'id' =>
                                    'search_job_sheet_parts', 'placeholder' => __('repair::lang.search_parts')]); !!}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-10 col-sm-offset-1">
                            <div class="table-responsive">
                                <table class="table table-bordered table-striped table-condensed"
                                    id="job_sheet_parts_table">
                                    <thead>
                                        <tr>
                                            <th class="col-sm-4 text-center">
                                                @lang('repair::lang.part')
                                            </th>
                                            <th class="col-sm-2 text-center">
                                                @lang('sale.qty')
                                            </th>
                                            <th class="col-sm-2 text-center">
                                                @lang('price')
                                            </th>
                                            <th class="col-sm-2 text-center"><i class="fa fa-trash"
                                                    aria-hidden="true"></i></th>
                                        </tr>
                                    </thead>
                                    <tbody>

                                        @if(!empty($parts))
                                        @foreach($parts as $part)
                                        @include('repair::job_sheet.partials.job_sheet_part_row', ['variation_name' =>
                                        $part['variation_name'], 'unit' => $part['unit'], 'quantity' =>
                                        $part['quantity'], 'variation_id' => $part['variation_id'],'price'=>$part['']])
                                        @endforeach
                                        @endif
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    @endcomponent

                    @include('repair::job_sheet.partials.document')

                    @endif

                    @php
                    $accepted_files = implode(',', array_keys(config('constants.document_upload_mimes_types')));
                    @endphp
                </div>

                <div class="col-md-12">
                    <div class="form-group">
                        {!! Form::label('comment_by_ss', __('repair::lang.comment_by_ss') . ':') !!}
                        {!! Form::textarea('comment_by_ss', null, ['class' => 'form-control ', 'rows' => '3']); !!}
                    </div>
                </div>

                <div class="clearfix"></div>
                {{-- <div class="col-md-4">
                    <div class="form-group">
                        {!! Form::label('product_configuration', __('repair::lang.product_configuration') . ':') !!}
                        <br>
                        {!! Form::textarea('product_configuration', null, ['class' => 'tags-look', 'rows' => 3]); !!}
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        {!! Form::label('product_condition', __('repair::lang.condition_of_product') . ':') !!} <br>
                        {!! Form::textarea('product_condition', null, ['class' => 'tags-look', 'rows' => 3]); !!}
                    </div>
                </div> --}}


                <div class="clearfix"></div>

            </div>
            <!--More Info -->

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

    <div class="clearfix"></div>


    {{-- Total and substotal advanced payement shown here --}}
    @if (Agent::isDesktop())

    @if ($Isprint)

    <div class="col-12">
        <div class="row pos_form_totals" style="background: antiquewhite;">
            <div class="col-md-12">
                <table class="table table-condensed" style="margin: 10px;">
                    <tr>
                        <td class="notinmobile"><b>@lang('Advanced Payment'):</b>&nbsp;
                            <span class="total_quantity" id="adv_pay">0</span>
                        </td>
                        <td class="notinmobile">
                            <b>@lang('Sub Total'):</b> &nbsp;
                            <span class="price_total" id="part_price">0</span>
                        </td>

                        <td class="notinmobile">
                            <b>@lang('Service charge'):</b> &nbsp;
                            <span class="price_total" id="pack_charge">0</span>
                        </td>


                        <td class="notinmobile">
                            <b>@lang('Grand Total'):</b> &nbsp;
                            <span class="price_total" id="grand_total">0</span>
                        </td>

                    </tr>
                </table>
            </div>
        </div>
    </div>
    @endif

    @endif

    @if (Agent::isDesktop())

    @if($Isprint==0)
    <div class="col-sm-12" style="text-align: center; margin-bottom:3%;margin-left:18vh">
        <input type="hidden" name="submit_type" id="submit_type">

        <button type="submit" class="btn btn-primary submit_button" value="save_and_upload_docs"
            id="save_and_upload_docs" data-title="Create Jobsheet & Upload Doc/Image"
            data-intro="This button will create the Jobsheet and will take you to next page where you can upload the image of the device or document like Aadhar, if it's required."
            data-step="22">
            @lang('repair::lang.save_and_upload_docs')
        </button>



        <button type="submit" class="btn btn-primary submit_button" value="submit" id="save"
            data-title="Create Jobsheet"
            data-intro="This button will create the Jobsheet and will take you to Jobsheet detail page, where you can print the Jobsheet."
            data-step="23">
            @lang('messages.save')
        </button>
    </div>
    @else
    <div class="col-sm-12 text-right">
        <input type="hidden" name="submit_type" id="submit_type">


        <button type="submit" class="btn btn-primary submit_button" value="submit" id="save">
            @lang('messages.save')
        </button>
    </div>
    @endif
    @else

    @if($Isprint==0)
    <div class="col-sm-12 text-center">
        <input type="hidden" name="submit_type" id="submit_type">

        {{-- <button type="submit" class="btn btn-success submit_button" value="save_and_add_parts"
            id="save_and_add_parts">
            @lang('repair::lang.save_and_add_parts')
        </button> --}}

        <button type="submit" class="btn btn-info submit_button" value="save_and_upload_docs" id="save_and_upload_docs">
            @lang('repair::lang.save_and_upload_docs')
        </button>



        <button type="submit" class="btn btn-primary submit_button" value="submit" id="save">
            @lang('messages.save')
        </button>
    </div>
    @else
    <div class="col-sm-12 text-center">
        <input type="hidden" name="submit_type" id="submit_type">


        <button type="submit" class="btn btn-primary submit_button" value="submit" id="save">
            @lang('messages.save')
        </button>
    </div>
    @endif
    @endif
    {!! Form::close() !!}
    <!-- /form close -->
    <div class="modal fade contact_modal" role="dialog" aria-labelledby="gridSystemModalLabel">
        @include('contact.create', ['quick_add' => true])
    </div>

    <div class="modal fade category_modal" role="dialog" aria-labelledby="gridSystemModalLabel">
    </div>
    <div class="modal fade" id="device_model_modal" role="dialog" aria-labelledby="myModalLabel"></div>
    <div class="modal fade brands_modal" role="dialog" aria-labelledby="gridSystemModalLabel">
    </div>


    <!--Edit price Modal -->
    <div class="modal fade" id="priceeditModel" role="dialog" aria-labelledby="priceeditModelLabel" aria-hidden="true">
        <div class="modal-dialog modal-sm" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    Edit Price

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <input type="text" class="form-control" id="product_price">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">save</button>
                    {{-- <button type="button" class="btn btn-primary" data-dismiss="modal">Save </button> --}}
                </div>
            </div>
        </div>
    </div>


</section>
@stop
@section('css')
@include('repair::job_sheet.tagify_css')
@stop
@section('javascript')
<script src="{{ asset('js/pos.js?v=' . $asset_v) }}"></script>
{{-- <script>
    introJs().start();
</script> --}}

<script type="text/javascript">
    let pevalue;
    function customeropen() {
        $('select[name^="contact_id"]').focus();
    }

    window.onload = customeropen();

    function opentech() {

        $('select[name^="service_staff"]').focus();
        
      };
      
      function devicemodel() {

        $('select[name^="device_model_id"]').focus();
        
      };

      function opencustomer(){
        $('select[name^="contact_id"]').focus();
      }

      function openbrand(){
        $('select[name^="brand_id"]').focus();
      }

      function openstatus(){
        $('select[name^="status_id"]').focus();
      }
      function serialinput(){
        document.getElementByname('serial_no').focus();

      }

        Dropzone.autoDiscover = false;
        $(function () {
            var file_names = [];
            $("div#imageUpload").dropzone({
                url: base_path+'/post-document-upload',
                paramName: 'file',
                uploadMultiple: true,
                autoProcessQueue: true,
                timeout:600000, //10 min
                acceptedFiles: '{{$accepted_files}}',
                maxFiles: 4,
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(file, response) {
                    if (response.success) {
                        toastr.success(response.msg);
                        file_names.push(response.file_name);
                        $('input#images').val(JSON.stringify(file_names));
                    } else {
                        toastr.error(response.msg);
                    }
                },
            });
    
            $(document).on('click', '.delete_media', function (e) {
                e.preventDefault();
                var url = $(this).data('href');
                var this_btn = $(this);
                swal({
                    title: LANG.sure,
                    icon: "warning",
                    buttons: true,
                    dangerMode: true,
                }).then((confirmed) => {
                    if (confirmed) {
                        $.ajax({
                            method: 'GET',  
                            url: url,
                            dataType: 'json',
                            success: function(result) {
                                if(result.success == true){
                                    this_btn.closest('tr').remove();
                                    toastr.success(result.msg);
                                } else {
                                    toastr.error(result.msg);
                                }
                            }
                        });
                    }
                });
            });
        });
</script>
<script type="text/javascript">
    var Iserror=false;
        $(document).ready( function() {
            $('.submit_button').click( function(){
                $('#submit_type').val($(this).attr('value'));      
            });
            $('form#job_sheet_form').validate({
                errorPlacement: function(error, element) {
                    if (element.parent('.iradio_square-blue').length) {
                        $('.loader').removeClass('d-block')      
                        $('.loader').addClass('d-none') 
                        error.insertAfter($(".radio_btns"));      
                    } else if (element.hasClass('status')) {
                        $('.loader').removeClass('d-block')      
                        $('.loader').addClass('d-none') 
                        error.insertAfter(element.parent());
                    } else {
                        $('.loader').removeClass('d-block')      
                        $('.loader').addClass('d-none') 
                        error.insertAfter(element);

                    }
                },
                submitHandler: function(form) {
                    let adv_pay=parseInt($('#input_advance_pay').val())
                    let est_cost=parseInt($('#est_cost').val())
                    if(adv_pay>est_cost){
                        toastr.error('Advanced amount must not be greater than Estimated Amount');
                    }else{
                        form.submit();
                        $('.submit_button').prop('disabled','true');
                        setTimeout(() => {
                            $('.loader').removeClass('d-block')      
                                $('.loader').addClass('d-none') 
                        }, 5000);
                    }
                }
            });

            var data = [{
              id: "",
              text: '@lang("messages.please_select")',
              html: '@lang("messages.please_select")',
              is_complete : '0',
            }, 
            @foreach($repair_statuses as $repair_status)
                {
                id: {{$repair_status->id}},
                is_complete : '{{$repair_status->is_completed_status}}',
                @if(!empty($repair_status->color))
                    text: '<i class="fa fa-circle" aria-hidden="true" style="color: {{$repair_status->color}};"></i> {{$repair_status->name}}',
                    title: '{{$repair_status->name}}'
                @else
                    text: "{{$repair_status->name}}"
                @endif
                },
            @endforeach
            ];

            $("select#status_id").select2({
                data: data,
                escapeMarkup: function(markup) {
                    return markup;
                },
                templateSelection: function (data, container) {
                    $(data.element).attr('data-is_complete', data.is_complete);
                    return data.text;
                }
            });

            @if(!empty($default_status))
                $("select#status_id").val({{$default_status}}).change();
            @endif

//till here
var activeDeviceForm = null; // To keep track of which form triggers the modal

// Initialize the pattern lock
var lock = new PatternLock("#pattern_container", {
        onDraw: function(pattern) {
            if (activeDeviceForm) {
                activeDeviceForm.find('.security_pattern_input').val(pattern); // Store the drawn pattern
                console.log('Pattern drawn for:', activeDeviceForm.attr('id'), 'Pattern:', pattern);
            }
        },
        enableSetPattern: true
    });

    // When the "Pattern Lock" button is clicked, store the form that triggered the modal
    $(document).on('click', '.btn[data-target="#security_pattern"]', function() {
        activeDeviceForm = $(this).closest('.device-box'); // Store the device form that opened the modal

        var currentPattern = activeDeviceForm.find('.security_pattern_input').val(); // Get the existing pattern for the form

        // Reset the pattern in the modal (clear the visual pattern)
        lock.reset();

        // If the form already has a saved pattern, set it on the pattern lock
        if (currentPattern) {
            lock.setPattern(currentPattern); // This is the part where you set the previously drawn pattern
            console.log('Setting pattern for form:', activeDeviceForm.attr('id'), 'Pattern:', currentPattern);
        }
    });

    // When the "Save" button in the modal is clicked
    $(document).on('click', '.save-pattern-btn', function() {
        // Get the drawn pattern from the lock
        var pattern = lock.getPattern();

        // Ensure the drawn pattern is correctly saved in the input field of the active form
        if (activeDeviceForm) {
            activeDeviceForm.find('.security_pattern_input').val(pattern);

            // Print the saved pattern in the console
            console.log('Saved pattern for device:', activeDeviceForm.attr('id'), 'Pattern:', pattern);
        }

        // Close the modal (optional)
        $('#security_pattern').modal('hide');
    });
            
            // When brand is changed
            // Handle brand change
$(document).on('change', '.brand_id', function() {
    var currentForm = $(this).closest('.device-box'); // Get the specific form
    var selectedBrand = $(this).val();
    
    console.log('Selected brand:', selectedBrand);  // Log the selected brand
    currentForm.find('select.device_id').focus(); // Focus on the device_id in the same form
    currentForm.find(".related-items").empty(); // Clear related items for this specific form
});

            $(document).ready(function() {
                // Define the getModelForDevice function
                function getModelForDevice(currentForm, newModelId = null) {
                    var device_id = currentForm.find('.device_id').val();
                    var brand_id = currentForm.find('.brand_id').val();

                    if (!device_id || !brand_id) {
                        console.error('Device ID or Brand ID is missing!');
                        return;
                    }

                    $.ajax({
                        method: 'GET',
                        url: '/repair/get-device-models',
                        dataType: 'html',
                        data: { device_id: device_id, brand_id: brand_id },
                        success: function(result) {
                            currentForm.find('select.device_model_id').html(result);
                            currentForm.find('select.device_model_id').select2();

                            // Automatically select the new model if newModelId is provided
                            if (newModelId) {
                                currentForm.find('select.device_model_id').val(newModelId).trigger('change');
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('Error fetching models:', error);
                        }
                    });
                }

                // Track the form that triggered the model addition
                let activeFormForModel = null;

                // "Add Device Model" button click handler
                $(document).on('click', '#add_device_model', function () {
                    activeFormForModel = $(this).closest('.device-box');
                    var url = $(this).data('href');
                    $.ajax({
                        method: 'GET',
                        url: url,
                        dataType: 'html',
                        success: function(result) {
                            $('#device_model_modal').html(result).modal('show');
                        }
                    });
                });

                // Handle model form submission and refresh the specific device model dropdown
                $(document).on('submit', 'form#device_model', function(e) {
                    e.preventDefault();
                    var url = $('form#device_model').attr('action');
                    var method = $('form#device_model').attr('method');
                    var data = $('form#device_model').serialize();

                    $.ajax({
                        method: method,
                        dataType: "json",
                        url: url,
                        data: data,
                        success: function(result) {
                            if (result.success) {
                                toastr.success(result.msg);
                                $('#device_model_modal').modal("hide");

                                // Refresh only the dropdown for the form that triggered the addition and select the new model
                                if (activeFormForModel && result.data && result.data.id) {
                                    getModelForDevice(activeFormForModel, result.data.id);
                                    activeFormForModel = null; // Reset for next usage
                                }
                            } else {
                                toastr.error(result.msg);
                            }
                        }
                    });
                });

                // Change handler for .device_id to refresh device models dynamically
                $(document).on('change', '.device_id', function() {
                    var currentForm = $(this).closest('.device-box'); // Get the form context
                    getModelForDevice(currentForm); // Call the function with the specific form
                });
            });


           
            function getModelRepairChecklists(deviceFormCount) {
                var deviceFormId = 'deviceForm_' + deviceFormCount;
                var arraycount = deviceFormCount-1;
                var deviceModelId = $('#' + deviceFormId).find('select[name^="device_model_id"]').val(); // Get the correct device model ID
                if (deviceModelId) {
                    $.ajax({
                        method: 'GET',
                        url: '/repair/models-repair-checklist',
                        dataType: 'html',
                        data: { model_id: deviceModelId, arraycount: arraycount }, // Send the selected model_id to the server
                        success: function (result) {
                            // Update only the checklist for the corresponding form
                            var checklistContainer = $('#' + deviceFormId).find('.append_checklists');
                            // Append checklist to the correct form's append_checklists container
                            checklistContainer.html(result);
                        },
                        error: function (xhr, status, error) {
                            console.log("Error in fetching checklist: ", error);
                        }
                    });
                }
            }

            function getModelRepairEstCosts(deviceFormCount) {
                var deviceFormId = 'deviceForm_' + deviceFormCount;
                var data = {
                    model_id: $('#' + deviceFormId).find('select[name^="device_model_id"]').val(),
                };

                $.ajax({
                    method: 'GET',
                    url: '/repair/models-repair-est-cost',
                    dataType: 'html',
                    data: data,
                    success: function(result) {
                        $('#' + deviceFormId).find(".append_est_costs").html(result);
                    }
                });
            }

            $(document).on('change', 'select[name^="device_model_id"]', function () {
                var deviceFormId = $(this).closest('.device-box').attr('id'); // Get the form ID
                var deviceFormCount = deviceFormId.split('_')[1]; // Extract the form count
                            if (deviceFormId) {
                                // Pass the form count to the getModelRepairChecklists function
                                getModelRepairChecklists(deviceFormCount);
                                getModelRepairEstCosts(deviceFormCount);
                            } else {
                                console.error('Device form ID is undefined');
                            }
                        });


            $('#service_type').on('change', function() {
                var selectedValue = $(this).val();

                if (selectedValue === 'pick_up' || selectedValue === 'on_site') {
                    $("div.pick_up_onsite_addr").show();
                } else {
                    $("div.pick_up_onsite_addr").hide();
                }
            });

            //initialize file input
            $('#upload_job_sheet_image').fileinput({
                showUpload: false,
                showPreview: false,
                browseLabel: LANG.file_browse_label,
                removeLabel: LANG.remove
            });

           
        });
        $('.more_btn2').click(function(){
            $($(this).data('target')).toggleClass('hide');
        });
        $('.add_parts').click(function(){
            $($(this).data('target')).toggleClass('hide');
        });
</script>


<script type="text/javascript">
    var Iserror = false;
    let activeFormForDevice = null; // Declare the variable to track the active device form

    $(document).ready(function() {
        // Existing code...

        // Click event handler for the "Add Device" button
        $(document).on('click', '.add-device-btn', function() {
            activeFormForDevice = $(this).closest('.device-box');
        });

        // AJAX form submission for adding a new device
        $(document).on('submit', 'form#category_add_form', function(e) {
            e.preventDefault();
            var form = $(this);
            var data = form.serialize();

            $.ajax({
                method: 'POST',
                url: form.attr('action'),
                dataType: 'json',
                data: data,
                beforeSend: function(xhr) {
                    __disable_submit_button(form.find('button[type="submit"]'));
                },
                success: function(result) {
                    if (result.success === true) {
                        var newOption = new Option(result.data.name, result.data.id, true, true);
                        if (activeFormForDevice) {
                            activeFormForDevice.find('select.device_id')
                                .append(newOption)
                                .val(result.data.id)
                                .trigger('change');
                        }
                        activeFormForDevice = null; // Reset the variable

                        $('div.category_modal').modal('hide');
                        toastr.success(result.msg);
                        // If you have a category table, reload it
                        if (typeof category_table !== 'undefined') {
                            category_table.ajax.reload();
                        }
                    } else {
                        toastr.error(result.msg);
                    }
                },
            });
        });

        // Change handler for device select field to update device models
        $(document).on('change', '.device_id', function() {
            var currentForm = $(this).closest('.device-box');
            getModelForDevice(currentForm);
        });

        // Function to get device models for the selected device and brand
        function getModelForDevice(currentForm, newModelId = null) {
            var device_id = currentForm.find('.device_id').val();
            var brand_id = currentForm.find('.brand_id').val();

            if (!device_id || !brand_id) {
                console.error('Device ID or Brand ID is missing!');
                return;
            }

            $.ajax({
                method: 'GET',
                url: '/repair/get-device-models',
                dataType: 'html',
                data: { device_id: device_id, brand_id: brand_id },
                success: function(result) {
                    currentForm.find('select.device_model_id').html(result);
                    currentForm.find('select.device_model_id').select2();

                    // Automatically select the new model if newModelId is provided
                    if (newModelId) {
                        currentForm.find('select.device_model_id').val(newModelId).trigger('change');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error fetching models:', error);
                }
            });
        }

        // Existing code...

        // Ensure the device select field has the class 'device_id' and 'select2' initialized
        $('.device_id').select2();

        // Rest of your existing code...
    });

</script>

<script type="text/javascript">
    $(document).on('submit', 'form#status_form', function(e){
            e.preventDefault();
            $(this).find('button[type="submit"]').attr('disabled', true);
            var data = $(this).serialize();

            $.ajax({
                method: $(this).attr('method'),
                url: $(this).attr("action"),
                dataType: "json",
                data: data,
                success: function(result){
                    if(result.success == true){
                        let newOption = new Option(result.data.name, result.data.brand_id,result.data.id, true, true);
                    $('#status_id')
                    .append(newOption)
                    .trigger('change');

                        $('div.view_modal').modal('hide');
                        toastr.success(result.msg);
                        status_table.ajax.reload();
                    } else {
                        toastr.error(result.msg);
                    }
                }
            });
        });
</script>
<!--Added to refresh brand-->
<script type="text/javascript">
    let activeFormForBrand = null;

// When "Add Brand" button is clicked
$(document).on('click', '.add-brand-btn', function() {
    activeFormForBrand = $(this).closest('.device-box');
});

// On brand form submission
$(document).on('submit', 'form#quick_add_brand_form', function(e){
    e.preventDefault();
    $(this).find('button[type="submit"]').attr('disabled', true);

    var fd = new FormData(this);

    $.ajax({
        method: $(this).attr('method'),
        url: $(this).attr("action"),
        dataType: "json",
        data: fd,
        contentType: false,
        processData: false,
        success: function(result){
            if(result.success == true){
                var newOption = new Option(result.data.name, result.data.id, true, true);
                if (activeFormForBrand) {
                    activeFormForBrand.find('select.brand_id')
                        .append(newOption)
                        .val(result.data.id)
                        .trigger('change');
                }
                activeFormForBrand = null; // Reset after use

                $('div.view_modal').modal('hide');
                toastr.success(result.msg);
                if (typeof brand_table !== 'undefined') {
                    brand_table.ajax.reload();
                }
            } else {
                toastr.error(result.msg);
            }
        }
    });
});


</script>

<script type="text/javascript">
    $(document).ready( function(){
		$('#search_job_sheet_parts')
            .autocomplete({
                source: function(request, response) {
                    $.getJSON(
                        '/products/list',
                        { term: request.term },
                        response
                    );
                },
                minLength: 2,
                response: function(event, ui) {
                    if (ui.content.length == 1) {
                        ui.item = ui.content[0];
                        $(this)
                                .data('ui-autocomplete')
                                ._trigger('select', 'autocompleteselect', ui);
                        $(this).autocomplete('close');
                    } else if (ui.content.length == 0) {
                        swal(LANG.no_products_found);
                    }
                },
                select: function(event, ui) {
                   job_sheet_parts_row(ui.item.variation_id);
                },
            })
            .autocomplete('instance')._renderItem = function(ul, item) {
	            var string = '<div>' + item.name;
	                if (item.type == 'variable') {
	                    string += '-' + item.variation;
	                }
	                string += ' (' + item.sub_sku + ') </div>';
                   
	                return $('<li>')
	                    .append(string)
	                    .appendTo(ul);
        	};

       	//initialize editor
        tinymce.init({
            selector: 'textarea#email_body',
        });

        $('#send_sms').change(function() {
            if ($(this). is(":checked")) {
                $('div.sms_body').fadeIn();
            } else {
                $('div.sms_body').fadeOut();
            }
        });

        $('#send_email').change(function() {
            if ($(this). is(":checked")) {
                $('div.email_template').fadeIn();
            } else {
                $('div.email_template').fadeOut();
            }
        });

        if ($('#status_id_modal').length) {
            
            $("#sms_body").val($("#status_id_modal :selected").data('sms_template'));
            $("#email_subject").val($("#status_id_modal :selected").data('email_subject'));
            tinymce.activeEditor.setContent($("#status_id_modal :selected").data('email_body'));  
        }

        $('#status_id_modal').on('change', function() {
            var sms_template = $(this).find(':selected').data('sms_template');
            var email_subject = $(this).find(':selected').data('email_subject');
            var email_body = $(this).find(':selected').data('email_body');

            $("#sms_body").val(sms_template);
            $("#email_subject").val(email_subject);
            tinymce.activeEditor.setContent(email_body);

            if ($('#status_modal .mark-as-complete-btn').length) {
                if ($(this).find(':selected').data('is_completed_status') == 1) 
                {
                    $('#status_modal').find('.mark-as-complete-btn').removeClass('hide');
                    $('#status_modal').find('.mark-as-incomplete-btn').addClass('hide');
                } else {
                    $('#status_modal').find('.mark-as-complete-btn').addClass('hide');
                    $('#status_modal').find('.mark-as-incomplete-btn').removeClass('hide');
                }
            }
        });
	});
let availabe_data=[];
	function job_sheet_parts_row(variation_id) {
		var row_index = parseInt($('#product_row_index').val());
	    var location_id = $('select#location_id').val();
        let current_vid=$('.current_variation_id').val();

        if(!availabe_data.includes(variation_id))
        {
            availabe_data.push(variation_id)

	    $.ajax({
	        method: 'POST',
	        url: "{{action('\Modules\Repair\Http\Controllers\JobSheetController@jobsheetPartRow')}}",
	        data: { variation_id: variation_id },
	        success: function(result) {
                if (result==0) {
                    toastr.error('Item out of stock');
                    return false;
                }
	            $('table#job_sheet_parts_table tbody').append(result);
	            $('input#search_job_sheet_parts').val('')
	            $('input#search_job_sheet_parts')
                        .focus()
                        .select();
	            // for price calculation
                    part_amount=parseInt($(`.part_price${variation_id}`).val());
                    part_qty=parseInt($(`.part_price${variation_id}`).data('qty'));
                    total_part_amount+=part_amount
                    total_part_qty+=part_qty
                    let charge=$('#pack_charge').html()

                    loadAllamount(total_part_qty,total_part_amount,charge)
	        },
	    });
    }else{
        toastr.error('Item already added');

    }

	}
     
	$(document).on('click', '.remove_product_row', function(){
        // checking the id qty price and then subtracting 
        let vid=$(this).data('id')
        let price=$('#qty'+vid).attr('data-totalprice')
       let charge=$('#pack_charge').html()
    //    total_part_qty=total_part_qty-qty
       total_part_amount= total_part_amount-price
        loadAllamount(total_part_qty,total_part_amount,charge)
		$(this).closest('tr').remove();
        
	})




// calling function on chaning qttotalpricefocusy 

var total_part_amount=0;
var total_part_qty=0;
$(document).on('keyup', '.input_quantity', function(){
        
        let qty=$(this).val()
        let totalprice=parseInt($(this).attr('data-totalprice'))
        let unitprice=parseInt($(this).attr('data-price'))
       let charge=$('#pack_charge').html()
       let $price=0;
       if (qty.trim() !==null && qty.trim() !=='' && qty.trim().length>0) {

        let preqty=$(this).attr('data-preqty')
                        qty=parseInt(qty)
    $price=qty*unitprice;
      total_part_qty=total_part_qty-preqty+qty
    total_part_amount= parseInt(total_part_amount-totalprice+$price)
    loadAllamount(total_part_qty-1,total_part_amount,charge)
    $(this).attr('data-preqty',qty)
    $(this).attr('data-totalprice',parseInt($price))

       }
})



	$(document).on('click', '#submit_add_part_form', function(e){
		$('form#add_part_form').submit();
	})

    var val=0

    // fetching and showing  package price 
$(document).on('click','.types_of_service_modal .btn-default',function(){
    val= $('#packing_charge').val()
    setTimeout(() => {
    loadAllamount(total_part_qty,total_part_amount,val)
}, 500); 
})




$(document).on('keyup','#packing_charge',function(){
        setInterval(() => {
            val= $(this).val()
    loadAllamount(total_part_qty,total_part_amount,val)
        }, 500);
    })

function loadAllamount(part_qty,part_price,pack_charge){
    $('#part_qty').html(parseInt(part_qty))
    $('#part_price').html(parseInt(part_price))
    $('#pack_charge').html(parseInt(pack_charge))
    $('#grand_total').html(parseInt(pack_charge)+parseInt(part_price))
    $('#est_cost_span').html(parseInt(pack_charge)+parseInt(part_price))
    $('#est_cost').val(parseInt(pack_charge)+parseInt(part_price))
}

$('#input_advance_pay').keyup(function(){
    $('#adv_pay').html($(this).val())
})

$('.submit_button').click(function(){
    $('.loader').removeClass('d-none')      
    $('.loader').addClass('d-block')
 

  
})



// disable and active adavnced payment 

$('#types_of_service_id').on('change',function(){
    let id=$(this).val();
if(id.trim()){
   let val=$('#input_advance_pay').prop('readonly','')
}else{
   $('#input_advance_pay').prop('readonly','true')

}

});




// update price onthe basis of change price in modal 

$(document).on('click','.edit_price',function(){
let vid=$(this).data('vid')
let price=$(this).data('price')
let name=$(this).data('name')
$('.product_name').html(name)
$('#product_price').val(parseInt(price))
$('#product_price').attr('data-id',vid)

// loadAllamount(part_qty,part_price,pack_charge)

})

$(document).on('keyup','#product_price',function(){
    let val=$(this).val()
    let vid=$(this).attr('data-id')
let pretotal=parseInt($('#qty'+vid).attr('data-totalprice'));

   $('#'+vid).val(val);
   $('#price'+vid).html(val);
   $('#qty'+vid).attr('data-price',val);
   let qty=$('#qty'+vid).val();
let totalp=parseInt(qty*val);
$('#qty'+vid).attr('data-totalprice',totalp);

total_part_amount=total_part_amount-pretotal+totalp;
val= $('#pack_charge').html()
loadAllamount(total_part_qty,total_part_amount,val)


})

</script>
<script>
    var tour = new Tour({
  steps: [
  {
    element: "#my-element",
    title: "Title of my step",
    content: "Content of my step"
  },
  {
    element: "#my-other-element",
    title: "Title of my step",
    content: "Content of my step"
  }
]});
</script>
<script>
    $(document).ready(function() {
    var deviceFormCount = 1; 

    function initDatepicker() {
        $('.delivery_date').daterangepicker({
            singleDatePicker: true,
            timePicker: true,
            timePickerIncrement: 15,
            timePicker24Hour: false, // Ensures 12-hour format with AM/PM
            locale: {
                format: 'YYYY-MM-DD h:mm A' // Defines the date and time format
            },
            startDate: moment()
        });
    }

    function reinitializeComponents(formElement) {
        initDatepicker();
        formElement.find('.datetimepicker').datetimepicker({
            format: moment_date_format + ' ' + moment_time_format,
            ignoreReadonly: true,
        });

        // Check if formElement is the original #deviceForm_1
    if (formElement.attr('id') !== 'deviceForm_1') {
        formElement.find('.defects').each(function() {
            var defectsTextarea = this;
            
            // Destroy existing Tagify instance
            if (defectsTextarea.tagify) {
                defectsTextarea.tagify.destroy();
            }

            // Reinitialize Tagify
            new Tagify(defectsTextarea, {
                whitelist: {!! json_encode($defects) !!},
                maxTags: 100,
                dropdown: {
                    maxItems: 100,
                    classname: "tags-look",
                    enabled: 0,
                    closeOnSelect: false
                }
            }, {
                wrapper: defectsTextarea.parentElement
            });
        });
    } else {
        // Initialize Tagify for original #deviceForm_1
        $('#defects_1').each(function() {
            var defectsTextarea = this;
            console.log("Tagify",defectsTextarea);
            
            // Destroy existing Tagify instance
            if (defectsTextarea.tagify) {
                defectsTextarea.tagify.destroy();
            }

            // Reinitialize Tagify
            new Tagify(defectsTextarea, {
                whitelist: {!! json_encode($defects) !!},
                maxTags: 100,
                dropdown: {
                    maxItems: 100,
                    classname: "tags-look",
                    enabled: 0,
                    closeOnSelect: false
                }
            }, {
                wrapper: defectsTextarea.parentElement
            });
        });
    }
    // Update checkbox names and IDs
    var deviceId = parseInt(formElement.attr('id').replace('deviceForm_', '')) || 0;
    formElement.find('input[type="checkbox"]').each(function() {
        var originalName = $(this).attr('name');
        $(this).attr('name', 'repair_checklist[' + deviceId + '][' + $(this).val() + ']');
        $(this).attr('id', 'checklist_device_' + deviceId + '_' + $(this).val());
    });
    }

    // $('#addNewDeviceBtn').click(function() {
    //     deviceFormCount++;
    //     var deviceFormId = 'deviceForm_' + deviceFormCount; // Construct the deviceFormId
    //     console.log('Current deviceFormId:', deviceFormId);
    //     var activeDeviceForm = null;

    //     $('#deviceForm_1').find('.select2').each(function() {
    //         if ($(this).data('select2')) {
    //             $(this).select2('destroy');  
    //         }
    //     });

    //     var newDeviceForm = $('#deviceForm_1').clone().attr('id', 'deviceForm_' + deviceFormCount);
    //     var activeDeviceForm = null; // Track the active device form
    //     // Append a unique hidden input for the pattern to the cloned form

    //     var patternInput = $('<input type="hidden" name="security_pattern[' + (deviceFormCount - 1) + ']" id="security_pattern_' + deviceFormCount + '" class="security_pattern_input">');
    //     let newFormId = `deviceForm_${deviceFormCount}`;

    //         newDeviceForm.attr('id', newFormId);

    //     // Update drop zone ID
    //     let newDropZone = newDeviceForm.find('.drop-zone');
    //         newDropZone.attr('id', `dropzone-${deviceFormCount}`);

    //     // Update file input ID
    //     let newInput = newDeviceForm.find('.drop-zone__input');
    //     newInput.attr('id', `device-image-input-${deviceFormCount}`);
    //     newInput.val(''); // Clear any previously selected files

    //     // Clear old thumbnails
    //     newDeviceForm.find('.drop-zone__thumb').remove();
    //     newDeviceForm.find('.drop-zone__prompt').html("Drop files here or click to upload");
    //         // Correctly replace IDs
    //     newDeviceForm.find('[id]').each(function() {
    //         var originalId = $(this).attr('id');
    //         if (originalId && originalId.match(/_1$/)) { // Only replace _1 at the end of the ID
    //             var newId = originalId.replace('_1', '_' + deviceFormCount);
    //             $(this).attr('id', newId);
    //         }
    //     });

    //     // Correctly replace name attributes
    //     newDeviceForm.find('input, textarea, select').each(function() {
    //         var originalName = $(this).attr('name');
    //         if (originalName) {
    //             var newName = originalName.replace(/\[\d+\]/g, '[' + (deviceFormCount - 1) + ']');
    //             $(this).attr('name', newName);

    //             // Clear the value of input and textarea fields
    //             $(this).val('');
    //         }
    //     });
    //     // Remove Tagify's HTML structure from cloned form
    //     newDeviceForm.find('tags').remove();  // This removes any pre-existing tags from Device 1
    //     newDeviceForm.find('.tagify').remove();  // Removes any leftover Tagify container

    //     // Remove cloned checklist content
    //     newDeviceForm.find('.append_checklists').empty(); // Clear out any checklist that might have been cloned

    //     // Ensure unique IDs for the checklist section
    //     newDeviceForm.find('.append_checklists').attr('id', 'checklist_' + deviceFormCount);

    //     var deleteButton = '<button type="button" class="btn btn-danger remove-device-btn">Delete</button>';
    //     newDeviceForm.find('.delete-btn').html(deleteButton); 

    //     $('#devicesContainer').append(newDeviceForm);

    //     newDeviceForm.find('.select2').select2({
    //         width: 'resolve' 
    //     });

    //     reinitializeComponents(newDeviceForm);
    //     initializeTagifyForFields(newDeviceForm);
    //     $('#devicesContainer').append(newDeviceForm);
    //     setupDropzone(newFormId);

    // });
    $('#addNewDeviceBtn').click(function () {
    deviceFormCount++;
    let deviceCount = deviceFormCount;


    var deviceFormId = 'deviceForm_' + deviceFormCount;
    console.log('Current deviceFormId:', deviceFormId);

    $('#deviceForm_1').find('.select2').each(function () {
        if ($(this).data('select2')) {
            $(this).select2('destroy');
        }
    });

    var newDeviceForm = $('#deviceForm_1').clone().attr('id', deviceFormId);

    // Update drop zone ID
    // Update drop zone ID
    let newDropZone = newDeviceForm.find('.drop-zone');
    newDropZone.attr('id', `dropzone-${deviceFormCount}`);

    // Update file input ID and name
    // let newInput = newDeviceForm.find('.drop-zone__input');
    // newInput.attr('id', `device-image-input-${deviceFormCount}`);
    // // newInput.attr('name', `device_images[${deviceCount}][]`); // Assign unique name for image input
    // // newInput.attr('name', `device_images[${deviceFormCount - 1}][]`);
    // // newInput.attr('name', `device_images[${deviceCount}][]`);
    // newInput.attr('name', `device_images[${deviceFormCount}][]`);


    // newInput.val(''); // Clear previous selected files
    let newInput = newDeviceForm.find('.drop-zone__input');
    newInput.attr('id', `device-image-input-${deviceCount}`);
    // newInput.attr('name', `device_images[${deviceCount}][]`);  // ✅ Corrected name assignment
    newInput.attr('name', `device_images[${$('.device-box').length}][]`);

    newInput.val('');

    // Clear old thumbnails
    newDeviceForm.find('.image-preview-container').empty();
    newDeviceForm.find('.drop-zone__prompt').html("Drop files here or click to upload");

    // $('#devicesContainer').append(newDeviceForm);

    // setTimeout(() => {
    //     setupDropzone(newFormId, deviceCount); // Reinitialize Dropzone for the new device
    // }, 100);

    // Ensure unique IDs for elements inside the new form
    newDeviceForm.find('[id]').each(function () {
        var originalId = $(this).attr('id');
        if (originalId && originalId.match(/_1$/)) {
            var newId = originalId.replace('_1', `_${deviceFormCount}`);
            $(this).attr('id', newId);
        }
    });

    // Ensure unique names for input fields
    newDeviceForm.find('input, textarea, select').each(function () {
        var originalName = $(this).attr('name');
        if (originalName) {
            var newName = originalName.replace(/\[\d+\]/g, `[${deviceFormCount - 1}]`);
            $(this).attr('name', newName);
            $(this).val(''); // Clear input values
        }
    });

    // Remove Tagify's previous structure
    newDeviceForm.find('tags').remove();
    newDeviceForm.find('.tagify').remove();

    // Remove cloned checklist content
    newDeviceForm.find('.append_checklists').empty();

    // Assign unique ID for the checklist section
    newDeviceForm.find('.append_checklists').attr('id', `checklist_${deviceFormCount}`);

    // Add Delete Button for the New Device Form
    newDeviceForm.find('.delete-btn').html('<button type="button" class="btn btn-danger remove-device-btn">Delete</button>');

    // Append New Form to the Container
    $('#devicesContainer').append(newDeviceForm);

    // Reinitialize Select2
    newDeviceForm.find('.select2').select2({ width: 'resolve' });

    // Reinitialize Components (Date Picker, Tagify, etc.)
    reinitializeComponents(newDeviceForm);
    initializeTagifyForFields(newDeviceForm);

    // ✅ Reinitialize Drop Zone for the New Device
    setTimeout(() => {
        setupDropzone(deviceFormId, deviceCount);
    }, 100);
});


    $('#devicesContainer').on('click', '.remove-device-btn', function () {
        $(this).closest('.device-box').remove();
        console.log('Device form removed. Total forms:', $('.device-box').length);
    });

    reinitializeComponents($('#deviceForm_1'));
    initializeTagifyForFields($('#deviceForm_1'));
});

function initializeTagifyForFields(formElement) {
    // Initialize Tagify for product_configuration
    formElement.find('textarea[name="product_configuration[]"]').each(function() {
        new Tagify(this, {
            whitelist: {!! json_encode($product_conf) !!},
            maxTags: 100,
            dropdown: {
                maxItems: 100,
                classname: "tags-look",
                enabled: 0,
                closeOnSelect: false
            }
        });
    });

    // Initialize Tagify for product_condition
    formElement.find('textarea[name="product_condition[]"]').each(function() {
        new Tagify(this, {
            whitelist: {!! json_encode($product_cond) !!},
            maxTags: 100,
            dropdown: {
                maxItems: 100,
                classname: "tags-look",
                enabled: 0,
                closeOnSelect: false
            }
        });
    });
}

</script>
<script>
    // ✅ Define setupDropzone globally
// function setupDropzone(deviceFormId) {
//     let dropZoneElement = document.querySelector(`#${deviceFormId} .drop-zone`);
//     if (!dropZoneElement) {
//         console.error(`Drop zone not found for: ${deviceFormId}`);
//         return;
//     }

//     let inputElement = dropZoneElement.querySelector(".drop-zone__input");

//     // Remove existing event listeners before adding new ones
//     let newInputElement = inputElement.cloneNode(true);
//     inputElement.parentNode.replaceChild(newInputElement, inputElement);

//     // Click to open file dialog
//     // dropZoneElement.addEventListener("click", () => {
//     //     newInputElement.click();
//     // });
//     dropZoneElement.removeEventListener("click", openFileDialog); // ✅ Remove existing event listener
//     dropZoneElement.addEventListener("click", openFileDialog); 

//     function openFileDialog() {
//         newInputElement.click();
//     }


//     // Drag and drop handlers
//     dropZoneElement.addEventListener("dragover", (e) => {
//         e.preventDefault();
//         dropZoneElement.classList.add("drop-zone--over");
//     });

//     ["dragleave", "dragend"].forEach((eventType) => {
//         dropZoneElement.addEventListener(eventType, () => {
//             dropZoneElement.classList.remove("drop-zone--over");
//         });
//     });

//     dropZoneElement.addEventListener("drop", (e) => {
//         e.preventDefault();
//         if (e.dataTransfer.files.length) {
//             newInputElement.files = e.dataTransfer.files;
//             updateImagePreview(deviceFormId, e.dataTransfer.files);
//         }
//         dropZoneElement.classList.remove("drop-zone--over");
//     });

//     newInputElement.addEventListener("change", (e) => {
//         if (newInputElement.files.length) {
//             updateImagePreview(deviceFormId, newInputElement.files);
//         }
//     });
// }
function setupDropzone(deviceFormId) {
    let dropZoneElement = document.querySelector(`#${deviceFormId} .drop-zone`);
    if (!dropZoneElement) {
        console.error(`Drop zone not found for: ${deviceFormId}`);
        return;
    }

    let inputElement = dropZoneElement.querySelector(".drop-zone__input");

    // ✅ Remove existing event listeners before adding new ones
    let newInputElement = inputElement.cloneNode(true);
    inputElement.parentNode.replaceChild(newInputElement, inputElement);

    function openFileDialog() {
        newInputElement.click();
    }

    dropZoneElement.removeEventListener("click", openFileDialog); // ✅ Remove old listeners
    dropZoneElement.addEventListener("click", openFileDialog); // ✅ Add new listener

    // ✅ Fix drag & drop multiple event binding
    ["dragover", "dragleave", "dragend", "drop"].forEach(eventType => {
        dropZoneElement.removeEventListener(eventType, handleDragEvents);
        dropZoneElement.addEventListener(eventType, handleDragEvents);
    });

    function handleDragEvents(e) {
        e.preventDefault();
        if (e.type === "dragover") dropZoneElement.classList.add("drop-zone--over");
        else dropZoneElement.classList.remove("drop-zone--over");
    }

    newInputElement.addEventListener("change", (e) => {
        if (newInputElement.files.length) {
            updateImagePreview(deviceFormId, newInputElement.files);
        }
    });
}


// ✅ Define updateImagePreview globally
function updateImagePreview(deviceFormId, files) {
    let previewContainer = document.querySelector(`#${deviceFormId} .image-preview-container`);
    if (!previewContainer) return;

    previewContainer.innerHTML = ''; // Clear previous previews

    Array.from(files).forEach(file => {
        if (!file.type.startsWith("image/")) return;

        let reader = new FileReader();
        reader.onload = function (e) {
            let img = document.createElement("img");
            img.src = e.target.result;
            img.classList.add("image-preview");
            previewContainer.appendChild(img);
        };
        reader.readAsDataURL(file);
    });
}

// ✅ Now inside DOMContentLoaded, you can safely call setupDropzone
document.addEventListener("DOMContentLoaded", function () {
    setupDropzone("deviceForm_1"); // Initialize dropzone for the first device form
});

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


    // Initialize for first device
    setupDropzone("deviceForm_1");


});



    
    function previewSelectedImages(event, index) {
        let files = event.target.files;
        let previewContainer = document.getElementById(`image-preview-container-${index}`);
        previewContainer.innerHTML = '';
    
        if (files) {
            for (let file of files) {
                let reader = new FileReader();
                reader.onload = function (e) {
                    let img = document.createElement('img');
                    img.src = e.target.result;
                    img.classList.add('img-thumbnail', 'm-1');
                    img.style.width = '100px';
                    img.style.height = '100px';
                    previewContainer.appendChild(img);
                };
                reader.readAsDataURL(file);
            }
        }
    }
    
    function openWebcam(index) {
        let modal = document.getElementById(`webcam-modal-${index}`);
        let video = document.getElementById(`webcam-stream-${index}`);
        
        navigator.mediaDevices.getUserMedia({ video: true }).then(stream => {
            video.srcObject = stream;
            $(modal).modal('show');
        }).catch(error => {
            alert('Error accessing webcam: ' + error);
        });
    }
    
    function captureImage(index) {
        let video = document.getElementById(`webcam-stream-${index}`);
        let canvas = document.getElementById(`webcam-canvas-${index}`);
        let previewContainer = document.getElementById(`image-preview-container-${index}`);
        let hiddenInput = document.getElementById(`captured-images-${index}`);
    
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        let context = canvas.getContext('2d');
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
    
        let imageData = canvas.toDataURL('image/png');
        
        // Store base64 image in hidden input field
        let existingImages = hiddenInput.value ? JSON.parse(hiddenInput.value) : [];
        existingImages.push(imageData);
        hiddenInput.value = JSON.stringify(existingImages);
    
        // Display captured image
        let img = document.createElement('img');
        img.src = imageData;
        img.classList.add('img-thumbnail', 'm-1');
        img.style.width = '100px';
        img.style.height = '100px';
        previewContainer.appendChild(img);
    
        // Close webcam modal
        $(`#webcam-modal-${index}`).modal('hide');
    
        // Stop the webcam
        video.srcObject.getTracks().forEach(track => track.stop());
    }

console.log("Total Devices Detected:", $(".device-box").length);

    </script>
    
@endsection
Editor is loading...
Leave a Comment