<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Http\Requests\User\StoreEducationRequest;
use App\Http\Requests\User\UpdateEducationRequest;
use App\Models\EducationScheme;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;

class EducationSchemeController extends Controller
{
    public function index(){
        $education_scheme = EducationScheme::latest()->get();

        $document = DB::table('document_type_msts')
                        ->where('scheme_id', 3)
                        ->whereNull('deleted_at')
                        ->orderBy('created_at', 'DESC')
                        ->get();

        return view('users.education_scheme')->with(['education_scheme'=> $education_scheme, 'document'=>$document]);
    }

    public function store(StoreEducationRequest $request){
        try
        {
            DB::beginTransaction();
            $input = $request->validated();
            if ($request->hasFile('residence_proof')) {
                $file1 = $request->file('residence_proof');
                $ext1=$file1->getClientOriginalName();
                $filename1=time().'.'.$ext1;
                $file1->move('education_scheme_file/', $filename1);
                $input['residence_proof'] = $filename1;
            }

            if ($request->hasFile('income_certificate')) {
                $file2 = $request->file('income_certificate');
                $ext2=$file2->getClientOriginalName();
                $filename2=time().'.'.$ext2;
                $file2->move('education_scheme_file/', $filename2);
                $input['income_certificate'] = $filename2;
            }

            if ($request->hasFile('admission_certificate')) {
                $file3 = $request->file('admission_certificate');
                $ext3=$file3->getClientOriginalName();
                $filename3=time().'.'.$ext3;
                $file3->move('education_scheme_file/', $filename3);
                $input['admission_certificate'] = $filename3;
            }

            if ($request->hasFile('academic_certificate')) {
                $file4 = $request->file('academic_certificate');
                $ext4=$file4->getClientOriginalName();
                $filename4=time().'.'.$ext4;
                $file4->move('education_scheme_file/', $filename4);
                $input['academic_certificate'] = $filename4;
            }

            if ($request->hasFile('passbook_copy')) {
                $file5 = $request->file('passbook_copy');
                $ext5=$file5->getClientOriginalName();
                $filename5=time().'.'.$ext5;
                $file5->move('education_scheme_file/', $filename5);
                $input['passbook_copy'] = $filename5;
            }

            if ($request->hasFile('adhaar_copy')) {
                $file6 = $request->file('adhaar_copy');
                $ext6=$file6->getClientOriginalName();
                $filename6=time().'.'.$ext6;
                $file6->move('education_scheme_file/', $filename6);
                $input['adhaar_copy'] = $filename6;
            }

            if ($request->hasFile('recommendation_letter')) {
                $file7 = $request->file('recommendation_letter');
                $ext7=$file7->getClientOriginalName();
                $filename7=time().'.'.$ext7;
                $file7->move('education_scheme_file/', $filename7);
                $input['recommendation_letter'] = $filename7;
            }

            if ($request->hasFile('signature')) {
                $file8 = $request->file('signature');
                $ext8=$file8->getClientOriginalName();
                $filename8=time().'.'.$ext8;
                $file8->move('education_scheme_file/', $filename8);
                $input['signature'] = $filename8;
            }

            if ($request->hasFile('profile')) {
                $file9 = $request->file('profile');
                $ext9=$file9->getClientOriginalName();
                $filename9=time().'.'.$ext9;
                $file9->move('education_scheme_file/', $filename9);
                $input['profile'] = $filename9;
            }

            $unique_id = "EDU-SCH".rand(100000,10000000);
            $input['application_no'] = $unique_id;
            EducationScheme::create( Arr::only( $input, EducationScheme::getFillables() ) );
            DB::commit();
            return response()->json(['success'=> 'Education Scheme created successfully!']);
        }
        catch(\Exception $e)
        {
            return $this->respondWithAjax($e, 'creating', 'Education Scheme');
        }

    }

