@extends('layouts.app')
@section('title', 'Projects')
@section('pages')
    <style type="text/css">
        .dataTables_filter {
            margin-bottom: 6px;
        }

        .text-left {
            text-align: left !important;
        }
    </style>
    <link rel="stylesheet/less" type="text/css" href="{{ asset('admin/plugins/datepicker/less/datepicker.less') }}">
    <link href="{{ asset('admin/plugins/datepicker/css/datepicker.css') }}" rel="stylesheet" />
    <!--breadcrumb-->
    <div class="page-breadcrumb d-flex align-items-center mb-3 px-3 px-md-0">
        <div class="breadcrumb-title pe-3"><i class="bi bi-list"></i> Projects</div>
        <div class="ps-3">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-0 p-0">
                    <li class="breadcrumb-item active" aria-current="page"> Project Details</li>
                </ol>
            </nav>
        </div>
        <div class="ms-auto">
            {{-- @if (auth()->user()->can('product-edit')) --}}
            {{-- <div class="btn-group">
            <a href="{{route('projects.edit',$data->id)}}" class="btn btn-warning" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Edit">
                <i class="bi bi-pencil-square text-white"></i>
            </a>
        </div> --}}
            {{-- @endif --}}
            <div class="btn-group">
                <a href="{!! route('projects.index') !!}" class="btn btn-info"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
            </div>
        </div>
    </div>
    <!--end breadcrumb-->

    <div class="row auto">
        <div class="col-xl-12 mx-auto">
            <div class="shadow-none radius-5 min-height">
                <div class="row">
                    @if (isset($product->description) && $product->description != '')
                        <div class="col-md-12">
                            <div class="card">
                                <div class="card-body g-3 row">
                                    <div class="table-responsive">
                                        <h5 class="mb-0">Item Name: <b>{{ $product->name }}</b></h5>
                                        <hr class="mb-2">
                                        <p>{{ $product->description }}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endif
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body g-3">
                                <div class="table-responsive">
                                    <div class="d-flex justify-content-between">
                                        <h5 class="mb-0">Project Details</h5>
                                    </div>
                                    <hr class="mb-2">
                                    <table class="table table-bordered align-middle">
                                        <tr>
                                            <td class="text-left">Title </td>
                                            <td>{{ ucfirst($data->title) }} {{ $data->code }}</td>
                                        </tr>
                                        <tr>
                                            <td class="text-left">Project Type</td>
                                            <td>{{ ucfirst($data->getProjectType->title) ?? 'N/A' }}</td>
                                        </tr>
                                        <tr>
                                            <td class="text-left">Departments</td>
                                            <td style="white-space: initial;">
                                                @if ($data->getDepartments)
                                                    @foreach ($data->getDepartments as $department)
                                                        {{ $department->name }},
                                                    @endforeach
                                                @else
                                                    Null
                                                @endif
                                            </td>
                                        </tr>
                                        <tr>
                                            <td class="text-left">About</td>
                                            <td>{{ $data->about }}</td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body g-3 row">
                                <div class="table-responsive">
                                    <h5 class="mb-0">Additional Details</h5>
                                    <hr class="mb-2">
                                    <table class="table table-bordered align-middle">
                                        <tr>
                                            <td class="text-left">receive Date</td>
                                            <td>{{ $data->receive_date }}</td>
                                        </tr>
                                        <tr>
                                            <td class="text-left">start date</td>
                                            <td>{{ $data->start_date }}</td>
                                        </tr>
                                        <tr>
                                            <td class="text-left">Dead Line Date</td>
                                            <td>{{ $data->dead_line_date }}</td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        @if (auth()->user()->can('project-budget-list'))
        <div class="col-xl-12 mx-auto">
            <div class="shadow-none radius-5 min-height">
                <div class="row">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-body g-3" id="budget_project">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        @endif
        @if (auth()->user()->can('project-attachment-list'))
        <div class="col-xl-12 mx-auto">
            <div class="shadow-none radius-5 min-height">
                <div class="row">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-body g-3" id="project_attachments">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        @endif
        @if (auth()->user()->can('project-requirement-list'))
        <div class="col-xl-12 mx-auto">
            <div class="shadow-none radius-5 min-height">
                <div class="row">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-body g-3" id="project_requirments">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        @endif
        @if (auth()->user()->can('project-team-list'))
        <div class="col-xl-12 mx-auto">
            <div class="shadow-none radius-5 min-height">
                <div class="row">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-body g-3" id="fetch_project_teams">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        @endif
    </div>

    <!--end row-->
