@extends('back.layout.page-layout')
@section('pageTitle', isset($pageTitle) ? $pageTitle : 'Page Title Here')
@section('content')

<div class="page-header">
    <div class="row">
        <div class="col-md-6 col-sm-12">
            <div class="title">
                <h4>Edit Faculty</h4>
            </div>
            <nav aria-label="breadcrumb" role="navigation">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item">
                        <a href="{{ route('admin.dashboard') }}">Home</a>
                    </li>
                    <li class="breadcrumb-item active" aria-current="page">
                        Edit Faculty
                    </li>
                </ol>
            </nav>
        </div>
        <div class="col-md-6 col-sm-12 text-right">
            <a href="{{ route('admin.faculty') }}" class="btn btn-primary">View all Faculty</a>
        </div>
    </div>
</div>

<form action="{{ route('admin.update_faculty', ['faculty_id'=>$faculty->id]) }}" method="POST" autocomplete="off" enctype="multipart/form-data" id="updateFacultyForm">
    @csrf
    <div class="row">
        <div class="col-md-9">
            <div class="card card-box mb-2">
                <div class="card-body">
                    <div class="form-group">
                        <label for="department">Department</label>
                        <select name="department" id="department" class="form-control"
                            @if($user->type === 'admin') disabled @endif>

                            @if($user->type === 'superAdmin')
                            {{-- Selected department option first --}}
                            @if(!in_array($faculty->department, $departments))
                            <option value="{{ $faculty->department }}" selected>{{ $faculty->department }}</option>
                            @endif

                            {{-- Other department options --}}
                            @foreach($departments as $dept)
                            <option value="{{ $dept }}" {{ $dept === $faculty->department ? 'selected' : '' }}>
                                {{ $dept }}
                            </option>
                            @endforeach
                            @else
                            <option value="{{ $user->department }}" selected>{{ $user->department }}</option>
                            @endif
                        </select>

                        @if($user->type === 'admin')
                        {{-- Hidden input to send the value since select is disabled --}}
                        <input type="hidden" name="department" value="{{ $user->department }}">
                        @endif
                    </div>
                    <div class="form-group">
                        <label for="faculty_name"><b>Faculty Name</b>: </label>
                        <input type="text" name="faculty_name" placeholder="Enter faculty name" class="form-control" value="{{ $faculty->faculty_name }}">
                        <span class="text-danger error-text faculty_name_error"></span>
                    </div>
                    <div class="form-group">
                        <label for="faculty_position"><b>Faculty Position</b>: </label>
                        <input type="text" name="faculty_position" placeholder="Enter faculty position" class="form-control" value="{{ $faculty->faculty_position }}">
                        <span class="text-danger error-text faculty_position_error"></span>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card card-box mb-2">
                <div class="card-body">
                    <div class="form-group">
                        <label for="faculty_image"><b>Faculty image</b>:</label>
                        <input type="file" name="faculty_image" class="form-control-file form-control" height="auto">
                        <span class="text-danger error-text faculty_image_error"></span>
                    </div>
                    <div class="d-block mb-3" style="max-width:200px">
                        <img src="/images/faculty/{{ $faculty->profile_picture }}" alt="" class="img-thumbnail" id="faculty_image_preview">
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="mb-3">
        <button type="submit" class="btn btn-primary">Update Faculty</button>
    </div>
</form>

@endsection
@push('stylesheets')
<link rel="stylesheet" href="/back/src/plugins/bootstrap-tagsinput/bootstrap-tagsinput.css">
@endpush
@push('scripts')
<script src="/back/src/plugins/bootstrap-tagsinput/bootstrap-tagsinput.js"></script>
<script src="https://cdn.ckeditor.com/4.22.1/standard/ckeditor.js"></script>
<script>
    document.addEventListener("DOMContentLoaded", function() {
        const inputFile = document.querySelector('input[type="file"][name="faculty_image"]');
        const previewImage = document.getElementById("faculty_image_preview");

        inputFile.addEventListener("change", function(event) {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewImage.src = e.target.result;
                };
                reader.readAsDataURL(file);
            }
        });


    });
    $(document).ready(function() {
        $('#updateFacultyForm').submit(function(e) {
            e.preventDefault(); // Prevent default form submission

            var form = this;
            // var errorElement = $(form).find('span.text-danger');

            // Reset error message
            // errorElement.text('');
            var formData = new FormData(form);
            $.ajax({
                url: $(form).attr('action'),
                method: $(form).attr('method'),
                data: formData,
                processData: false,
                contentType: false,
                dataType: 'json',
                beforeSend: function() {
                    $(form).find('span.error-text').text('');
                },
                success: function(data) {
                    try {
                        if (data.status === 1) {
                            form.reset();
                            $('img#faculty_image_preview').attr('src', '');
                            toastr.success(data.message);

                            // Update all instances of the site logo
                            // $('img.site_logo').each(function() {
                            //     $(this).attr('src', '/' + data.image_path + '?' + new Date().getTime());
                            // });
                        } else {
                            toastr.error(data.message);
                        }
                    } catch (e) {
                        console.error('Parsing error:', e);
                        toastr.error('Unexpected response format.');
                    }
                },
                error: function(data) {
                    $.each(data.responseJSON.errors, function(prefix, val) {
                        $(form).find('span.' + prefix + '_error').text(val[0]);
                    });
                }
            });


        });
    });
</script>
@endpush