    public function edit(EducationScheme $education_scheme){

        $fullPath = 'education_scheme_file/' . $education_scheme['residence_proof'] ?? '';
        $imagePath = asset($fullPath);

        $fullPath1 = 'education_scheme_file/' . $education_scheme['income_certificate'] ?? '';
        $imagePath1 = asset($fullPath1);

        $fullPath2 = 'education_scheme_file/' . $education_scheme['admission_certificate'] ?? '';
        $imagePath2 = asset($fullPath2);

        if ($education_scheme)
        {
            $response = [
                'result' => 1,
                'education_scheme' => $education_scheme,
                'imagePath'=>$imagePath,
                'imagePath1'=>$imagePath1,
                'imagePath2'=>$imagePath2

            ];
        }
        else
        {
            $response = ['result' => 0];
        }
        return $response;
    }

    public function update(UpdateEducationRequest $request, EducationScheme $education_scheme)
    {
        try
        {
            DB::beginTransaction();
            $input = $request->validated();
            if ($request->hasFile('residence_proof')) {
                $path1='education_scheme_file/'.$input['residence_proof'];
                if(File::exists($path1)){
                    File::delete($path1);
                }
                $file1 = $request->file('residence_proof');
                $ext1=$file1->getClientOriginalName();
                $filename1=time().'.'.$ext1;
                $file1->move('education_scheme_file/', $filename1);
                $input['residence_proof'] = $filename1;
            }

            if ($request->hasFile('income_certificate')) {
                $path2='education_scheme_file/'.$input['income_certificate'];
                if(File::exists($path2)){
                    File::delete($path2);
                }
                $file2 = $request->file('income_certificate');
                $ext2=$file2->getClientOriginalName();
                $filename2=time().'.'.$ext2;
                $file2->move('education_scheme_file/', $filename2);
                $input['income_certificate'] = $filename2;

            }

            if ($request->hasFile('admission_certificate')) {
                $path3='education_scheme_file/'.$input['admission_certificate'];
                if(File::exists($path3)){
                    File::delete($path3);
                }
                $file3 = $request->file('admission_certificate');
                $ext3=$file3->getClientOriginalName();
                $filename3=time().'.'.$ext3;
                $file3->move('education_scheme_file/', $filename3);
                $input['admission_certificate'] = $filename3;
            }

            if ($request->hasFile('academic_certificate')) {
                $path4='education_scheme_file/'.$input['academic_certificate'];
                if(File::exists($path4)){
                    File::delete($path4);
                }
                $file4 = $request->file('academic_certificate');
                $ext4=$file4->getClientOriginalName();
                $filename4=time().'.'.$ext4;
                $file4->move('education_scheme_file/', $filename4);
                $input['academic_certificate'] = $filename4;
            }

            if ($request->hasFile('passbook_copy')) {
                $path5='education_scheme_file/'.$input['passbook_copy'];
                if(File::exists($path5)){
                    File::delete($path5);
                }
                $file5 = $request->file('passbook_copy');
                $ext5=$file5->getClientOriginalName();
                $filename5=time().'.'.$ext5;
                $file5->move('education_scheme_file/', $filename5);
                $input['passbook_copy'] = $filename5;
            }


            if ($request->hasFile('adhaar_copy')) {
                $path6='education_scheme_file/'.$input['adhaar_copy'];
                if(File::exists($path6)){
                    File::delete($path6);
                }
                $file6 = $request->file('adhaar_copy');
                $ext6=$file6->getClientOriginalName();
                $filename6=time().'.'.$ext6;
                $file6->move('education_scheme_file/', $filename6);
                $input['adhaar_copy'] = $filename6;
            }


            if ($request->hasFile('recommendation_letter')) {
                $path7='education_scheme_file/'.$input['recommendation_letter'];
                if(File::exists($path7)){
                    File::delete($path7);
                }
                $file7 = $request->file('recommendation_letter');
                $ext7=$file7->getClientOriginalName();
                $filename7=time().'.'.$ext7;
                $file7->move('education_scheme_file/', $filename7);
                $input['recommendation_letter'] = $filename7;
            }

            if ($request->hasFile('signature')) {
                $path8='education_scheme_file/'.$input['signature'];
                if(File::exists($path8)){
                    File::delete($path8);
                }
                $file8 = $request->file('signature');
                $ext8=$file8->getClientOriginalName();
                $filename8=time().'.'.$ext8;
                $file8->move('education_scheme_file/', $filename8);
                $input['signature'] = $filename8;

            }

            if ($request->hasFile('profile')) {
                $path9='education_scheme_file/'.$input['profile'];
                if(File::exists($path9)){
                    File::delete($path9);
                }
                $file9 = $request->file('profile');
                $ext9=$file9->getClientOriginalName();
                $filename9=time().'.'.$ext9;
                $file9->move('education_scheme_file/', $filename9);
                $input['profile'] = $filename9;
            }
            $education_scheme->update( Arr::only( $input, EducationScheme::getFillables() ) );
            DB::commit();
            return response()->json(['success'=> 'Education Scheme updated successfully!']);
        }
        catch(\Exception $e)
        {
            return $this->respondWithAjax($e, 'updating', 'Education Scheme');
        }
    }