@endsection
@section('js')
    <script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js') }}"></script>
    <script type="text/javascript">

        $(document).on('click', '.save_button', function(event) {
            event.preventDefault();
            if ($('#commonModal').find('form').hasClass('project_budget')) {
                $('.error_projects_id').hide();
                $('.error_budget_type_id').hide();
                var error = 0;

                if ($('select[name="budget_type_id"]').val() == null || $('select[name="budget_type_id"]').val() ==
                    '') {
                    $('.error_budget_type_id').show();
                    error = 1;
                    setTimeout(function () {
                    $('.error_budget_type_id').hide();
                    }, 3000);
                }

                if (error == 0) {
                    $('[name="projects_id"]').val('{{$data->id}}');
                    let formdata = new FormData($('#commonModal').find('form')[0]);

                    $.ajax({
                            url: $('#commonModal').find('form').attr('action'),
                            data: formdata,
                            processData: false,
                            contentType: false,
                            type: 'POST',
                            success: function(response) {
                                if (response.success === true) {
                                    toastr.success(response.message, 'Success.');

                                    // hide modal
                                    $('#commonModal').modal('hide');
                                    fetch_budget_project();
                                } else {
                                    toastr.error(response.message, 'Error!');
                                }
                            }
                        })
                        .fail(function(jqXHR, textStatus, errorThrown) {
                            console.log('AJAX request failed:', textStatus, errorThrown);
                            toastr.error('An error occurred during the request.', 'Error!');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        });
                }
            }
            if ($('#commonModal').find('form').hasClass('project_attachments')) {
                $('.error_file_url').hide();
                $('.error_title').hide();
                var error = 0;

                if ($('#commonModal').find('form').find('[name="title"]').val() == '') {
                    $('.error_title ').show();
                    error = 1;
                    setTimeout(function () {
                    $('.error_title').hide();
                    }, 3000);
                }

                if (error == 0) {
                    $('[name="projects_id"]').val('{{$data->id}}');
                    let formdata = new FormData($('#commonModal').find('form')[0]);

                    $.ajax({
                            url: $('#commonModal').find('form').attr('action'),
                            data: formdata,
                            processData: false,
                            contentType: false,
                            type: 'POST',
                            success: function(response) {
                                if (response.success === true) {
                                    toastr.success(response.message, 'Success.');

                                    // hide modal
                                    $('#commonModal').modal('hide');
                                    fetch_project_attachments();
                                } else {
                                    toastr.error(response.message, 'Error!');
                                }
                            }
                        })
                        .fail(function(jqXHR, textStatus, errorThrown) {
                            console.log('AJAX request failed:', textStatus, errorThrown);
                            toastr.error('An error occurred during the request.', 'Error!');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        });
                }
            }
            if ($('#commonModal').find('form').hasClass('project_requirments')) {
                $('.error_features').hide();
                var error = 0;

                if ($('#commonModal').find('form').find('[name="features"]').val() == '') {
                    $('.error_features ').show();
                    error = 1;
                    setTimeout(function () {
                    $('.error_features').hide();
                    }, 3000);
                }

                if (error == 0) {
                    $('[name="project_id"]').val('{{$data->id}}');
                    let formdata = new FormData($('#commonModal').find('form')[0]);

                    $.ajax({
                            url: $('#commonModal').find('form').attr('action'),
                            data: formdata,
                            processData: false,
                            contentType: false,
                            type: 'POST',
                            success: function(response) {
                                if (response.success === true) {
                                    toastr.success(response.message, 'Success.');

                                    // hide modal
                                    $('#commonModal').modal('hide');
                                    fetch_project_requirments();
                                } else {
                                    toastr.error(response.message, 'Error!');
                                }
                            }
                        })
                        .fail(function(jqXHR, textStatus, errorThrown) {
                            console.log('AJAX request failed:', textStatus, errorThrown);
                            toastr.error('An error occurred during the request.', 'Error!');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        });
                }
            }
            if ($('#commonModal').find('form').hasClass('project_teams')) {
                $('.error_role_in_project').hide();
                var error = 0;

                if ($('#commonModal').find('form').find('[name="role_in_project"]').val() == '') {
                    $('.error_role_in_project ').show();
                    error = 1;
                    setTimeout(function () {
                    $('.error_role_in_project').hide();
                    }, 3000);
                }

                if (error == 0) {
                    $('[name="project_id"]').val('{{$data->id}}');
                    let formdata = new FormData($('#commonModal').find('form')[0]);

                    $.ajax({
                            url: $('#commonModal').find('form').attr('action'),
                            data: formdata,
                            processData: false,
                            contentType: false,
                            type: 'POST',
                            success: function(response) {
                                if (response.success === true) {
                                    toastr.success(response.message, 'Success.');

                                    // hide modal
                                    $('#commonModal').modal('hide');
                                    fetch_project_teams();
                                } else {
                                    toastr.error(response.message, 'Error!');
                                }
                            }
                        })
                        .fail(function(jqXHR, textStatus, errorThrown) {
                            console.log('AJAX request failed:', textStatus, errorThrown);
                            toastr.error('An error occurred during the request.', 'Error!');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        });
                }
            }

            error = 1;
        })

        function clickBTN() {
            $('#createLicenses').trigger('click');
        }
        $(document).ready(function() {
            fetch_budget_project();
            fetch_project_attachments();
            fetch_project_requirments();
            fetch_project_teams();
        });

        function fetch_budget_project() {
            $.ajax({
                url: "{!! route('project.budget', $data->id) !!}",
                success: function(data) {
                    $('#budget_project').html('');
                    $('#budget_project').html(data);
                    $.switcher('#budget_project .changeStatusCustom');
                }
            })
        }

        function fetch_project_attachments() {
            $.ajax({
                url: "{!! route('project.attachments', $data->id) !!}",
                success: function(data) {
                    $('#project_attachments').html('');
                    $('#project_attachments').html(data);
                    $.switcher('#project_attachments .changeStatusCustom');
                }
            })
        }

        function fetch_project_requirments() {
            $.ajax({
                url: "{!! route('project.requirments', $data->id) !!}",
                success: function(data) {
                    $('#project_requirments').html('');
                    $('#project_requirments').html(data);
                    $.switcher('#project_requirments .changeStatusCustom');
                }
            })
        }

        function fetch_project_teams() {
            $.ajax({
                url: "{!! route('project.teams', $data->id) !!}",
                success: function(data) {
                    $('#fetch_project_teams').html('');
                    $('#fetch_project_teams').html(data);
                    $.switcher('#fetch_project_teams .changeStatusCustom');
                }
            })
        }

        /*********Update Project Budget**********/
        $(document).on('click', '#project_budget_edit', function() {
            var id = $(this).data('id');
            var url = `{!! route('project-budget.edit', ':id') !!}`.replace(':id', id);
            $('#commonModalLabel').text('Edit Project Budget');
            $('.save_button_span').text('Update Project Budget');

            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);

                }
            })
        })
        /*********Create Project Budget**********/
        $(document).on('click', '#createProjectBudget', function() {
            $('#commonModalLabel').text('Add New Project Budget');
            $('.save_button_span').text('Store Project Budget');

            $.ajax({
                url: "{!! route('project-budget.create') !!}",
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                }
            })
        })

        /*********create Project Attachments**********/
        $(document).on('click', '#createProjectAttachments', function() {
            $('#commonModalLabel').text('Add New Project Attachments');
            $('.save_button_span').text('Store Project Attachments');

            $.ajax({
                url: "{!! route('project-attachments.create') !!}",
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                    $.switcher('.isFeatured');

                    /*** on change of toggle button ***/

                    $('#div_image').show();
                    $('#div_file').hide();

                    $('.isFeatured').on('click', function() {
                        if ($(this).is(':checked')) {
                            $('#div_image').show();
                            $('#div_file').hide();
                        } else {
                            $('#div_image').hide();
                            $('#div_file').show();
                        }
                    });

                }
            })
        })
         /*********Update Project Budget**********/
         $(document).on('click', '#project_attachments_edit', function() {
            var id = $(this).data('id');
            var url = `{!! route('project-attachments.edit', ':id') !!}`.replace(':id', id);
            $('#commonModalLabel').text('Edit Project Budget');
            $('.save_button_span').text('Update Project Budget');
            $.switcher('.isFeatured');

            /*** on change of toggle button ***/

            $('#div_image').show();
            $('#div_file').hide();

            $('.isFeatured').on('click', function() {
                if ($(this).is(':checked')) {
                    $('#div_image').show();
                    $('#div_file').hide();
                } else {
                    $('#div_image').hide();
                    $('#div_file').show();
                }
            });
            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);

                }
            })
        })

        /*********create Project Requirment**********/
        $(document).on('click', '#createProjectRequirment', function() {
            $('#commonModalLabel').text('Add New Project Requirment');
            $('.save_button_span').text('Store Project Requirment');

            $.ajax({
                url: "{!! route('project-requirements.create') !!}",
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                }
            })
        })
         /*********Update Project Requirment**********/
         $(document).on('click', '#project_requirements_edit', function() {
            var id = $(this).data('id');
            var url = `{!! route('project-requirements.edit', ':id') !!}`.replace(':id', id);
            $('#commonModalLabel').text('Edit Project Requirements');
            $('.save_button_span').text('Update Project Requirements');

            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);

                }
            })
        })

         /*********create Project Teams**********/
         $(document).on('click', '#createProjectTeams', function() {
            $('#commonModalLabel').text('Add New Project Team');
            $('.save_button_span').text('Store Project Team');

            $.ajax({
                url: "{!! route('project-teams.create') !!}",
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);

                    var currentDate = new Date();
                    var formattedDate = currentDate.getDate() + '-' + (currentDate.getMonth() + 1) + '-' + currentDate.getFullYear();
                    $('#assign_date').val(formattedDate).datepicker();

                    $( function() {
                        $('#release_date').datepicker();
                    });
                }
            })
        })

         /*********Update Project Teams**********/
         $(document).on('click', '#project_teams_edit', function() {
            var id = $(this).data('id');
            var url = `{!! route('project-teams.edit', ':id') !!}`.replace(':id', id);
            $('#commonModalLabel').text('Edit Project Teams');
            $('.save_button_span').text('Update Project Teams');

            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);

                    $( function() {
                        $('#assign_date').datepicker();
                    });
                    $( function() {
                        $('#release_date').datepicker();
                    });

                }
            })
        })

        $(document).on('click', '.editPayment', function() {
            $('#commonModalLabel').text('Edit Payment');
            $('.save_button_span').text('Update Payment');
            var id = $(this).data('id');
            var url = `{!! route('account-payments.edit', ':id') !!}`.replace(':id', id);

            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                }
            })
        })

        /*********change status**********/
        $("body").on("click", '.changeStatusCustom', function(event) {
            dataString = {
                "id": $(this).data('id'),
                "status": $(this).data('status')
            };
            var UrlValue = $(this).data('url');
            var status = $(this).data('status');
            var changeStatus = $(this);
            var btn = $(this);

            Swal.fire({
                title: 'Are you sure you want to change status?',
                icon: 'warning',
                showDenyButton: true,
                showCancelButton: false,
                confirmButtonText: 'Yes',
                denyButtonText: 'No',
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: UrlValue,
                        method: 'post',
                        data: dataString,
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        success: function(response) {
                            if (response.success) {
                                var ErroMsg = $(this).printErrorMsg(response.message);
                                $(this).Toastshow('success', ErroMsg);
                            } else {
                                var ErroMsg = $(this).printErrorMsg(response.message);
                                if (ErroMsg === '') {
                                    ErroMsg = "Something went wrong!";
                                }
                                $(this).Toastshow('error', ErroMsg);
                            }
                            fetch_status();
                            fetch_prices();
                        },
                        error: function(data) {
                            console.log("error ", data);
                            fetch_status();
                            fetch_prices();
                        }
                    });
                } else if (result.isDenied) {
                    fetch_status();
                    fetch_prices();
                }
                //return false;
            });
            //return false;
        });

        /*********delete data**********/
        $("body").on("click", '.deleteAccountData', function(event) {
            dataString = {
                "id": $(this).data('id')
            };
            var UrlValue = $(this).data('url');
            var btn = $(this);
            //alert(dataValue);
            console.log($('meta[name="csrf-token"]').attr('content'));
            console.log(dataString);

            Swal.fire({
                title: 'Are you sure you want to delete this?',
                icon: 'warning',
                showDenyButton: true,
                showCancelButton: false,
                confirmButtonText: 'Yes',
                denyButtonText: 'No',
            }).then((result) => {
                /* Read more about isConfirmed, isDenied below */
                if (result.isConfirmed) {
                    $.ajax({
                        url: UrlValue,
                        method: 'post',
                        data: {
                            "_token": $('meta[name="csrf-token"]').attr('content'),
                            "id": $(this).data('id'),
                            "account": "{!! $data->id !!}"
                        },
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        beforeSend: function(xhr) {
                            // xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                        },
                        success: function(response) {
                            console.log(response.data);
                            if (response.success) {
                                var ErroMsg = $(this).printErrorMsg(response.message);

                                $(this).Toastshow('success', ErroMsg);

                                if (btn.hasClass('project_teams')) {
                                    fetch_project_teams();
                                } else if (btn.hasClass('project_attachments')) {
                                    fetch_project_attachments();
                                } else if (btn.hasClass('project_requirments')) {
                                    fetch_project_requirments();
                                }  else if (btn.hasClass('budget_project')) {
                                    fetch_budget_project();
                                }
                                console.log('s');
                            } else {
                                var ErroMsg = $(this).printErrorMsg(response.message);
                                $(this).Toastshow('error', ErroMsg);
                            }
                        },
                        error: function(data) {
                            console.log("error ", data);
                        }
                    });
                }
            });
        });
    </script>
@endsection
