@extends('backend.layouts.app')
@section('content')
    <style>
        .file-upload {
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            padding: 4rem 1.5rem;
            margin-top: 2rem;
            border: 3px dashed #dbedff;
            border-radius: .5rem;
            transition: background-color .25s ease-out;
            max-width: 700px;

            &:hover {
                background-color: #dbedff;
            }

            .file-input {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                opacity: 0;
                outline: none;
                cursor: pointer;
            }
        }

        .icon {
            width: 75px;
            margin-bottom: 1rem;
        }

        .image-container {
            position: relative;
            display: flex;
            justify-content: center;/ Centers content horizontally / align-items: center;/ Centers content vertically /
        }

        .delete-button-container {
            position: absolute;/ Position the button container inside the image container / bottom: 10px;/ Adjust position as needed /
        }

        .btn-danger {
            background-color: rgba(255, 0, 0, 0.7);/ Optional: slightly transparent background / border-color: rgba(255, 0, 0, 0.7);/ Optional: slightly transparent border /
        }
    </style>
    <div class="row page-titles">
        <div class="col-md-5 align-self-center">
            <h4 class="text-themecolor">Career Guidance Manager</h4>
        </div>
        <div class="col-md-7 align-self-center text-right">
            <div class="d-flex justify-content-end align-items-center">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
                    <li class="breadcrumb-item"><a href="{{ route('blog') }}">Career Guidance Manager</a></li>
                    <li class="breadcrumb-item active">Create Career Guidance Manager</li>
                </ol>
            </div>
        </div>
    </div>

    <div id="deleteModal" class="modal fade" role='dialog'>
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-body">
                    <p>Are you sure you want to delete this?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <span id='deleteButton'></span>
                </div>
            </div>
        </div>
    </div>

    <!-- Content Wrapper. Contains page content -->
    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                @if (session('status'))
                    <div class="alert alert-success alert-dismissible fade show" role="alert"><i
                            class="far fa-check-circle"></i>
                        <strong></strong> {{ session('status') }}
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                @endif
                <div class="col-md-12">
                    <div class="card card-primary">
                        <div class="tab-content">
                            <form action="{{ route('careerGuidance.update',$careerGuidance->id) }}" id="careerGuidance" method="POST"
                                enctype="multipart/form-data">
                                @csrf
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-sm-6">
                                            <div class="form-group">
                                                <label for="title">Title<span
                                                        style="color: red;font-size:18px;"><b>*</b></span></label>
                                                <input type="text" name="title"
                                                    value="{{ old('title') ? old('title') : $careerGuidance->title }}"
                                                    class="form-control" id="title" placeholder="Enter Title">
                                                @error('title')
                                                    <p style="color:red;">{{ $message }}</p>
                                                @enderror
                                            </div>
                                        </div>

                                        <div class="col-sm-6">
                                            <div class="form-group">
                                                <label for="Category">Category<span
                                                        style="color: red;font-size:18px;"><b>*</b></span></label>
                                        <select class="form-control" name="category_id" id="">

                                            <option value="">Select Category</option>
                                            @foreach ($categories as $cat => $category)
                                            <option @if($cat==$careerGuidance->category_id) selected @endif value="{{$cat}}">{{$category}}</option>
                                            @endforeach
                                        </select>
                                                @error('title')
                                                    <p style="color:red;">{{ $message }}</p>
                                                @enderror
                                            </div>
                                        </div>


                                        <div class="col-md-12">
                                            <div class="form-group">
                                                <label>Images/Videos Upload<span
                                                    style="color: red;font-size:18px;"><b>*</b></span></label>

                                                <div class="file-upload">
                                                    <input type="file" class="file-input" name="file" id="fileInput"
                                                        class="form-control @error('file') is-invalid @enderror">

                                                    <!-- Progress bar container -->
                                                    <div id="progressContainer"></div>

                                                    <svg class="icon" viewBox="0 0 60 60"
                                                        xmlns="http://www.w3.org/2000/svg">
                                                        <!-- SVG content here (unchanged) -->
                                                    </svg>
                                                    <div class="card-subtitle">Drag n Drop your file here</div>
                                                </div>
                                            </div>
                                        </div>
                                        <!-- Progress bar template -->
                                        <script type="text/template" id="progressTemplate">
                                            <div class="upload-progress">
                                            <span class="file-name"></span>
                                            <progress class="progress-bar" value="0" max="100"></progress>
                                            <span class="progress-percentage">0%</span>
                                            </div>
                                        </script>

                                        <div class="col-md-12">
                                            <div class="row" id="images-preview">
                                                <div class="image-container position-relative m-2 d-flex justify-content-center align-items-center"
                                                    id="removeid_{{ $careerGuidance->id }}">
                                                    <a target="blank"
                                                        href="{{ asset('images/career-guidances/' . $careerGuidance->file) }}">
                                                        @if ($careerGuidance->file)
                                                            @php
                                                                // Get the file's extension
                                                                $fileExtension = pathinfo(
                                                                    $careerGuidance->file,
                                                                    PATHINFO_EXTENSION,
                                                                );
                                                            @endphp

                                                            @if (in_array(strtolower($fileExtension), ['jpg', 'jpeg', 'png', 'gif', 'webp']))
                                                                <!-- Image file -->
                                                                <img width="320" src="{{ asset('images/career-guidances/' . $careerGuidance->file) }}"
                                                                    alt="Career Guidance Image" class="img-fluid">
                                                            @elseif(in_array(strtolower($fileExtension), ['mp4', 'webm', 'ogg']))
                                                                <!-- Video file -->
                                                                <video width="320" height="240" controls>
                                                                    <source
                                                                        src="{{ asset('images/career-guidances/' . $careerGuidance->file) }}"
                                                                        type="video/{{ $fileExtension }}">
                                                                    Your browser does not support the video tag.
                                                                </video>
                                                            @else
                                                                <!-- If it's neither image nor video, show fallback or message -->
                                                                <span>No valid media available</span>
                                                            @endif
                                                        @else
                                                            <span>No file available</span>
                                                        @endif
                                                    </a>
                                                    <div class="delete-button-container">
                                                        {{-- <button class="btn btn-danger btn-sm" title="Delete">
                                                                <i class="fas fa-trash"></i>
                                                            </button> --}}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-sm-12">
                                            <div class="tab-content" id="languageTabContent" style="margin-top:1%">
                                                <div class="" id="language-content" role="tabpanel"
                                                    aria-labelledby="language-tab">
                                                    <div class="row">
                                                        <div class="col-sm-12">
                                                            <div class="form-group">
                                                                <label for="description">Description<span
                                                                        style="color: red;font-size:18px;"><b>*</b></span></label>
                                                                <textarea name="description" id="description" class="form-control" placeholder="Enter Description">{{ old('description')? old('description'):$careerGuidance->description }}</textarea>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>


                                        </div>

                                        <div class="col-sm-12">
                                            <div class="form-group">
                                                <div class="custom-control custom-checkbox mr-sm-2 m-b-15">
                                                    <input type="checkbox" class="custom-control-input" name="status"
                                                        id="checkbox0"
                                                        @if (old('status') == 1) checked @else @endif
                                                        value="1">
                                                    <label class="custom-control-label" for="checkbox0">Is Active </label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card-body">
                                        <button type="submit" id="submitButton" class="btn btn-primary">Submit</button>
                                        <a href="{{ route('blog', request()->query()) }}"
                                            class="btn btn-secondary">Back</a>
                                    </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    </div>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.ckeditor.com/4.16.2/standard/ckeditor.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Convert Blade variables to JavaScript variables

            CKEDITOR.replace('description');


            $.validator.addMethod("maxFileSize", function(value, element, param) {
                if (element.files.length) {
                    var fileSize = element.files[0].size;
                    return this.optional(element) || (fileSize <= param);
                }
                return true; // No file selected
            }, "The file must be less than {0} bytes.");


            const form = $('#careerGuidance');

            // Initialize jQuery Validation
            form.validate({
                ignore: [],
                rules: {
                    title: {
                        required: true,
                        minlength: 3,
                        noOnlySpaces: true
                    },
                    category_id:{
                        required: true,
                    },
                    description: {
                        required: true, // Make it required
                        minlength: 5, // You can add other validation like minimum length
                        noOnlySpaces: true
                    }
                },
                messages: {
                    title: {
                        required: "The title field is required.",
                        minlength: "The title must be at least 3 characters long."
                    },
                    file: {
                        required: "Please upload a file.",
                        validFile: "Only images or videos are allowed."
                    },
                    description: {
                        required: "The description field is required.",
                        minlength: "The description must be at least 5 characters long."
                    }
                },
                errorClass: "error",
                errorPlacement: function (error, element) {
                    if (element.attr("name") === "description") {
                        error.insertAfter("#cke_" + element.attr("id"));
                    } else {
                        error.insertAfter(element);
                    }
                },
                highlight: function(element) {
                    $(element).addClass('is-invalid').removeClass('is-valid');
                },
                unhighlight: function(element) {
                    $(element).removeClass('is-invalid');
                    // .addClass('is-valid');
                },
                submitHandler: function(form) {
                    // Ensure CKEditor data is included in the form submission
                    for (var instance in CKEDITOR.instances) {
                        CKEDITOR.instances[instance]
                    .updateElement(); // This ensures CKEditor content is updated in the textarea before submitting
                    }
                    form.submit();
                }
            });

            // Track if there were changes made (optional)
            let isInputChanged = false;
            form.find('input, textarea').on('input', function() {
                isInputChanged = true;
            });

            $('#submitButton').click(function() {
                if (!isInputChanged) {
                    return;
                }
                if (form.valid()) {
                    form.submit();
                }
            });
        });


        // Select the file input element
        const fileInput = document.getElementById("fileInput");
        const progressContainer = document.getElementById("progressContainer");

        // Listen for file selection
        fileInput.addEventListener("change", (event) => {
            const files = event.target.files;

// Clear previous progress
progressContainer.innerHTML = '';



// Loop through selected files and upload them
const allowedTypes = ["image/jpeg", "image/png", "image/gif", "image/webp", "video/mp4", "video/webm", "video/ogg"];

        // Loop through selected files and upload them
        Array.from(files).forEach((file) => {

        if (!allowedTypes.includes(file.type)) {
            Swal.fire({
        icon: 'error',
        title: 'Invalid File Type',
        text: `The file "${file.name}" is not a valid image or video. Please select a valid file.`,
        confirmButtonText: 'OK'
    });
    fileInput.value = "";
    return;
    }
                // Create a new progress bar for each file
                const progressTemplate = document.getElementById("progressTemplate").innerHTML;
                const progressElement = document.createElement('div');
                progressElement.innerHTML = progressTemplate;
                const fileName = progressElement.querySelector('.file-name');
                const progressBar = progressElement.querySelector('.progress-bar');
                const progressPercentage = progressElement.querySelector('.progress-percentage');

                // Set the file name in the progress bar
                fileName.textContent = file.name;

                // Append the progress bar to the container
                progressContainer.appendChild(progressElement);

                // Start the upload for this file
                uploadFile(file, progressBar, progressPercentage);

                // update the preview
            });
        });

        // Function to upload a file
        function uploadFile(file, progressBar, progressPercentage) {
            const formData = new FormData();
            formData.append("file", file);
            formData.append("id", '{{ $careerGuidance->id }}');



            // Create a new XMLHttpRequest to upload the file
            const xhr = new XMLHttpRequest();

            // Event listener for upload progress
            xhr.upload.addEventListener("progress", (event) => {
                if (event.lengthComputable) {
                    const percent = (event.loaded / event.total) * 100;
                    progressBar.value = percent;
                    progressPercentage.textContent = `${Math.round(percent)}%`;
                }
            });

            // Event listener for when the upload is complete
            xhr.addEventListener("load", () => {
                if (xhr.status === 200) {
                    // Success message or handling
                    const response = JSON.parse(xhr.responseText);

                    // Assuming the backend returns the file's ID and path
                    const fileId = response.data.id; // Example: response should have 'id' and 'file'
                    const filePath = response.data.file;

                    // Dynamically append the image to the images-preview section
                    $('#images-preview').append(`
                       <div class="image-container position-relative m-2 d-flex justify-content-center align-items-center" id="removeid_${fileId}">
                            <a target="blank" href="${window.location.origin}/images/career-guidances/${filePath}">
                                <img src="${window.location.origin}/images/career-guidances/${filePath}" alt="" width="150px" height="150px">
                            </a>

                        </div>
                    `);
                    progressPercentage.textContent = "Upload complete!";
                } else {
                    // Error message handling
                    progressPercentage.textContent = "Upload failed!";
                }
            });

            // Event listener for upload failure
            xhr.addEventListener("error", () => {
                progressPercentage.textContent = "Error uploading file!";
            });

            // Send the request to the server
            xhr.open("POST", "{{ route('careerGuidance.imageUpload') }}"); // Replace with your server endpoint
            xhr.setRequestHeader("X-CSRF-TOKEN", document.querySelector('meta[name="csrf-token"]')
            .content); // Add CSRF token
            xhr.send(formData);
        }

        function deleteImage(cg_id, imageId) {
            // AJAX request to delete the image
            $.ajax({
                url: '{{ route('careerGuidance.delete') }}', // Route to your delete method
                method: 'POST',
                data: {
                    _token: '{{ csrf_token() }}', // Include CSRF token for security
                    image_id: imageId,
                    cg_id: cg_id
                },
                success: function(response) {
                    if (response.success) {
                        $(`#removeid_${imageId}`).remove();
                        // On success, remove the image element from the DOM
                        const files = response.data;
                    }
                },
                error: function() {
                    alert('There was an error with the request.');
                }
            });
        }
    </script>
@endsection