    public function destroy(EducationScheme $education_scheme)
    {
        try
        {
            DB::beginTransaction();
            $education_scheme->delete();
            DB::commit();
            return response()->json(['success'=> 'Education Scheme deleted successfully!']);
        }
        catch(\Exception $e)
        {
            return $this->respondWithAjax($e, 'deleting', 'Education Scheme');
        }
    }
}

blade

<x-admin.layout>
    <x-slot name="title">Education Scheme Form</x-slot>
    <x-slot name="heading">Education Scheme Form</x-slot>
    {{-- <x-slot name="subheading">Test</x-slot> --}}


        <!-- Add Form -->
        <div class="row" id="addContainer" style="display:none;">
            <div class="col-sm-12">
                <div class="card">
                    <form class="theme-form"  name="addForm" id="addForm" enctype="multipart/form-data">
                        @csrf

                        <div class="card-header">
                            <h4 class="card-title">Add Education Scheme Form </h4>
                        </div>
                        <div class="card-body">
                            <div class="mb-3 row">
                                {{-- <input type="hidden" id="h_id" name="h_id" value=""> --}}

                                <div class="col-md-4 mt-3">
                                    <label class="col-form-label" for="name">1. संपूर्ण नाव</label>
                                    <input class="form-control"  type="text"  name="full_name"  value="" placeholder="Enter Full Name ">
                                    <span class="text-danger is-invalid full_name_err"></span>
                                </div>
                                <div class="col-md-4 mt-3">
                                    <label class="col-form-label" for="full_address">2. Full Address / संपूर्ण पत्ता</label>
                                    <input class="form-control"   type="text" name="full_address" value=""  placeholder="Enter Full Address">
                                    <span class="text-danger is-invalid full_address_err"></span>
                                </div>

                                <div class="col-md-4 mt-3">
                                    <label class="col-form-label" for="dob">3.  Date Of Birth/ वय </label>
                                    <input class="form-control" id="dob" name="dob" type="date"  placeholder="Enter Date Of Birth">
                                    <span class="text-danger is-invalid age_err"></span>
                                </div>

                                <div class="col-md-4 mt-3">
                                    <label class="col-form-label" for="Age"> Age/ वय </label>
                                    <input class="form-control" id="age" name="age" type="text"  placeholder="Enter Age">
                                    <span class="text-danger is-invalid age_err"></span>
                                </div>

                                <div class="col-md-4 mt-3">
                                    <label class="col-form-label" for="contact"> Mobile No/ मोबाईल नं.:</label>
                                    <input class="form-control" id="contact" name="contact"  type="number"  placeholder="Enter Mobile No" min="0" onkeypress="return (event.charCode !=8 && event.charCode ==0 || (event.charCode >= 48 && event.charCode <= 57))">
                                    <span class="text-danger is-invalid contact_err"></span>
                                </div>

                                <div class="col-md-4 mt-3">
                                    <label class="col-form-label" for="email"> Email/ ई मेल:</label>
                                    <input class="form-control" id="email" name="email"  type="text"  placeholder="Enter Email" >
                                    <span class="text-danger is-invalid email_err"></span>
                                </div>

                                <div class="col-md-4 mt-3">
                                    <label class="col-form-label" for="beneficiary_relationship"> Beneficiary relationship/ लाभार्थ्याचे नाते :</label>
                                    <input class="form-control" id="beneficiary_relationship" name="beneficiary_relationship"  type="text"  placeholder="Enter Beneficiary relationship" >
                                    <span class="text-danger is-invalid beneficiary_relationship_err"></span>
                                </div>

                                <div class="col-md-4 mt-3">
                                    <label class="col-form-label" for="family_name">4. Name of Head of Family/ कूटुंब प्रमुखाचे नाव ::</label>
                                    <input class="form-control" id="family_name" name="family_name"  type="text"  placeholder="Enter family name" >
                                    <span class="text-danger is-invalid family_name_err"></span>
                                </div>

                                <div class="col-md-4 mt-3">
                                    <label class="col-form-label" for="total_family">5. Total Number of Family / कुटुंबातील एकूण संख्या ::</label>
                                    <input class="form-control" id="total_family" name="total_family"  type="text"  placeholder="Enter total family" >
                                    <span class="text-danger is-invalid total_family_err"></span>
                                </div>



                                <div class="col-md-4 mt-3">
                                    <label class="col-form-label" for="adhaar_no">11. Aadhar Card Number  / आधारकार्ड क्रमांक <span class="text-danger">*</span></label>
                                    <input class="form-control" id="adhaar_no" name="adhaar_no" type="text" placeholder="Enter Adhaar Number">
                                    <span class="text-danger is-invalid adhaar_no_err"></span>
                                </div>


                                @foreach ($document as $doc)
                                <div class="col-md-4 mt-3">
                                        <label class="col-form-label" for="document_name">{{$doc->document_name}} @if($doc->is_required==1) <span class="required">*</span> @endif</label>
                                        <input type="hidden" name="document_id[]" class="form-control" value="{{$doc->id}}">
                                        <input type="file" name="document_file[]" class="form-control" multiple>
                                        <span class="text-danger is-invalid document_file_err"></span>
                                </div>
                            @endforeach

                            </div>
                        </div>
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary" id="addSubmit">Submit</button>
                            <button type="reset" class="btn btn-warning">Reset</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

 {{-- Edit Form --}}
 <div class="row" id="editContainer" style="display:none;">
    <div class="col">
        <form class="form-horizontal form-bordered" method="post" id="editForm">
            @csrf
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title">Edit Education Scheme Form</h4>
                </div>
                <div class="card-body py-2">
                    <input type="hidden" id="edit_model_id" name="edit_model_id" value="">
                    <div class="mb-3 row">
                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="name">1. संपूर्ण नाव</label>
                            <input class="form-control"  type="text"  name="full_name"  value="" placeholder="Enter Full Name ">
                            <span class="text-danger is-invalid full_name_err"></span>
                        </div>
                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="full_address">2. Full Address / संपूर्ण पत्ता</label>
                            <input class="form-control"   type="text" name="full_address" value=""  placeholder="Enter Full Address">
                            <span class="text-danger is-invalid full_address_err"></span>
                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="dob">3.  Date Of Birth/ वय </label>
                            <input class="form-control" id="dob" name="dob" type="date"  placeholder="Enter Date Of Birth">
                            <span class="text-danger is-invalid age_err"></span>
                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="Age"> Age/ वय </label>
                            <input class="form-control" id="age" name="age" type="text"  placeholder="Enter Age">
                            <span class="text-danger is-invalid age_err"></span>
                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="contact"> Mobile No/ मोबाईल नं.:</label>
                            <input class="form-control" id="contact" name="contact"  type="number"  placeholder="Enter Mobile No" min="0" onkeypress="return (event.charCode !=8 && event.charCode ==0 || (event.charCode >= 48 && event.charCode <= 57))">
                            <span class="text-danger is-invalid contact_err"></span>
                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="email"> Email/ ई मेल:</label>
                            <input class="form-control" id="email" name="email"  type="text"  placeholder="Enter Email" >
                            <span class="text-danger is-invalid email_err"></span>
                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="beneficiary_relationship"> Beneficiary relationship/ लाभार्थ्याचे नाते :</label>
                            <input class="form-control" id="beneficiary_relationship" name="beneficiary_relationship"  type="text"  placeholder="Enter Beneficiary relationship" >
                            <span class="text-danger is-invalid beneficiary_relationship_err"></span>
                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="family_name">4. Name of Head of Family/ कूटुंब प्रमुखाचे नाव ::</label>
                            <input class="form-control" id="family_name" name="family_name"  type="text"  placeholder="Enter family name" >
                            <span class="text-danger is-invalid family_name_err"></span>
                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="total_family">5. Total Number of Family / कुटुंबातील एकूण संख्या ::</label>
                            <input class="form-control" id="total_family" name="total_family"  type="text"  placeholder="Enter total family" >
                            <span class="text-danger is-invalid total_family_err"></span>
                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="residence_proof">6. Proof of residence for 3 years in Municipal area:/महानगरपालिका क्षेत्रातील ३ वर्ष वास्तव्याचा पुरावा : <span class="text-danger">*</span></label>
                            <input class="form-control"  name="residence_proof" type="file" >
                            <span class="text-danger is-invalid residence_proof_err"></span>
                            <a class="btn btn-sm btn-primary" id="residence_proof" target="_blank" href="">View Document</a>
                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="income_certificate">7. Low Income Certificate from Tehsildar:/तहसिलदाराकडील अल्प उत्पन्नाचा दाखला : <span class="text-danger">*</span></label>
                            <input class="form-control"  name="income_certificate" type="file" >
                            <span class="text-danger is-invalid income_certificate_err"></span>
                            <a class="btn btn-sm btn-primary" id="income_certificate" target="_blank" href="">View Document</a>
                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="admission_certificate">8. Certificate of Admission to Medical College:/वैद्यकिय महाविद्यालयात प्रवेश घेतल्याचे प्रमाणपत्र : <span class="text-danger">*</span></label>
                            <input class="form-control"  name="admission_certificate" type="file" >
                            <span class="text-danger is-invalid admission_certificate_err"></span>
                            <a class="btn btn-sm btn-primary" id="admission_certificate" target="_blank" href="">View Document</a>
                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="academic_certificate">9. Copy of Result of First Academic Year:/ पहिल्या शैक्षणिक वर्षाच्या निकालाची प्रत :</label>
                            <input class="form-control"  name="academic_certificate" type="file"  >
                            <span class="text-danger is-invalid academic_certificate_err"></span>
                            <a class="btn btn-sm btn-primary" id="academic_certificate_link" target="_blank" href="" >View Document</a>

                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="passbook_copy">10. Photocopy of Passbook of Nationalized Bank/ राष्ट्रियकृत बँकेच्या पासबूकची छायांकित प्रतः</label>
                            <input class="form-control" id="passbook_copy" name="passbook_copy" type="file"  >
                            <span class="text-danger is-invalid passbook_copy_err"></span>

                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="adhaar_no">11. Aadhar Card Number  / आधारकार्ड क्रमांक <span class="text-danger">*</span></label>
                            <input class="form-control" id="adhaar_no" name="adhaar_no" type="text" placeholder="Enter Adhaar Number">
                            <span class="text-danger is-invalid adhaar_no_err"></span>
                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="adhaar_copy"> Photocopy of Aadhar Card/ आधारकार्डाची छायांकित प्रतः :</label>
                            <input class="form-control" id="adhaar_copy" name="adhaar_copy" type="file"  >
                            <span class="text-danger is-invalid adhaar_copy_err"></span>
                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="recommendation_letter">12. Hon. Recommendation letter from corporator/ corporator:/ मा. नगरसेवक / नगरसेविका यांचे शिफारस पत्र :</label>
                            <input class="form-control" id="recommendation_letter" name="recommendation_letter" type="file"  >
                            <span class="text-danger is-invalid recommendation_letter_err"></span>
                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="signature"> Signature</label>
                            <input class="form-control" id="signature" name="signature" type="file"  >
                            <span class="text-danger is-invalid signature_err"></span>
                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="profile"> profile</label>
                            <input class="form-control" id="profile" name="profile" type="file"  >
                            <span class="text-danger is-invalid profile_err"></span>
                        </div>
                    </div>

                </div>
                <div class="card-footer">
                    <button class="btn btn-primary" id="editSubmit">Submit</button>
                    <button type="reset" class="btn btn-warning">Reset</button>
                </div>
            </div>
        </form>
    </div>
</div>


        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header">
                        <div class="row">
                            <div class="col-sm-6">
                                <div class="">
                                    <button id="addToTable" class="btn btn-primary">Add <i class="fa fa-plus"></i></button>
                                    <button id="btnCancel" class="btn btn-danger" style="display:none;">Cancel</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="buttons-datatables" class="table table-bordered nowrap align-middle" style="width:100%">
                                <thead>



                                    <tr>
                                        <th>Application Number</th>
                                        <th>Name</th>
                                        <th>Full Address</th>
                                        <th>Contact</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>

                                    @foreach ($education_scheme as $value)


                                     <tr>
                                            <td>{{ $value->application_no }}</td>
                                            <td>{{ $value->full_name }}</td>
                                            <td>{{ $value->full_address }}</td>
                                            <td>{{ $value->contact }}</td>
                                            <td>
                                                <button class="edit-element btn text-secondary px-2 py-1" title="Edit category" data-id="{{ $value->id }}"><i data-feather="edit"></i></button>
                                                <button class="btn text-danger rem-element px-2 py-1" title="Delete category" data-id="{{ $value->id }}"><i data-feather="trash-2"></i> </button>
                                            </td>
                                        </tr>
                                        @endforeach
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>




</x-admin.layout>


{{-- Add --}}
<script>
    $("#addForm").submit(function(e) {
        e.preventDefault();
        $("#addSubmit").prop('disabled', true);

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('education_scheme.store') }}',
            type: 'POST',
            data: formdata,
            contentType: false,
            processData: false,
            success: function(data)
            {
                $("#addSubmit").prop('disabled', false);
                if (!data.error2)
                    swal("Successful!", data.success, "success")
                        .then((action) => {
                            window.location.href = '{{ route('education_scheme.index') }}';
                        });
                else
                    swal("Error!", data.error2, "error");
            },
            statusCode: {
                422: function(responseObject, textStatus, jqXHR) {
                    $("#addSubmit").prop('disabled', false);
                    resetErrors();
                    printErrMsg(responseObject.responseJSON.errors);
                },
                500: function(responseObject, textStatus, errorThrown) {
                    $("#addSubmit").prop('disabled', false);
                    swal("Error occured!", "Something went wrong please try again", "error");
                }
            }
        });

        function resetErrors() {
            var form = document.getElementById('addForm');
            var data = new FormData(form);
            for (var [key, value] of data) {
                $('.' + key + '_err').text('');
                $('#' + key).removeClass('is-invalid');
                $('#' + key).addClass('is-valid');
            }
        }

        function printErrMsg(msg) {
            $.each(msg, function(key, value) {
                $('.' + key + '_err').text(value);
                $('#' + key).addClass('is-invalid');
                $('#' + key).removeClass('is-valid');
            });
        }

    });


</script>


<!-- Edit -->
<script>
    $("#buttons-datatables").on("click", ".edit-element", function(e) {
        e.preventDefault();
        var model_id = $(this).attr("data-id");
        var url = "{{ route('education_scheme.edit', ":model_id") }}";

        $.ajax({
            url: url.replace(':model_id', model_id),
            type: 'GET',
            data: {
                '_token': "{{ csrf_token() }}"
            },
            success: function(data, textStatus, jqXHR) {
                editFormBehaviour();
                if (!data.error)
                {
                    $("#editForm input[name='edit_model_id']").val(data.education_scheme.id);
                    $("#editForm input[name='full_name']").val(data.education_scheme.full_name);
                    $("#editForm input[name='full_address']").val(data.education_scheme.full_address);
                    $("#editForm input[name='dob']").val(data.education_scheme.dob);
                    $("#editForm input[name='age']").val(data.education_scheme.age);
                    $("#editForm input[name='contact']").val(data.education_scheme.contact);
                    $("#editForm input[name='adhaar_no']").val(data.education_scheme.adhaar_no);
                    $("#editForm input[name='email']").val(data.education_scheme.email);
                    $("#editForm input[name='family_name']").val(data.education_scheme.family_name);
                    $("#editForm input[name='beneficiary_relationship']").val(data.education_scheme.beneficiary_relationship);
                    $("#editForm input[name='total_family']").val(data.education_scheme.total_family);
                    $("#editForm a#residence_proof").attr('href', data.imagePath);
                    $("#editForm a#income_certificate").attr('href', data.imagePath1);
                    $("#editForm a#admission_certificate").attr('href', data.imagePath2);

                    $("#editForm a#academic_certificate_link").attr('href', "{{ asset('education_scheme_file/') }}" + data.education_scheme.academic_certificate);




                    $("#editForm input[name='passbook_copy']").val(data.education_scheme.passbook_copy);
                    $("#editForm input[name='adhaar_copy']").val(data.education_scheme.adhaar_copy);
                    $("#editForm input[name='recommendation_letter']").val(data.education_scheme.recommendation_letter);
                    $("#editForm input[name='signature']").val(data.education_scheme.signature);
                    $("#editForm input[name='profile']").val(data.education_scheme.profile);

                }
                else
                {
                    alert(data.error);
                }
            },
            error: function(error, jqXHR, textStatus, errorThrown) {
                alert("Some thing went wrong");
            },
        });
    });
</script>

<!-- Update -->
<script>
    $(document).ready(function() {
        $("#editForm").submit(function(e) {
            e.preventDefault();
            $("#editSubmit").prop('disabled', true);
            var formdata = new FormData(this);
            formdata.append('_method', 'PUT');
            var model_id = $('#edit_model_id').val();
            var url = "{{ route('education_scheme.update', ":model_id") }}";
            //
            $.ajax({
                url: url.replace(':model_id', model_id),
                type: 'POST',
                data: formdata,
                contentType: false,
                processData: false,
                success: function(data)
                {
                    $("#editSubmit").prop('disabled', false);
                    if (!data.error2)
                        swal("Successful!", data.success, "success")
                            .then((action) => {
                                window.location.href = '{{ route('education_scheme.index') }}';
                            });
                    else
                        swal("Error!", data.error2, "error");
                },
                statusCode: {
                    422: function(responseObject, textStatus, jqXHR) {
                        $("#editSubmit").prop('disabled', false);
                        resetErrors();
                        printErrMsg(responseObject.responseJSON.errors);
                    },
                    500: function(responseObject, textStatus, errorThrown) {
                        $("#editSubmit").prop('disabled', false);
                        swal("Error occured!", "Something went wrong please try again", "error");
                    }
                }
            });

        });
    });
</script>

<!-- Delete -->
<script>
    $("#buttons-datatables").on("click", ".rem-element", function(e) {
        e.preventDefault();
        swal({
            title: "Are you sure to delete this Education Scheme?",

            icon: "info",
            buttons: ["Cancel", "Education Scheme"]
        })
        .then((justTransfer) =>
        {
            if (justTransfer)
            {
                var model_id = $(this).attr("data-id");
                var url = "{{ route('education_scheme.destroy', ":model_id") }}";

                $.ajax({
                    url: url.replace(':model_id', model_id),
                    type: 'POST',
                    data: {
                        '_method': "DELETE",
                        '_token': "{{ csrf_token() }}"
                    },
                    success: function(data, textStatus, jqXHR) {
                        if (!data.error && !data.error2) {
                            swal("Success!", data.success, "success")
                                .then((action) => {
                                    window.location.reload();
                                });
                        } else {
                            if (data.error) {
                                swal("Error!", data.error, "error");
                            } else {
                                swal("Error!", data.error2, "error");
                            }
                        }
                    },
                    error: function(error, jqXHR, textStatus, errorThrown) {
                        swal("Error!", "Something went wrong", "error");
                    },
                });
            }
        });
    });
</script>

